file_name
stringlengths 26
96
| text
stringlengths 6.17k
164k
|
|---|---|
crates__analytics__src__clickhouse.rs
|
use std::sync::Arc;
use actix_web::http::StatusCode;
use common_utils::errors::ParsingError;
use error_stack::{report, Report, ResultExt};
use router_env::logger;
use time::PrimitiveDateTime;
use super::{
active_payments::metrics::ActivePaymentsMetricRow,
auth_events::metrics::AuthEventMetricRow,
frm::{filters::FrmFilterRow, metrics::FrmMetricRow},
health_check::HealthCheck,
payment_intents::{filters::PaymentIntentFilterRow, metrics::PaymentIntentMetricRow},
payments::{
distribution::PaymentDistributionRow, filters::PaymentFilterRow, metrics::PaymentMetricRow,
},
query::{Aggregate, ToSql, Window},
refunds::{
distribution::RefundDistributionRow, filters::RefundFilterRow, metrics::RefundMetricRow,
},
sdk_events::{filters::SdkEventFilter, metrics::SdkEventMetricRow},
types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, QueryExecutionError},
};
use crate::{
api_event::{
events::ApiLogsResult,
filters::ApiEventFilter,
metrics::{latency::LatencyAvg, ApiEventMetricRow},
},
auth_events::filters::AuthEventFilterRow,
connector_events::events::ConnectorEventsResult,
disputes::{filters::DisputeFilterRow, metrics::DisputeMetricRow},
outgoing_webhook_event::events::OutgoingWebhookLogsResult,
routing_events::events::RoutingEventsResult,
sdk_events::events::SdkEventsResult,
types::TableEngine,
};
pub type ClickhouseResult<T> = error_stack::Result<T, ClickhouseError>;
#[derive(Clone, Debug)]
pub struct ClickhouseClient {
pub config: Arc<ClickhouseConfig>,
pub database: String,
}
#[derive(Clone, Debug, serde::Deserialize)]
pub struct ClickhouseConfig {
username: String,
password: Option<String>,
host: String,
}
impl Default for ClickhouseConfig {
fn default() -> Self {
Self {
username: "default".to_string(),
password: None,
host: "http://localhost:8123".to_string(),
}
}
}
impl ClickhouseClient {
async fn execute_query(&self, query: &str) -> ClickhouseResult<Vec<serde_json::Value>> {
logger::debug!("Executing query: {query}");
let client = reqwest::Client::new();
let params = CkhQuery {
date_time_output_format: String::from("iso"),
output_format_json_quote_64bit_integers: 0,
database: self.database.clone(),
};
let response = client
.post(&self.config.host)
.query(¶ms)
.basic_auth(self.config.username.clone(), self.config.password.clone())
.body(format!("{query}\nFORMAT JSON"))
.send()
.await
.change_context(ClickhouseError::ConnectionError)?;
logger::debug!(clickhouse_response=?response, query=?query, "Clickhouse response");
if response.status() != StatusCode::OK {
response.text().await.map_or_else(
|er| {
Err(ClickhouseError::ResponseError)
.attach_printable_lazy(|| format!("Error: {er:?}"))
},
|t| Err(report!(ClickhouseError::ResponseNotOK(t))),
)
} else {
Ok(response
.json::<CkhOutput<serde_json::Value>>()
.await
.change_context(ClickhouseError::ResponseError)?
.data)
}
}
}
#[async_trait::async_trait]
impl HealthCheck for ClickhouseClient {
async fn deep_health_check(
&self,
) -> common_utils::errors::CustomResult<(), QueryExecutionError> {
self.execute_query("SELECT 1")
.await
.map(|_| ())
.change_context(QueryExecutionError::DatabaseError)
}
}
#[async_trait::async_trait]
impl AnalyticsDataSource for ClickhouseClient {
type Row = serde_json::Value;
async fn load_results<T>(
&self,
query: &str,
) -> common_utils::errors::CustomResult<Vec<T>, QueryExecutionError>
where
Self: LoadRow<T>,
{
self.execute_query(query)
.await
.change_context(QueryExecutionError::DatabaseError)?
.into_iter()
.map(Self::load_row)
.collect::<Result<Vec<_>, _>>()
.change_context(QueryExecutionError::RowExtractionFailure)
}
fn get_table_engine(table: AnalyticsCollection) -> TableEngine {
match table {
AnalyticsCollection::Payment
| AnalyticsCollection::PaymentSessionized
| AnalyticsCollection::Refund
| AnalyticsCollection::RefundSessionized
| AnalyticsCollection::FraudCheck
| AnalyticsCollection::PaymentIntent
| AnalyticsCollection::PaymentIntentSessionized
| AnalyticsCollection::Authentications
| AnalyticsCollection::Dispute => {
TableEngine::CollapsingMergeTree { sign: "sign_flag" }
}
AnalyticsCollection::DisputeSessionized => {
TableEngine::CollapsingMergeTree { sign: "sign_flag" }
}
AnalyticsCollection::SdkEvents
| AnalyticsCollection::SdkEventsAnalytics
| AnalyticsCollection::ApiEvents
| AnalyticsCollection::ApiPayoutEvents
| AnalyticsCollection::ConnectorEvents
| AnalyticsCollection::ConnectorPayoutEvents
| AnalyticsCollection::RoutingEvents
| AnalyticsCollection::ApiEventsAnalytics
| AnalyticsCollection::OutgoingWebhookEvent
| AnalyticsCollection::OutgoingWebhookPayoutEvent
| AnalyticsCollection::ActivePaymentsAnalytics => TableEngine::BasicTree,
}
}
}
impl<T, E> LoadRow<T> for ClickhouseClient
where
Self::Row: TryInto<T, Error = Report<E>>,
{
fn load_row(row: Self::Row) -> common_utils::errors::CustomResult<T, QueryExecutionError> {
row.try_into()
.map_err(|error| error.change_context(QueryExecutionError::RowExtractionFailure))
}
}
impl super::payments::filters::PaymentFilterAnalytics for ClickhouseClient {}
impl super::payments::metrics::PaymentMetricAnalytics for ClickhouseClient {}
impl super::payments::distribution::PaymentDistributionAnalytics for ClickhouseClient {}
impl super::payment_intents::filters::PaymentIntentFilterAnalytics for ClickhouseClient {}
impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for ClickhouseClient {}
impl super::refunds::metrics::RefundMetricAnalytics for ClickhouseClient {}
impl super::refunds::filters::RefundFilterAnalytics for ClickhouseClient {}
impl super::refunds::distribution::RefundDistributionAnalytics for ClickhouseClient {}
impl super::frm::metrics::FrmMetricAnalytics for ClickhouseClient {}
impl super::frm::filters::FrmFilterAnalytics for ClickhouseClient {}
impl super::sdk_events::filters::SdkEventFilterAnalytics for ClickhouseClient {}
impl super::sdk_events::metrics::SdkEventMetricAnalytics for ClickhouseClient {}
impl super::sdk_events::events::SdkEventsFilterAnalytics for ClickhouseClient {}
impl super::active_payments::metrics::ActivePaymentsMetricAnalytics for ClickhouseClient {}
impl super::auth_events::metrics::AuthEventMetricAnalytics for ClickhouseClient {}
impl super::auth_events::filters::AuthEventFilterAnalytics for ClickhouseClient {}
impl super::api_event::events::ApiLogsFilterAnalytics for ClickhouseClient {}
impl super::api_event::filters::ApiEventFilterAnalytics for ClickhouseClient {}
impl super::api_event::metrics::ApiEventMetricAnalytics for ClickhouseClient {}
impl super::connector_events::events::ConnectorEventLogAnalytics for ClickhouseClient {}
impl super::routing_events::events::RoutingEventLogAnalytics for ClickhouseClient {}
impl super::outgoing_webhook_event::events::OutgoingWebhookLogsFilterAnalytics
for ClickhouseClient
{
}
impl super::disputes::filters::DisputeFilterAnalytics for ClickhouseClient {}
impl super::disputes::metrics::DisputeMetricAnalytics for ClickhouseClient {}
#[derive(Debug, serde::Serialize)]
struct CkhQuery {
date_time_output_format: String,
output_format_json_quote_64bit_integers: u8,
database: String,
}
#[derive(Debug, serde::Deserialize)]
struct CkhOutput<T> {
data: Vec<T>,
}
impl TryInto<ApiLogsResult> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<ApiLogsResult, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse ApiLogsResult in clickhouse results",
))
}
}
impl TryInto<SdkEventsResult> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<SdkEventsResult, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse SdkEventsResult in clickhouse results",
))
}
}
impl TryInto<ConnectorEventsResult> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<ConnectorEventsResult, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse ConnectorEventsResult in clickhouse results",
))
}
}
impl TryInto<RoutingEventsResult> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<RoutingEventsResult, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse RoutingEventsResult in clickhouse results",
))
}
}
impl TryInto<PaymentMetricRow> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<PaymentMetricRow, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse PaymentMetricRow in clickhouse results",
))
}
}
impl TryInto<PaymentDistributionRow> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<PaymentDistributionRow, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse PaymentDistributionRow in clickhouse results",
))
}
}
impl TryInto<PaymentFilterRow> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<PaymentFilterRow, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse FilterRow in clickhouse results",
))
}
}
impl TryInto<PaymentIntentMetricRow> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<PaymentIntentMetricRow, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse PaymentIntentMetricRow in clickhouse results",
))
}
}
impl TryInto<PaymentIntentFilterRow> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<PaymentIntentFilterRow, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse PaymentIntentFilterRow in clickhouse results",
))
}
}
impl TryInto<RefundMetricRow> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<RefundMetricRow, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse RefundMetricRow in clickhouse results",
))
}
}
impl TryInto<RefundFilterRow> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<RefundFilterRow, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse RefundFilterRow in clickhouse results",
))
}
}
impl TryInto<RefundDistributionRow> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<RefundDistributionRow, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse RefundDistributionRow in clickhouse results",
))
}
}
impl TryInto<FrmMetricRow> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<FrmMetricRow, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse FrmMetricRow in clickhouse results",
))
}
}
impl TryInto<FrmFilterRow> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<FrmFilterRow, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse FrmFilterRow in clickhouse results",
))
}
}
impl TryInto<DisputeMetricRow> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<DisputeMetricRow, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse DisputeMetricRow in clickhouse results",
))
}
}
impl TryInto<DisputeFilterRow> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<DisputeFilterRow, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse DisputeFilterRow in clickhouse results",
))
}
}
impl TryInto<ApiEventMetricRow> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<ApiEventMetricRow, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse ApiEventMetricRow in clickhouse results",
))
}
}
impl TryInto<LatencyAvg> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<LatencyAvg, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse LatencyAvg in clickhouse results",
))
}
}
impl TryInto<SdkEventMetricRow> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<SdkEventMetricRow, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse SdkEventMetricRow in clickhouse results",
))
}
}
impl TryInto<SdkEventFilter> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<SdkEventFilter, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse SdkEventFilter in clickhouse results",
))
}
}
impl TryInto<AuthEventMetricRow> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<AuthEventMetricRow, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse AuthEventMetricRow in clickhouse results",
))
}
}
impl TryInto<AuthEventFilterRow> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<AuthEventFilterRow, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse AuthEventFilterRow in clickhouse results",
))
}
}
impl TryInto<ApiEventFilter> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<ApiEventFilter, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse ApiEventFilter in clickhouse results",
))
}
}
impl TryInto<OutgoingWebhookLogsResult> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<OutgoingWebhookLogsResult, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse OutgoingWebhookLogsResult in clickhouse results",
))
}
}
impl TryInto<ActivePaymentsMetricRow> for serde_json::Value {
type Error = Report<ParsingError>;
fn try_into(self) -> Result<ActivePaymentsMetricRow, Self::Error> {
serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
"Failed to parse ActivePaymentsMetricRow in clickhouse results",
))
}
}
impl ToSql<ClickhouseClient> for PrimitiveDateTime {
fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
Ok(self.assume_utc().unix_timestamp().to_string())
}
}
impl ToSql<ClickhouseClient> for AnalyticsCollection {
fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
match self {
Self::Payment => Ok("payment_attempts".to_string()),
Self::PaymentSessionized => Ok("sessionizer_payment_attempts".to_string()),
Self::Refund => Ok("refunds".to_string()),
Self::RefundSessionized => Ok("sessionizer_refunds".to_string()),
Self::FraudCheck => Ok("fraud_check".to_string()),
Self::SdkEvents => Ok("sdk_events_audit".to_string()),
Self::SdkEventsAnalytics => Ok("sdk_events".to_string()),
Self::ApiEvents => Ok("api_events_audit".to_string()),
Self::ApiPayoutEvents => Ok("api_events_payout_audit".to_string()),
Self::ApiEventsAnalytics => Ok("api_events".to_string()),
Self::PaymentIntent => Ok("payment_intents".to_string()),
Self::PaymentIntentSessionized => Ok("sessionizer_payment_intents".to_string()),
Self::ConnectorEvents => Ok("connector_events_audit".to_string()),
Self::ConnectorPayoutEvents => Ok("connector_events_payout_audit".to_string()),
Self::OutgoingWebhookEvent => Ok("outgoing_webhook_events_audit".to_string()),
Self::OutgoingWebhookPayoutEvent => {
Ok("outgoing_webhook_events_payout_audit".to_string())
}
Self::Dispute => Ok("dispute".to_string()),
Self::DisputeSessionized => Ok("sessionizer_dispute".to_string()),
Self::ActivePaymentsAnalytics => Ok("active_payments".to_string()),
Self::Authentications => Ok("authentications".to_string()),
Self::RoutingEvents => Ok("routing_events_audit".to_string()),
}
}
}
impl<T> ToSql<ClickhouseClient> for Aggregate<T>
where
T: ToSql<ClickhouseClient>,
{
fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
Ok(match self {
Self::Count { field: _, alias } => {
let query = match table_engine {
TableEngine::CollapsingMergeTree { sign } => format!("sum({sign})"),
TableEngine::BasicTree => "count(*)".to_string(),
};
format!(
"{query}{}",
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}"))
)
}
Self::Sum { field, alias } => {
let query = match table_engine {
TableEngine::CollapsingMergeTree { sign } => format!(
"sum({sign} * {})",
field
.to_sql(table_engine)
.attach_printable("Failed to sum aggregate")?
),
TableEngine::BasicTree => format!(
"sum({})",
field
.to_sql(table_engine)
.attach_printable("Failed to sum aggregate")?
),
};
format!(
"{query}{}",
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}"))
)
}
Self::Min { field, alias } => {
format!(
"min({}){}",
field
.to_sql(table_engine)
.attach_printable("Failed to min aggregate")?,
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}"))
)
}
Self::Max { field, alias } => {
format!(
"max({}){}",
field
.to_sql(table_engine)
.attach_printable("Failed to max aggregate")?,
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}"))
)
}
Self::Percentile {
field,
alias,
percentile,
} => {
format!(
"quantilesExact(0.{})({})[1]{}",
percentile.map_or_else(|| "50".to_owned(), |percentile| percentile.to_string()),
field
.to_sql(table_engine)
.attach_printable("Failed to percentile aggregate")?,
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}"))
)
}
Self::DistinctCount { field, alias } => {
format!(
"count(distinct {}){}",
field
.to_sql(table_engine)
.attach_printable("Failed to percentile aggregate")?,
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}"))
)
}
})
}
}
impl<T> ToSql<ClickhouseClient> for Window<T>
where
T: ToSql<ClickhouseClient>,
{
fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
Ok(match self {
Self::Sum {
field,
partition_by,
order_by,
alias,
} => {
format!(
"sum({}) over ({}{}){}",
field
.to_sql(table_engine)
.attach_printable("Failed to sum window")?,
partition_by.as_ref().map_or_else(
|| "".to_owned(),
|partition_by| format!("partition by {}", partition_by.to_owned())
),
order_by.as_ref().map_or_else(
|| "".to_owned(),
|(order_column, order)| format!(
" order by {} {}",
order_column.to_owned(),
order
)
),
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}"))
)
}
Self::RowNumber {
field: _,
partition_by,
order_by,
alias,
} => {
format!(
"row_number() over ({}{}){}",
partition_by.as_ref().map_or_else(
|| "".to_owned(),
|partition_by| format!("partition by {}", partition_by.to_owned())
),
order_by.as_ref().map_or_else(
|| "".to_owned(),
|(order_column, order)| format!(
" order by {} {}",
order_column.to_owned(),
order
)
),
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}"))
)
}
})
}
}
#[derive(Debug, thiserror::Error)]
pub enum ClickhouseError {
#[error("Clickhouse connection error")]
ConnectionError,
#[error("Clickhouse NON-200 response content: '{0}'")]
ResponseNotOK(String),
#[error("Clickhouse response error")]
ResponseError,
}
|
crates__analytics__src__sqlx.rs
|
use std::{fmt::Display, str::FromStr};
use api_models::{
analytics::{frm::FrmTransactionType, refunds::RefundType},
enums::{DisputeStage, DisputeStatus},
};
use common_enums::{
AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus,
};
use common_utils::{
errors::{CustomResult, ParsingError},
DbConnectionParams,
};
use diesel_models::enums::{
AttemptStatus, AuthenticationType, Currency, FraudCheckStatus, IntentStatus, PaymentMethod,
RefundStatus, RoutingApproach,
};
use error_stack::ResultExt;
use sqlx::{
postgres::{PgArgumentBuffer, PgPoolOptions, PgRow, PgTypeInfo, PgValueRef},
Decode, Encode,
Error::ColumnNotFound,
FromRow, Pool, Postgres, Row,
};
use storage_impl::config::Database;
use time::PrimitiveDateTime;
use super::{
health_check::HealthCheck,
query::{Aggregate, ToSql, Window},
types::{
AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, QueryExecutionError,
TableEngine,
},
};
#[derive(Debug, Clone)]
pub struct SqlxClient {
pool: Pool<Postgres>,
}
impl Default for SqlxClient {
fn default() -> Self {
let database_url = format!(
"postgres://{}:{}@{}:{}/{}",
"db_user", "db_pass", "localhost", 5432, "hyperswitch_db"
);
Self {
#[allow(clippy::expect_used)]
pool: PgPoolOptions::new()
.connect_lazy(&database_url)
.expect("SQLX Pool Creation failed"),
}
}
}
impl SqlxClient {
pub async fn from_conf(conf: &Database, schema: &str) -> Self {
let database_url = conf.get_database_url(schema);
#[allow(clippy::expect_used)]
let pool = PgPoolOptions::new()
.max_connections(conf.pool_size)
.acquire_timeout(std::time::Duration::from_secs(conf.connection_timeout))
.connect_lazy(&database_url)
.expect("SQLX Pool Creation failed");
Self { pool }
}
}
pub trait DbType {
fn name() -> &'static str;
}
macro_rules! db_type {
($a: ident, $str: tt) => {
impl DbType for $a {
fn name() -> &'static str {
stringify!($str)
}
}
};
($a:ident) => {
impl DbType for $a {
fn name() -> &'static str {
stringify!($a)
}
}
};
}
db_type!(Currency);
db_type!(AuthenticationType);
db_type!(AttemptStatus);
db_type!(IntentStatus);
db_type!(PaymentMethod, TEXT);
db_type!(RefundStatus);
db_type!(RefundType);
db_type!(FraudCheckStatus);
db_type!(FrmTransactionType);
db_type!(DisputeStage);
db_type!(DisputeStatus);
db_type!(AuthenticationStatus);
db_type!(TransactionStatus);
db_type!(AuthenticationConnectors);
db_type!(DecoupledAuthenticationType);
db_type!(RoutingApproach);
impl<'q, Type> Encode<'q, Postgres> for DBEnumWrapper<Type>
where
Type: DbType + FromStr + Display,
{
fn encode_by_ref(
&self,
buf: &mut PgArgumentBuffer,
) -> Result<sqlx::encode::IsNull, Box<dyn std::error::Error + Send + Sync + 'static>> {
<String as Encode<'q, Postgres>>::encode(self.0.to_string(), buf)
}
fn size_hint(&self) -> usize {
<String as Encode<'q, Postgres>>::size_hint(&self.0.to_string())
}
}
impl<'r, Type> Decode<'r, Postgres> for DBEnumWrapper<Type>
where
Type: DbType + FromStr + Display,
{
fn decode(
value: PgValueRef<'r>,
) -> Result<Self, Box<dyn std::error::Error + 'static + Send + Sync>> {
let str_value = <&'r str as Decode<'r, Postgres>>::decode(value)?;
Type::from_str(str_value).map(DBEnumWrapper).or(Err(format!(
"invalid value {:?} for enum {}",
str_value,
Type::name()
)
.into()))
}
}
impl<Type> sqlx::Type<Postgres> for DBEnumWrapper<Type>
where
Type: DbType + FromStr + Display,
{
fn type_info() -> PgTypeInfo {
PgTypeInfo::with_name(Type::name())
}
}
impl<T> LoadRow<T> for SqlxClient
where
for<'a> T: FromRow<'a, PgRow>,
{
fn load_row(row: PgRow) -> CustomResult<T, QueryExecutionError> {
T::from_row(&row).change_context(QueryExecutionError::RowExtractionFailure)
}
}
impl super::payments::filters::PaymentFilterAnalytics for SqlxClient {}
impl super::payments::metrics::PaymentMetricAnalytics for SqlxClient {}
impl super::payments::distribution::PaymentDistributionAnalytics for SqlxClient {}
impl super::payment_intents::filters::PaymentIntentFilterAnalytics for SqlxClient {}
impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for SqlxClient {}
impl super::refunds::metrics::RefundMetricAnalytics for SqlxClient {}
impl super::refunds::filters::RefundFilterAnalytics for SqlxClient {}
impl super::refunds::distribution::RefundDistributionAnalytics for SqlxClient {}
impl super::disputes::filters::DisputeFilterAnalytics for SqlxClient {}
impl super::disputes::metrics::DisputeMetricAnalytics for SqlxClient {}
impl super::frm::metrics::FrmMetricAnalytics for SqlxClient {}
impl super::frm::filters::FrmFilterAnalytics for SqlxClient {}
impl super::auth_events::metrics::AuthEventMetricAnalytics for SqlxClient {}
impl super::auth_events::filters::AuthEventFilterAnalytics for SqlxClient {}
#[async_trait::async_trait]
impl AnalyticsDataSource for SqlxClient {
type Row = PgRow;
async fn load_results<T>(&self, query: &str) -> CustomResult<Vec<T>, QueryExecutionError>
where
Self: LoadRow<T>,
{
sqlx::query(&format!("{query};"))
.fetch_all(&self.pool)
.await
.change_context(QueryExecutionError::DatabaseError)
.attach_printable_lazy(|| format!("Failed to run query {query}"))?
.into_iter()
.map(Self::load_row)
.collect::<Result<Vec<_>, _>>()
.change_context(QueryExecutionError::RowExtractionFailure)
}
}
#[async_trait::async_trait]
impl HealthCheck for SqlxClient {
async fn deep_health_check(&self) -> CustomResult<(), QueryExecutionError> {
sqlx::query("SELECT 1")
.fetch_all(&self.pool)
.await
.map(|_| ())
.change_context(QueryExecutionError::DatabaseError)
}
}
impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow {
fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
let authentication_status: Option<DBEnumWrapper<AuthenticationStatus>> =
row.try_get("authentication_status").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let trans_status: Option<DBEnumWrapper<TransactionStatus>> =
row.try_get("trans_status").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> =
row.try_get("authentication_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>> = row
.try_get("authentication_connector")
.or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let message_version: Option<String> =
row.try_get("message_version").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let platform: Option<String> = row.try_get("platform").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let acs_reference_number: Option<String> =
row.try_get("acs_reference_number").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let count: Option<i64> = row.try_get("count").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
// Removing millisecond precision to get accurate diffs against clickhouse
let start_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("start_bucket")?
.and_then(|dt| dt.replace_millisecond(0).ok());
let end_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("end_bucket")?
.and_then(|dt| dt.replace_millisecond(0).ok());
let mcc: Option<String> = row.try_get("mcc").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let currency: Option<DBEnumWrapper<Currency>> =
row.try_get("currency").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let merchant_country: Option<String> =
row.try_get("merchant_country").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let billing_country: Option<String> =
row.try_get("billing_country").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let shipping_country: Option<String> =
row.try_get("shipping_country").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let issuer_country: Option<String> =
row.try_get("issuer_country").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let earliest_supported_version: Option<String> = row
.try_get("earliest_supported_version")
.or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let latest_supported_version: Option<String> = row
.try_get("latest_supported_version")
.or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let whitelist_decision: Option<bool> =
row.try_get("whitelist_decision").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let device_manufacturer: Option<String> =
row.try_get("device_manufacturer").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let device_type: Option<String> = row.try_get("device_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let device_brand: Option<String> = row.try_get("device_brand").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let device_os: Option<String> = row.try_get("device_os").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let device_display: Option<String> =
row.try_get("device_display").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let browser_name: Option<String> = row.try_get("browser_name").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let browser_version: Option<String> =
row.try_get("browser_version").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let issuer_id: Option<String> = row.try_get("issuer_id").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let scheme_name: Option<String> = row.try_get("scheme_name").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let exemption_requested: Option<bool> =
row.try_get("exemption_requested").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let exemption_accepted: Option<bool> =
row.try_get("exemption_accepted").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
Ok(Self {
authentication_status,
trans_status,
authentication_type,
error_message,
authentication_connector,
message_version,
acs_reference_number,
platform,
count,
start_bucket,
end_bucket,
mcc,
currency,
merchant_country,
billing_country,
shipping_country,
issuer_country,
earliest_supported_version,
latest_supported_version,
whitelist_decision,
device_manufacturer,
device_type,
device_brand,
device_os,
device_display,
browser_name,
browser_version,
issuer_id,
scheme_name,
exemption_requested,
exemption_accepted,
})
}
}
impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow {
fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
let authentication_status: Option<DBEnumWrapper<AuthenticationStatus>> =
row.try_get("authentication_status").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let trans_status: Option<DBEnumWrapper<TransactionStatus>> =
row.try_get("trans_status").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> =
row.try_get("authentication_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>> = row
.try_get("authentication_connector")
.or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let message_version: Option<String> =
row.try_get("message_version").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let acs_reference_number: Option<String> =
row.try_get("acs_reference_number").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let platform: Option<String> = row.try_get("platform").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let mcc: Option<String> = row.try_get("mcc").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let currency: Option<DBEnumWrapper<Currency>> =
row.try_get("currency").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let merchant_country: Option<String> =
row.try_get("merchant_country").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let billing_country: Option<String> =
row.try_get("billing_country").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let shipping_country: Option<String> =
row.try_get("shipping_country").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let issuer_country: Option<String> =
row.try_get("issuer_country").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let earliest_supported_version: Option<String> = row
.try_get("earliest_supported_version")
.or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let latest_supported_version: Option<String> = row
.try_get("latest_supported_version")
.or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let whitelist_decision: Option<bool> =
row.try_get("whitelist_decision").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let device_manufacturer: Option<String> =
row.try_get("device_manufacturer").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let device_type: Option<String> = row.try_get("device_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let device_brand: Option<String> = row.try_get("device_brand").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let device_os: Option<String> = row.try_get("device_os").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let device_display: Option<String> =
row.try_get("device_display").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let browser_name: Option<String> = row.try_get("browser_name").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let browser_version: Option<String> =
row.try_get("browser_version").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let issuer_id: Option<String> = row.try_get("issuer_id").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let scheme_name: Option<String> = row.try_get("scheme_name").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let exemption_requested: Option<bool> =
row.try_get("exemption_requested").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let exemption_accepted: Option<bool> =
row.try_get("exemption_accepted").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
Ok(Self {
authentication_status,
trans_status,
authentication_type,
error_message,
authentication_connector,
message_version,
platform,
acs_reference_number,
mcc,
currency,
merchant_country,
billing_country,
shipping_country,
issuer_country,
earliest_supported_version,
latest_supported_version,
whitelist_decision,
device_manufacturer,
device_type,
device_brand,
device_os,
device_display,
browser_name,
browser_version,
issuer_id,
scheme_name,
exemption_requested,
exemption_accepted,
})
}
}
impl<'a> FromRow<'a, PgRow> for super::refunds::metrics::RefundMetricRow {
fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
let currency: Option<DBEnumWrapper<Currency>> =
row.try_get("currency").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let refund_status: Option<DBEnumWrapper<RefundStatus>> =
row.try_get("refund_status").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let connector: Option<String> = row.try_get("connector").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let refund_type: Option<DBEnumWrapper<RefundType>> =
row.try_get("refund_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let refund_reason: Option<String> = row.try_get("refund_reason").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let refund_error_message: Option<String> =
row.try_get("refund_error_message").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let count: Option<i64> = row.try_get("count").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
// Removing millisecond precision to get accurate diffs against clickhouse
let start_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("start_bucket")?
.and_then(|dt| dt.replace_millisecond(0).ok());
let end_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("end_bucket")?
.and_then(|dt| dt.replace_millisecond(0).ok());
Ok(Self {
currency,
refund_status,
connector,
refund_type,
profile_id,
refund_reason,
refund_error_message,
total,
count,
start_bucket,
end_bucket,
})
}
}
impl<'a> FromRow<'a, PgRow> for super::frm::metrics::FrmMetricRow {
fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
let frm_name: Option<String> = row.try_get("frm_name").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let frm_status: Option<DBEnumWrapper<FraudCheckStatus>> =
row.try_get("frm_status").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let frm_transaction_type: Option<DBEnumWrapper<FrmTransactionType>> =
row.try_get("frm_transaction_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let count: Option<i64> = row.try_get("count").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
// Removing millisecond precision to get accurate diffs against clickhouse
let start_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("start_bucket")?
.and_then(|dt| dt.replace_millisecond(0).ok());
let end_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("end_bucket")?
.and_then(|dt| dt.replace_millisecond(0).ok());
Ok(Self {
frm_name,
frm_status,
frm_transaction_type,
total,
count,
start_bucket,
end_bucket,
})
}
}
impl<'a> FromRow<'a, PgRow> for super::payments::metrics::PaymentMetricRow {
fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
let currency: Option<DBEnumWrapper<Currency>> =
row.try_get("currency").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let status: Option<DBEnumWrapper<AttemptStatus>> =
row.try_get("status").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let connector: Option<String> = row.try_get("connector").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let authentication_type: Option<DBEnumWrapper<AuthenticationType>> =
row.try_get("authentication_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let payment_method: Option<String> =
row.try_get("payment_method").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let payment_method_type: Option<String> =
row.try_get("payment_method_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let client_source: Option<String> = row.try_get("client_source").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let client_version: Option<String> =
row.try_get("client_version").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let first_attempt: Option<bool> = row.try_get("first_attempt").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let routing_approach: Option<DBEnumWrapper<RoutingApproach>> =
row.try_get("routing_approach").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let signature_network: Option<String> =
row.try_get("signature_network").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let is_issuer_regulated: Option<bool> =
row.try_get("is_issuer_regulated").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let is_debit_routed: Option<bool> =
row.try_get("is_debit_routed").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let count: Option<i64> = row.try_get("count").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
// Removing millisecond precision to get accurate diffs against clickhouse
let start_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("start_bucket")?
.and_then(|dt| dt.replace_millisecond(0).ok());
let end_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("end_bucket")?
.and_then(|dt| dt.replace_millisecond(0).ok());
Ok(Self {
currency,
status,
connector,
authentication_type,
payment_method,
payment_method_type,
client_source,
client_version,
profile_id,
card_network,
merchant_id,
card_last_4,
card_issuer,
error_reason,
first_attempt,
routing_approach,
signature_network,
is_issuer_regulated,
is_debit_routed,
total,
count,
start_bucket,
end_bucket,
})
}
}
impl<'a> FromRow<'a, PgRow> for super::payments::distribution::PaymentDistributionRow {
fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
let currency: Option<DBEnumWrapper<Currency>> =
row.try_get("currency").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let status: Option<DBEnumWrapper<AttemptStatus>> =
row.try_get("status").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let connector: Option<String> = row.try_get("connector").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let authentication_type: Option<DBEnumWrapper<AuthenticationType>> =
row.try_get("authentication_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let payment_method: Option<String> =
row.try_get("payment_method").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let payment_method_type: Option<String> =
row.try_get("payment_method_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let client_source: Option<String> = row.try_get("client_source").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let client_version: Option<String> =
row.try_get("client_version").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let routing_approach: Option<DBEnumWrapper<RoutingApproach>> =
row.try_get("routing_approach").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let signature_network: Option<String> =
row.try_get("signature_network").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let is_issuer_regulated: Option<bool> =
row.try_get("is_issuer_regulated").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let is_debit_routed: Option<bool> =
row.try_get("is_debit_routed").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let count: Option<i64> = row.try_get("count").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let first_attempt: Option<bool> = row.try_get("first_attempt").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
// Removing millisecond precision to get accurate diffs against clickhouse
let start_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("start_bucket")?
.and_then(|dt| dt.replace_millisecond(0).ok());
let end_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("end_bucket")?
.and_then(|dt| dt.replace_millisecond(0).ok());
Ok(Self {
currency,
status,
connector,
authentication_type,
payment_method,
payment_method_type,
client_source,
client_version,
profile_id,
card_network,
merchant_id,
card_last_4,
card_issuer,
error_reason,
first_attempt,
total,
count,
error_message,
routing_approach,
signature_network,
is_issuer_regulated,
is_debit_routed,
start_bucket,
end_bucket,
})
}
}
impl<'a> FromRow<'a, PgRow> for super::payments::filters::PaymentFilterRow {
fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
let currency: Option<DBEnumWrapper<Currency>> =
row.try_get("currency").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let status: Option<DBEnumWrapper<AttemptStatus>> =
row.try_get("status").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let connector: Option<String> = row.try_get("connector").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let authentication_type: Option<DBEnumWrapper<AuthenticationType>> =
row.try_get("authentication_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let payment_method: Option<String> =
row.try_get("payment_method").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let payment_method_type: Option<String> =
row.try_get("payment_method_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let client_source: Option<String> = row.try_get("client_source").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let client_version: Option<String> =
row.try_get("client_version").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let first_attempt: Option<bool> = row.try_get("first_attempt").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let routing_approach: Option<DBEnumWrapper<RoutingApproach>> =
row.try_get("routing_approach").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let signature_network: Option<String> =
row.try_get("signature_network").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let is_issuer_regulated: Option<bool> =
row.try_get("is_issuer_regulated").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let is_debit_routed: Option<bool> =
row.try_get("is_debit_routed").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
Ok(Self {
currency,
status,
connector,
authentication_type,
payment_method,
payment_method_type,
client_source,
client_version,
profile_id,
card_network,
merchant_id,
card_last_4,
card_issuer,
error_reason,
first_attempt,
routing_approach,
signature_network,
is_issuer_regulated,
is_debit_routed,
})
}
}
impl<'a> FromRow<'a, PgRow> for super::payment_intents::metrics::PaymentIntentMetricRow {
fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
let status: Option<DBEnumWrapper<IntentStatus>> =
row.try_get("status").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let currency: Option<DBEnumWrapper<Currency>> =
row.try_get("currency").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let connector: Option<String> = row.try_get("connector").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let authentication_type: Option<DBEnumWrapper<AuthenticationType>> =
row.try_get("authentication_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let payment_method: Option<String> =
row.try_get("payment_method").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let payment_method_type: Option<String> =
row.try_get("payment_method_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let count: Option<i64> = row.try_get("count").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let first_attempt: Option<i64> = row.try_get("first_attempt").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
// Removing millisecond precision to get accurate diffs against clickhouse
let start_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("start_bucket")?
.and_then(|dt| dt.replace_millisecond(0).ok());
let end_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("end_bucket")?
.and_then(|dt| dt.replace_millisecond(0).ok());
Ok(Self {
status,
currency,
profile_id,
connector,
authentication_type,
payment_method,
payment_method_type,
card_network,
merchant_id,
card_last_4,
card_issuer,
error_reason,
first_attempt,
total,
count,
start_bucket,
end_bucket,
})
}
}
impl<'a> FromRow<'a, PgRow> for super::payment_intents::filters::PaymentIntentFilterRow {
fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
let status: Option<DBEnumWrapper<IntentStatus>> =
row.try_get("status").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let currency: Option<DBEnumWrapper<Currency>> =
row.try_get("currency").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let connector: Option<String> = row.try_get("connector").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let authentication_type: Option<DBEnumWrapper<AuthenticationType>> =
row.try_get("authentication_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let payment_method: Option<String> =
row.try_get("payment_method").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let payment_method_type: Option<String> =
row.try_get("payment_method_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let customer_id: Option<String> = row.try_get("customer_id").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
Ok(Self {
status,
currency,
profile_id,
connector,
authentication_type,
payment_method,
payment_method_type,
card_network,
merchant_id,
card_last_4,
card_issuer,
error_reason,
customer_id,
})
}
}
impl<'a> FromRow<'a, PgRow> for super::refunds::filters::RefundFilterRow {
fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
let currency: Option<DBEnumWrapper<Currency>> =
row.try_get("currency").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let refund_status: Option<DBEnumWrapper<RefundStatus>> =
row.try_get("refund_status").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let connector: Option<String> = row.try_get("connector").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let refund_type: Option<DBEnumWrapper<RefundType>> =
row.try_get("refund_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let refund_reason: Option<String> = row.try_get("refund_reason").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let refund_error_message: Option<String> =
row.try_get("refund_error_message").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
Ok(Self {
currency,
refund_status,
connector,
refund_type,
profile_id,
refund_reason,
refund_error_message,
})
}
}
impl<'a> FromRow<'a, PgRow> for super::refunds::distribution::RefundDistributionRow {
fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
let currency: Option<DBEnumWrapper<Currency>> =
row.try_get("currency").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let refund_status: Option<DBEnumWrapper<RefundStatus>> =
row.try_get("refund_status").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let connector: Option<String> = row.try_get("connector").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let refund_type: Option<DBEnumWrapper<RefundType>> =
row.try_get("refund_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let count: Option<i64> = row.try_get("count").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let refund_reason: Option<String> = row.try_get("refund_reason").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let refund_error_message: Option<String> =
row.try_get("refund_error_message").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
// Removing millisecond precision to get accurate diffs against clickhouse
let start_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("start_bucket")?
.and_then(|dt| dt.replace_millisecond(0).ok());
let end_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("end_bucket")?
.and_then(|dt| dt.replace_millisecond(0).ok());
Ok(Self {
currency,
refund_status,
connector,
refund_type,
profile_id,
total,
count,
refund_reason,
refund_error_message,
start_bucket,
end_bucket,
})
}
}
impl<'a> FromRow<'a, PgRow> for super::frm::filters::FrmFilterRow {
fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
let frm_name: Option<String> = row.try_get("frm_name").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let frm_status: Option<DBEnumWrapper<FraudCheckStatus>> =
row.try_get("frm_status").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let frm_transaction_type: Option<DBEnumWrapper<FrmTransactionType>> =
row.try_get("frm_transaction_type").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
Ok(Self {
frm_name,
frm_status,
frm_transaction_type,
})
}
}
impl<'a> FromRow<'a, PgRow> for super::disputes::filters::DisputeFilterRow {
fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
let dispute_stage: Option<String> = row.try_get("dispute_stage").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let dispute_status: Option<String> =
row.try_get("dispute_status").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let connector: Option<String> = row.try_get("connector").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let connector_status: Option<String> =
row.try_get("connector_status").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let currency: Option<DBEnumWrapper<Currency>> =
row.try_get("currency").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
Ok(Self {
dispute_stage,
dispute_status,
connector,
connector_status,
currency,
})
}
}
impl<'a> FromRow<'a, PgRow> for super::disputes::metrics::DisputeMetricRow {
fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
let dispute_stage: Option<DBEnumWrapper<DisputeStage>> =
row.try_get("dispute_stage").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let dispute_status: Option<DBEnumWrapper<DisputeStatus>> =
row.try_get("dispute_status").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let connector: Option<String> = row.try_get("connector").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let currency: Option<DBEnumWrapper<Currency>> =
row.try_get("currency").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
let count: Option<i64> = row.try_get("count").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
// Removing millisecond precision to get accurate diffs against clickhouse
let start_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("start_bucket")?
.and_then(|dt| dt.replace_millisecond(0).ok());
let end_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("end_bucket")?
.and_then(|dt| dt.replace_millisecond(0).ok());
Ok(Self {
dispute_stage,
dispute_status,
connector,
currency,
total,
count,
start_bucket,
end_bucket,
})
}
}
impl ToSql<SqlxClient> for PrimitiveDateTime {
fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
Ok(self.to_string())
}
}
impl ToSql<SqlxClient> for AnalyticsCollection {
fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
match self {
Self::Payment => Ok("payment_attempt".to_string()),
Self::PaymentSessionized => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("PaymentSessionized table is not implemented for Sqlx"))?,
Self::Refund => Ok("refund".to_string()),
Self::RefundSessionized => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("RefundSessionized table is not implemented for Sqlx"))?,
Self::SdkEvents => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("SdkEventsAudit table is not implemented for Sqlx"))?,
Self::SdkEventsAnalytics => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("SdkEvents table is not implemented for Sqlx"))?,
Self::ApiEvents => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("ApiEvents table is not implemented for Sqlx"))?,
Self::ApiPayoutEvents => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("ApiPayoutEvents table is not implemented for Sqlx"))?,
Self::FraudCheck => Ok("fraud_check".to_string()),
Self::PaymentIntent => Ok("payment_intent".to_string()),
Self::PaymentIntentSessionized => Err(error_stack::report!(
ParsingError::UnknownError
)
.attach_printable("PaymentIntentSessionized table is not implemented for Sqlx"))?,
Self::ConnectorEvents => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("ConnectorEvents table is not implemented for Sqlx"))?,
Self::ConnectorPayoutEvents => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("ConnectorPayoutEvents table is not implemented for Sqlx"))?,
Self::ApiEventsAnalytics => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("ApiEvents table is not implemented for Sqlx"))?,
Self::ActivePaymentsAnalytics => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("ActivePaymentsAnalytics table is not implemented for Sqlx"))?,
Self::OutgoingWebhookEvent => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("OutgoingWebhookEvents table is not implemented for Sqlx"))?,
Self::OutgoingWebhookPayoutEvent => Err(error_stack::report!(
ParsingError::UnknownError
)
.attach_printable("OutgoingWebhookPayoutEvents table is not implemented for Sqlx"))?,
Self::Dispute => Ok("dispute".to_string()),
Self::DisputeSessionized => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("DisputeSessionized table is not implemented for Sqlx"))?,
Self::Authentications => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("Authentications table is not implemented for Sqlx"))?,
Self::RoutingEvents => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("RoutingEvents table is not implemented for Sqlx"))?,
}
}
}
impl<T> ToSql<SqlxClient> for Aggregate<T>
where
T: ToSql<SqlxClient>,
{
fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
Ok(match self {
Self::Count { field: _, alias } => {
format!(
"count(*){}",
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}"))
)
}
Self::Sum { field, alias } => {
format!(
"sum({}){}",
field
.to_sql(table_engine)
.attach_printable("Failed to sum aggregate")?,
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}"))
)
}
Self::Min { field, alias } => {
format!(
"min({}){}",
field
.to_sql(table_engine)
.attach_printable("Failed to min aggregate")?,
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}"))
)
}
Self::Max { field, alias } => {
format!(
"max({}){}",
field
.to_sql(table_engine)
.attach_printable("Failed to max aggregate")?,
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}"))
)
}
Self::Percentile {
field,
alias,
percentile,
} => {
format!(
"percentile_cont(0.{}) within group (order by {} asc){}",
percentile.map_or_else(|| "50".to_owned(), |percentile| percentile.to_string()),
field
.to_sql(table_engine)
.attach_printable("Failed to percentile aggregate")?,
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}"))
)
}
Self::DistinctCount { field, alias } => {
format!(
"count(distinct {}){}",
field
.to_sql(table_engine)
.attach_printable("Failed to distinct count aggregate")?,
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}"))
)
}
})
}
}
impl<T> ToSql<SqlxClient> for Window<T>
where
T: ToSql<SqlxClient>,
{
fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
Ok(match self {
Self::Sum {
field,
partition_by,
order_by,
alias,
} => {
format!(
"sum({}) over ({}{}){}",
field
.to_sql(table_engine)
.attach_printable("Failed to sum window")?,
partition_by.as_ref().map_or_else(
|| "".to_owned(),
|partition_by| format!("partition by {}", partition_by.to_owned())
),
order_by.as_ref().map_or_else(
|| "".to_owned(),
|(order_column, order)| format!(
" order by {} {}",
order_column.to_owned(),
order
)
),
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}"))
)
}
Self::RowNumber {
field: _,
partition_by,
order_by,
alias,
} => {
format!(
"row_number() over ({}{}){}",
partition_by.as_ref().map_or_else(
|| "".to_owned(),
|partition_by| format!("partition by {}", partition_by.to_owned())
),
order_by.as_ref().map_or_else(
|| "".to_owned(),
|(order_column, order)| format!(
" order by {} {}",
order_column.to_owned(),
order
)
),
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}"))
)
}
})
}
}
|
crates__api_models__src__admin.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 smithy::SmithyModel;
use utoipa::ToSchema;
use super::payments::AddressDetails;
use crate::{
consts::{MAX_ORDER_FULFILLMENT_EXPIRY, MIN_ORDER_FULFILLMENT_EXPIRY},
enums as api_enums, payment_methods,
};
#[cfg(feature = "v1")]
use crate::{profile_acquirer::ProfileAcquirerResponse, routing};
#[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<StaticRoutingAlgorithm>,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>,
/// Merchant Account Type of this merchant account
#[schema(value_type = Option<MerchantAccountType>, example = "standard")]
pub merchant_account_type: Option<api_enums::MerchantAccountType>,
}
#[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::StaticRoutingAlgorithm = routing_algorithm
.clone()
.parse_value("StaticRoutingAlgorithm")?;
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 ExternalVaultConnectorDetails {
/// Merchant Connector id to be stored for vault connector
#[schema(value_type = Option<String>)]
pub vault_connector_id: id_type::MerchantConnectorAccountId,
/// External vault to be used for storing payment method information
#[schema(value_type = Option<VaultSdk>)]
pub vault_sdk: Option<common_enums::VaultSdk>,
/// Fields to tokenization in vault
pub vault_token_selector: Option<Vec<VaultTokenField>>,
}
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
pub struct VaultTokenField {
/// Type of field to be tokenized in
#[schema(value_type = Option<VaultTokenType>)]
pub token_type: common_enums::VaultTokenType,
}
#[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<StaticRoutingAlgorithm>,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::StaticRoutingAlgorithm = routing_algorithm
.clone()
.parse_value("StaticRoutingAlgorithm")?;
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<StaticRoutingAlgorithm>,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<StaticRoutingAlgorithm>, 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>,
/// Merchant Account Type of this merchant account
#[schema(value_type = MerchantAccountType, example = "standard")]
pub merchant_account_type: api_enums::MerchantAccountType,
}
#[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>,
#[schema(value_type = Option<String>, example = "123456789")]
pub merchant_tax_registration_id: Option<Secret<String>>,
}
#[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>,
/// List of payment statuses that triggers a webhook for payment intents
#[schema(value_type = Vec<IntentStatus>, example = json!(["succeeded", "failed", "partially_captured", "requires_merchant_action"]))]
pub payment_statuses_enabled: Option<Vec<api_enums::IntentStatus>>,
/// List of refund statuses that triggers a webhook for refunds
#[schema(value_type = Vec<IntentStatus>, example = json!(["success", "failure"]))]
pub refund_statuses_enabled: Option<Vec<api_enums::RefundStatus>>,
/// List of payout statuses that triggers a webhook for payouts
#[cfg(feature = "payouts")]
#[schema(value_type = Option<Vec<PayoutStatus>>, example = json!(["success", "failed"]))]
pub payout_statuses_enabled: Option<Vec<api_enums::PayoutStatus>>,
}
impl WebhookDetails {
pub fn merge(self, other: Self) -> Self {
Self {
webhook_version: other.webhook_version.or(self.webhook_version),
webhook_username: other.webhook_username.or(self.webhook_username),
webhook_password: other.webhook_password.or(self.webhook_password),
webhook_url: other.webhook_url.or(self.webhook_url),
payment_created_enabled: other
.payment_created_enabled
.or(self.payment_created_enabled),
payment_succeeded_enabled: other
.payment_succeeded_enabled
.or(self.payment_succeeded_enabled),
payment_failed_enabled: other.payment_failed_enabled.or(self.payment_failed_enabled),
payment_statuses_enabled: other
.payment_statuses_enabled
.or(self.payment_statuses_enabled),
refund_statuses_enabled: other
.refund_statuses_enabled
.or(self.refund_statuses_enabled),
#[cfg(feature = "payouts")]
payout_statuses_enabled: other
.payout_statuses_enabled
.or(self.payout_statuses_enabled),
}
}
fn validate_statuses<T>(statuses: &[T], status_type_name: &str) -> Result<(), String>
where
T: strum::IntoEnumIterator + Copy + PartialEq + std::fmt::Debug,
T: Into<Option<api_enums::EventType>>,
{
let valid_statuses: Vec<T> = T::iter().filter(|s| (*s).into().is_some()).collect();
for status in statuses {
if !valid_statuses.contains(status) {
return Err(format!(
"Invalid {status_type_name} webhook status provided: {status:?}"
));
}
}
Ok(())
}
pub fn validate(&self) -> Result<(), String> {
if let Some(payment_statuses) = &self.payment_statuses_enabled {
Self::validate_statuses(payment_statuses, "payment")?;
}
if let Some(refund_statuses) = &self.refund_statuses_enabled {
Self::validate_statuses(refund_statuses, "refund")?;
}
#[cfg(feature = "payouts")]
{
if let Some(payout_statuses) = &self.payout_statuses_enabled {
Self::validate_statuses(payout_statuses, "payout")?;
}
}
Ok(())
}
}
#[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-based account for international transfers
Iban {
/// International Bank Account Number (up to 34 characters)
#[schema(value_type = String)]
iban: Secret<String>,
/// Account holder name
name: String,
#[schema(value_type = Option<String>)]
#[serde(skip_serializing_if = "Option::is_none")]
connector_recipient_id: Option<Secret<String>>,
},
/// UK BACS payment system
Bacs {
/// 8-digit UK account number
#[schema(value_type = String)]
account_number: Secret<String>,
/// 6-digit UK sort code
#[schema(value_type = String, example = "123456")]
sort_code: Secret<String>,
/// Account holder name
name: String,
#[schema(value_type = Option<String>)]
#[serde(skip_serializing_if = "Option::is_none")]
connector_recipient_id: Option<Secret<String>>,
},
/// UK Faster Payments (instant transfers)
FasterPayments {
/// 8-digit UK account number
#[schema(value_type = String)]
account_number: Secret<String>,
/// 6-digit UK sort code
#[schema(value_type = String)]
sort_code: Secret<String>,
/// Account holder name
name: String,
#[schema(value_type = Option<String>)]
#[serde(skip_serializing_if = "Option::is_none")]
connector_recipient_id: Option<Secret<String>>,
},
/// SEPA payments (Euro zone)
Sepa {
/// IBAN for SEPA transfers
#[schema(value_type = String, example = "FR1420041010050500013M02606")]
iban: Secret<String>,
/// Account holder name
name: String,
#[schema(value_type = Option<String>)]
#[serde(skip_serializing_if = "Option::is_none")]
connector_recipient_id: Option<Secret<String>>,
},
/// SEPA Instant payments (10-second transfers)
SepaInstant {
/// IBAN for instant SEPA transfers
#[schema(value_type = String, example = "DE89370400440532013000")]
iban: Secret<String>,
/// Account holder name
name: String,
#[schema(value_type = Option<String>)]
#[serde(skip_serializing_if = "Option::is_none")]
connector_recipient_id: Option<Secret<String>>,
},
/// Polish Elixir payment system
Elixir {
/// Polish account number (26 digits)
#[schema(value_type = String, example = "12345678901234567890123456")]
account_number: Secret<String>,
/// Polish IBAN (28 chars)
#[schema(value_type = String, example = "PL27114020040000300201355387")]
iban: Secret<String>,
/// Account holder name
name: String,
#[schema(value_type = Option<String>)]
#[serde(skip_serializing_if = "Option::is_none")]
connector_recipient_id: Option<Secret<String>>,
},
/// Swedish Bankgiro system
Bankgiro {
/// Bankgiro number (7-8 digits)
#[schema(value_type = String, example = "5402-9656")]
number: Secret<String>,
/// Account holder name
#[schema(example = "Erik Andersson")]
name: String,
#[schema(value_type = Option<String>)]
#[serde(skip_serializing_if = "Option::is_none")]
connector_recipient_id: Option<Secret<String>>,
},
/// Swedish Plusgiro system
Plusgiro {
/// Plusgiro number (2-8 digits)
#[schema(value_type = String, example = "4789-2")]
number: Secret<String>,
/// Account holder name
#[schema(example = "Anna Larsson")]
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 should be base64 encoded
certificate: Secret<String>,
// private_key should be base64 encoded
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>,
/// Details about the connector’s webhook configuration
#[schema(value_type = Option<WebhookSetupCapabilities>)]
pub webhook_setup_capabilities:
Option<common_types::connector_webhook_configuration::WebhookSetupCapabilities>,
}
#[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 Amazon Pay certificates and credentials
#[serde(skip_serializing_if = "Option::is_none")]
#[schema(value_type = Option<Object>)]
pub amazon_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,
SmithyModel,
ToSchema,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
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".
#[smithy(value_type = "String")]
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",
},
}"#)]
#[smithy(value_type = "Option<MerchantConnectorDetails>")]
pub encoded_data: Option<Secret<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize, SmithyModel, ToSchema)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
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" }))]
#[smithy(value_type = "Option<Object>")]
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" }))]
#[smithy(value_type = "Option<Object>")]
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<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))]
pub payout_routing_algorithm: Option<serde_json::Value>,
/// Verified Apple Pay domains for a particular profile
pub applepay_verified_domains: Option<Vec<String>>,
/// Client Secret Default expiry for all payments created under this profile
#[schema(example = 900)]
pub session_expiry: Option<u32>,
/// Default Payment Link config for all payment links created under this profile
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
/// External 3DS authentication details
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
/// 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>,
/// Indicates if the redirection has to open in the iframe
#[schema(example = false)]
pub is_iframe_redirection_enabled: Option<bool>,
/// Indicates if pre network tokenization is enabled or not
pub is_pre_network_tokenization_enabled: Option<bool>,
/// Four-digit code assigned based on business type to determine processing fees and risk level
#[schema(value_type = Option<MerchantCategoryCode>, example = "5411")]
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
/// Merchant country code.
/// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates.
/// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks.
/// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior.
#[schema(value_type = Option<MerchantCountryCode>, example = "840")]
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
/// Time interval (in hours) for polling the connector to check for new disputes
#[schema(value_type = Option<i32>, example = 2)]
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
/// Indicates if manual retry for payment is enabled or not
pub is_manual_retry_enabled: Option<bool>,
/// Bool indicating if overcapture must be requested for all payments
#[schema(value_type = Option<bool>)]
pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>,
/// Indicates if external vault is enabled or not.
#[schema(value_type = Option<ExternalVaultEnabled>, example = "Enable")]
pub is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>,
/// External Vault Connector Details
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
/// Merchant Connector id to be stored for billing_processor connector
#[schema(value_type = Option<String>)]
pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>,
/// Flag to enable Level 2 and Level 3 processing data for card transactions
#[schema(value_type = Option<bool>)]
pub is_l2_l3_enabled: Option<bool>,
}
#[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>,
/// Indicates if the redirection has to open in the iframe
#[schema(example = false)]
pub is_iframe_redirection_enabled: Option<bool>,
/// Indicates if external vault is enabled or not.
pub is_external_vault_enabled: Option<bool>,
/// External Vault Connector Details
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
/// Four-digit code assigned based on business type to determine processing fees and risk level
#[schema(value_type = Option<MerchantCategoryCode>, example = "5411")]
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
/// Merchant country code.
/// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates.
/// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks.
/// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior.
#[schema(value_type = Option<MerchantCountryCode>, example = "840")]
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
/// Enable split payments, i.e., split the amount between multiple payment methods
#[schema(value_type = Option<SplitTxnsEnabled>, default = "skip")]
pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>,
/// Merchant Connector id to be stored for billing_processor connector
#[schema(value_type = Option<String>)]
pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>,
/// Flag to enable Level 2 and Level 3 processing data for card transactions
#[schema(value_type = Option<bool>)]
pub is_l2_l3_enabled: Option<bool>,
}
#[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<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))]
pub payout_routing_algorithm: Option<serde_json::Value>,
/// Verified Apple Pay domains for a particular profile
pub applepay_verified_domains: Option<Vec<String>>,
/// Client Secret Default expiry for all payments created under this profile
#[schema(example = 900)]
pub session_expiry: Option<i64>,
/// Default Payment Link config for all payment links created under this profile
#[schema(value_type = Option<BusinessPaymentLinkConfig>)]
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
/// External 3DS authentication details
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
/// Merchant's config to support extended card info feature
pub extended_card_info_config: Option<ExtendedCardInfoConfig>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_shipping_details_from_wallet_connector: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_billing_details_from_wallet_connector: Option<bool>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
/// Indicates if the MIT (merchant initiated transaction) payments can be made connector
/// agnostic, i.e., MITs may be processed through different connector than CIT (customer
/// initiated transaction) based on the routing rules.
/// If set to `false`, MIT will go through the same connector as the CIT.
pub is_connector_agnostic_mit_enabled: Option<bool>,
/// Default payout link config
#[schema(value_type = Option<BusinessPayoutLinkConfig>)]
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
/// These key-value pairs are sent as additional custom headers in the outgoing webhook request.
#[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)]
pub outgoing_webhook_custom_http_headers: Option<MaskedHeaders>,
/// Merchant Connector id to be stored for tax_calculator connector
#[schema(value_type = Option<String>)]
pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>,
/// Indicates if tax_calculator connector is enabled or not.
/// If set to `true` tax_connector_id will be checked.
pub is_tax_connector_enabled: bool,
/// Indicates if network tokenization is enabled or not.
#[schema(default = false, example = false)]
pub is_network_tokenization_enabled: bool,
/// Indicates if is_auto_retries_enabled is enabled or not.
#[schema(default = false, example = false)]
pub is_auto_retries_enabled: bool,
/// Maximum number of auto retries allowed for a payment
pub max_auto_retries_enabled: Option<i16>,
/// Bool indicating if extended authentication must be requested for all payments
#[schema(value_type = Option<bool>)]
pub always_request_extended_authorization:
Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>,
/// Indicates if click to pay is enabled or not.
#[schema(default = false, example = false)]
pub is_click_to_pay_enabled: bool,
/// Product authentication ids
#[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)]
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
/// Card Testing Guard Configs
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
///Indicates if clear pan retries is enabled or not.
pub is_clear_pan_retries_enabled: bool,
/// Indicates if 3ds challenge is forced
pub force_3ds_challenge: bool,
/// Indicates if debit routing is enabled or not
#[schema(value_type = Option<bool>)]
pub is_debit_routing_enabled: Option<bool>,
//Merchant country for the profile
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
/// Indicates if pre network tokenization is enabled or not
#[schema(default = false, example = false)]
pub is_pre_network_tokenization_enabled: bool,
/// Acquirer configs
#[schema(value_type = Option<Vec<ProfileAcquirerResponse>>)]
pub acquirer_configs: Option<Vec<ProfileAcquirerResponse>>,
/// Indicates if the redirection has to open in the iframe
#[schema(example = false)]
pub is_iframe_redirection_enabled: Option<bool>,
/// Four-digit code assigned based on business type to determine processing fees and risk level
#[schema(value_type = Option<MerchantCategoryCode>, example = "5411")]
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
/// Merchant country code.
/// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates.
/// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks.
/// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior.
#[schema(value_type = Option<MerchantCountryCode>, example = "840")]
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
/// Time interval (in hours) for polling the connector to check dispute statuses
#[schema(value_type = Option<u32>, example = 2)]
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
/// Indicates if manual retry for payment is enabled or not
pub is_manual_retry_enabled: Option<bool>,
/// Bool indicating if overcapture must be requested for all payments
#[schema(value_type = Option<bool>)]
pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>,
/// Indicates if external vault is enabled or not.
#[schema(value_type = Option<ExternalVaultEnabled>, example = "Enable")]
pub is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>,
/// External Vault Connector Details
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
/// Merchant Connector id to be stored for billing_processor connector
#[schema(value_type = Option<String>)]
pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>,
/// Flag to enable Level 2 and Level 3 processing data for card transactions
#[schema(value_type = Option<bool>)]
pub is_l2_l3_enabled: Option<bool>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, ToSchema, Serialize)]
pub struct ProfileResponse {
/// The identifier for Merchant Account
#[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
pub merchant_id: id_type::MerchantId,
/// The identifier for profile. This must be used for creating merchant accounts, payments and payouts
#[schema(max_length = 64, value_type = String, example = "pro_abcdefghijklmnopqrstuvwxyz")]
pub id: id_type::ProfileId,
/// Name of the profile
#[schema(max_length = 64)]
pub profile_name: String,
/// The URL to redirect after the completion of the operation
#[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")]
pub return_url: Option<common_utils::types::Url>,
/// A boolean value to indicate if payment response hash needs to be enabled
#[schema(default = true, example = true)]
pub enable_payment_response_hash: bool,
/// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated.
pub payment_response_hash_key: Option<String>,
/// A boolean value to indicate if redirect to merchant with http post needs to be enabled
#[schema(default = false, example = true)]
pub redirect_to_merchant_with_http_post: bool,
/// Webhook related details
pub webhook_details: Option<WebhookDetails>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// Verified Apple Pay domains for a particular profile
pub applepay_verified_domains: Option<Vec<String>>,
/// Client Secret Default expiry for all payments created under this profile
#[schema(example = 900)]
pub session_expiry: Option<i64>,
/// Default Payment Link config for all payment links created under this profile
#[schema(value_type = Option<BusinessPaymentLinkConfig>)]
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
/// External 3DS authentication details
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
/// Merchant's config to support extended card info feature
pub extended_card_info_config: Option<ExtendedCardInfoConfig>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_shipping_details_from_wallet_connector_if_required: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_billing_details_from_wallet_connector_if_required: Option<bool>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
/// Indicates if the MIT (merchant initiated transaction) payments can be made connector
/// agnostic, i.e., MITs may be processed through different connector than CIT (customer
/// initiated transaction) based on the routing rules.
/// If set to `false`, MIT will go through the same connector as the CIT.
pub is_connector_agnostic_mit_enabled: Option<bool>,
/// Default payout link config
#[schema(value_type = Option<BusinessPayoutLinkConfig>)]
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
/// These key-value pairs are sent as additional custom headers in the outgoing webhook request.
#[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)]
pub outgoing_webhook_custom_http_headers: Option<MaskedHeaders>,
/// Will be used to determine the time till which your payment will be active once the payment session starts
#[schema(value_type = Option<u32>, example = 900)]
pub order_fulfillment_time: Option<OrderFulfillmentTime>,
/// Whether the order fulfillment time is calculated from the origin or the time of creating the payment, or confirming the payment
#[schema(value_type = Option<OrderFulfillmentTimeOrigin>, example = "create")]
pub order_fulfillment_time_origin: Option<api_enums::OrderFulfillmentTimeOrigin>,
/// Merchant Connector id to be stored for tax_calculator connector
#[schema(value_type = Option<String>)]
pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>,
/// Indicates if tax_calculator connector is enabled or not.
/// If set to `true` tax_connector_id will be checked.
pub is_tax_connector_enabled: bool,
/// Indicates if network tokenization is enabled or not.
#[schema(default = false, example = false)]
pub is_network_tokenization_enabled: bool,
/// Indicates if CVV should be collected during payment or not.
#[schema(value_type = Option<bool>)]
pub should_collect_cvv_during_payment:
Option<primitive_wrappers::ShouldCollectCvvDuringPayment>,
/// Indicates if click to pay is enabled or not.
#[schema(default = false, example = false)]
pub is_click_to_pay_enabled: bool,
/// Product authentication ids
#[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)]
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
/// Card Testing Guard Configs
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
///Indicates if clear pan retries is enabled or not.
pub is_clear_pan_retries_enabled: bool,
/// Indicates if debit routing is enabled or not
#[schema(value_type = Option<bool>)]
pub is_debit_routing_enabled: Option<bool>,
//Merchant country for the profile
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
/// Indicates if the redirection has to open in the iframe
#[schema(example = false)]
pub is_iframe_redirection_enabled: Option<bool>,
/// Indicates if external vault is enabled or not.
pub is_external_vault_enabled: Option<bool>,
/// External Vault Connector Details
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
/// Four-digit code assigned based on business type to determine processing fees and risk level
#[schema(value_type = Option<MerchantCategoryCode>, example = "5411")]
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
/// Merchant country code.
/// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates.
/// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks.
/// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior.
#[schema(value_type = Option<MerchantCountryCode>, example = "840")]
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
/// Enable split payments, i.e., split the amount between multiple payment methods
#[schema(value_type = SplitTxnsEnabled, default = "skip")]
pub split_txns_enabled: common_enums::SplitTxnsEnabled,
/// Indicates the state of revenue recovery algorithm type
#[schema(value_type = Option<RevenueRecoveryAlgorithmType>, example = "cascading")]
pub revenue_recovery_retry_algorithm_type:
Option<common_enums::enums::RevenueRecoveryAlgorithmType>,
/// Merchant Connector id to be stored for billing_processor connector
#[schema(value_type = Option<String>)]
pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>,
/// Flag to enable Level 2 and Level 3 processing data for card transactions
#[schema(value_type = Option<bool>)]
pub is_l2_l3_enabled: Option<bool>,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ProfileUpdate {
/// The name of profile
#[schema(max_length = 64)]
pub profile_name: Option<String>,
/// The URL to redirect after the completion of the operation
#[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")]
pub return_url: Option<url::Url>,
/// A boolean value to indicate if payment response hash needs to be enabled
#[schema(default = true, example = true)]
pub enable_payment_response_hash: Option<bool>,
/// Refers to the hash key used for calculating the signature for webhooks and redirect response.
pub payment_response_hash_key: Option<String>,
/// A boolean value to indicate if redirect to merchant with http post needs to be enabled
#[schema(default = false, example = true)]
pub redirect_to_merchant_with_http_post: Option<bool>,
/// Webhook related details
pub webhook_details: Option<WebhookDetails>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// The routing algorithm to be used for routing payments to desired connectors
#[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "stripe"}))]
pub routing_algorithm: Option<serde_json::Value>,
/// Will be used to determine the time till which your payment will be active once the payment session starts
#[schema(example = 900)]
pub intent_fulfillment_time: Option<u32>,
/// The frm routing algorithm to be used for routing payments to desired FRM's
#[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))]
pub frm_routing_algorithm: Option<serde_json::Value>,
/// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom'
#[cfg(feature = "payouts")]
#[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))]
pub payout_routing_algorithm: Option<serde_json::Value>,
/// Verified Apple Pay domains for a particular profile
pub applepay_verified_domains: Option<Vec<String>>,
/// Client Secret Default expiry for all payments created under this profile
#[schema(example = 900)]
pub session_expiry: Option<u32>,
/// Default Payment Link config for all payment links created under this profile
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
/// External 3DS authentication details
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
/// Merchant's config to support extended card info feature
pub extended_card_info_config: Option<ExtendedCardInfoConfig>,
// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_shipping_details_from_wallet_connector: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_billing_details_from_wallet_connector: Option<bool>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
/// Bool indicating if extended authentication must be requested for all payments
#[schema(value_type = Option<bool>)]
pub always_request_extended_authorization:
Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>,
/// Indicates if the MIT (merchant initiated transaction) payments can be made connector
/// agnostic, i.e., MITs may be processed through different connector than CIT (customer
/// initiated transaction) based on the routing rules.
/// If set to `false`, MIT will go through the same connector as the CIT.
pub is_connector_agnostic_mit_enabled: Option<bool>,
/// Default payout link config
#[schema(value_type = Option<BusinessPayoutLinkConfig>)]
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
/// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs.
#[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)]
pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>,
/// Merchant Connector id to be stored for tax_calculator connector
#[schema(value_type = Option<String>)]
pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>,
/// Indicates if tax_calculator connector is enabled or not.
/// If set to `true` tax_connector_id will be checked.
pub is_tax_connector_enabled: Option<bool>,
/// Indicates if dynamic routing is enabled or not.
#[serde(default)]
pub dynamic_routing_algorithm: Option<serde_json::Value>,
/// Indicates if network tokenization is enabled or not.
pub is_network_tokenization_enabled: Option<bool>,
/// Indicates if is_auto_retries_enabled is enabled or not.
pub is_auto_retries_enabled: Option<bool>,
/// Maximum number of auto retries allowed for a payment
pub max_auto_retries_enabled: Option<u8>,
/// Indicates if click to pay is enabled or not.
#[schema(default = false, example = false)]
pub is_click_to_pay_enabled: Option<bool>,
/// Product authentication ids
#[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)]
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
/// Card Testing Guard Configs
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
///Indicates if clear pan retries is enabled or not.
pub is_clear_pan_retries_enabled: Option<bool>,
/// Indicates if 3ds challenge is forced
pub force_3ds_challenge: Option<bool>,
/// Indicates if debit routing is enabled or not
#[schema(value_type = Option<bool>)]
pub is_debit_routing_enabled: Option<bool>,
//Merchant country for the profile
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
/// Indicates if the redirection has to open in the iframe
#[schema(example = false)]
pub is_iframe_redirection_enabled: Option<bool>,
/// Indicates if pre network tokenization is enabled or not
#[schema(default = false, example = false)]
pub is_pre_network_tokenization_enabled: Option<bool>,
/// Four-digit code assigned based on business type to determine processing fees and risk level
#[schema(value_type = Option<MerchantCategoryCode>, example = "5411")]
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
/// Merchant country code.
/// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates.
/// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks.
/// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior.
#[schema(value_type = Option<MerchantCountryCode>, example = "840")]
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
/// Time interval (in hours) for polling the connector to check for new disputes
#[schema(value_type = Option<u32>, example = 2)]
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
/// Indicates if manual retry for payment is enabled or not
pub is_manual_retry_enabled: Option<bool>,
/// Bool indicating if overcapture must be requested for all payments
#[schema(value_type = Option<bool>)]
pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>,
/// Indicates if external vault is enabled or not.
#[schema(value_type = Option<ExternalVaultEnabled>, example = "Enable")]
pub is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>,
/// External Vault Connector Details
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
/// Merchant Connector id to be stored for billing_processor connector
#[schema(value_type = Option<String>)]
pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>,
/// Flag to enable Level 2 and Level 3 processing data for card transactions
#[schema(value_type = Option<bool>)]
pub is_l2_l3_enabled: Option<bool>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ProfileUpdate {
/// The name of profile
#[schema(max_length = 64)]
pub profile_name: Option<String>,
/// The URL to redirect after the completion of the operation
#[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")]
pub return_url: Option<common_utils::types::Url>,
/// A boolean value to indicate if payment response hash needs to be enabled
#[schema(default = true, example = true)]
pub enable_payment_response_hash: Option<bool>,
/// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated.
pub payment_response_hash_key: Option<String>,
/// A boolean value to indicate if redirect to merchant with http post needs to be enabled
#[schema(default = false, example = true)]
pub redirect_to_merchant_with_http_post: Option<bool>,
/// Webhook related details
pub webhook_details: Option<WebhookDetails>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// Will be used to determine the time till which your payment will be active once the payment session starts
#[schema(value_type = Option<u32>, example = 900)]
pub order_fulfillment_time: Option<OrderFulfillmentTime>,
/// Whether the order fulfillment time is calculated from the origin or the time of creating the payment, or confirming the payment
#[schema(value_type = Option<OrderFulfillmentTimeOrigin>, example = "create")]
pub order_fulfillment_time_origin: Option<api_enums::OrderFulfillmentTimeOrigin>,
/// Verified Apple Pay domains for a particular profile
pub applepay_verified_domains: Option<Vec<String>>,
/// Client Secret Default expiry for all payments created under this profile
#[schema(example = 900)]
pub session_expiry: Option<u32>,
/// Default Payment Link config for all payment links created under this profile
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
/// External 3DS authentication details
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
/// Merchant's config to support extended card info feature
pub extended_card_info_config: Option<ExtendedCardInfoConfig>,
// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_shipping_details_from_wallet_connector_if_required: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_billing_details_from_wallet_connector_if_required: Option<bool>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
/// Indicates if the MIT (merchant initiated transaction) payments can be made connector
/// agnostic, i.e., MITs may be processed through different connector than CIT (customer
/// initiated transaction) based on the routing rules.
/// If set to `false`, MIT will go through the same connector as the CIT.
pub is_connector_agnostic_mit_enabled: Option<bool>,
/// Default payout link config
#[schema(value_type = Option<BusinessPayoutLinkConfig>)]
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
/// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs.
#[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)]
pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>,
/// Merchant Connector id to be stored for tax_calculator connector
#[schema(value_type = Option<String>)]
pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>,
/// Indicates if tax_calculator connector is enabled or not.
/// If set to `true` tax_connector_id will be checked.
pub is_tax_connector_enabled: Option<bool>,
/// Indicates if network tokenization is enabled or not.
pub is_network_tokenization_enabled: Option<bool>,
/// Indicates if click to pay is enabled or not.
#[schema(default = false, example = false)]
pub is_click_to_pay_enabled: Option<bool>,
/// Product authentication ids
#[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)]
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
/// Card Testing Guard Configs
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
///Indicates if clear pan retries is enabled or not.
pub is_clear_pan_retries_enabled: Option<bool>,
/// Indicates if debit routing is enabled or not
#[schema(value_type = Option<bool>)]
pub is_debit_routing_enabled: Option<bool>,
//Merchant country for the profile
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
/// Indicates if external vault is enabled or not.
pub is_external_vault_enabled: Option<bool>,
/// External Vault Connector Details
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
/// Four-digit code assigned based on business type to determine processing fees and risk level
#[schema(value_type = Option<MerchantCategoryCode>, example = "5411")]
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
/// Merchant country code.
/// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates.
/// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks.
/// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior.
#[schema(value_type = Option<MerchantCountryCode>, example = "840")]
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
/// Indicates the state of revenue recovery algorithm type
#[schema(value_type = Option<RevenueRecoveryAlgorithmType>, example = "cascading")]
pub revenue_recovery_retry_algorithm_type:
Option<common_enums::enums::RevenueRecoveryAlgorithmType>,
/// Enable split payments, i.e., split the amount between multiple payment methods
#[schema(value_type = Option<SplitTxnsEnabled>, default = "skip")]
pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>,
/// Merchant Connector id to be stored for billing_processor connector
#[schema(value_type = Option<String>)]
pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>,
}
#[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<(), String> {
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".to_string());
}
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".to_string());
}
if let Some(default_cfg) = self.default_config.as_ref() {
default_cfg.validate()?;
}
if let Some(biz_cfgs) = self.business_specific_configs.as_ref() {
for config in biz_cfgs.values() {
config.validate()?;
}
}
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>,
/// Text for customizing message for different Payment Method Types
#[schema(value_type = Option<PaymentMethodsConfig>)]
pub custom_message_for_payment_method_types:
Option<common_types::payments::PaymentMethodsConfig>,
/// 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>,
/// Optional header for the SDK's payment form
pub payment_form_header_text: Option<String>,
/// Label type in the SDK's payment form
#[schema(value_type = Option<PaymentLinkSdkLabelType>, example = "floating")]
pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>,
/// Boolean for controlling whether or not to show the explicit consent for storing cards
#[schema(value_type = Option<PaymentLinkShowSdkTerms>, example = "always")]
pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>,
/// Boolean to control payment button text for setup mandate calls
pub is_setup_mandate_flow: Option<bool>,
/// Hex color for the CVC icon during error state
pub color_icon_card_cvc_error: Option<String>,
}
impl PaymentLinkConfigRequest {
pub fn validate(&self) -> Result<(), String> {
if let Some(custom_message) = self.custom_message_for_payment_method_types.as_ref() {
custom_message.validate().map_err(|e| e.to_string())?;
}
Ok(())
}
}
#[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>,
/// Text for customizing message for different Payment Method Types
#[schema(value_type = Option<PaymentMethodsConfig>)]
pub custom_message_for_payment_method_types:
Option<common_types::payments::PaymentMethodsConfig>,
/// 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,
/// Optional header for the SDK's payment form
pub payment_form_header_text: Option<String>,
/// Label type in the SDK's payment form
#[schema(value_type = Option<PaymentLinkSdkLabelType>, example = "floating")]
pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>,
/// Boolean for controlling whether or not to show the explicit consent for storing cards
#[schema(value_type = Option<PaymentLinkShowSdkTerms>, example = "always")]
pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>,
/// Boolean to control payment button text for setup mandate calls
pub is_setup_mandate_flow: Option<bool>,
/// Hex color for the CVC icon during error state
pub color_icon_card_cvc_error: Option<String>,
}
#[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
}
}
|
crates__api_models__src__analytics.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 routing_events;
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>,
}
|
crates__api_models__src__events__payment.rs
|
use common_utils::events::{ApiEventMetric, ApiEventsType};
#[cfg(feature = "v2")]
use super::{
PaymentAttemptListRequest, PaymentAttemptListResponse, PaymentStartRedirectionRequest,
PaymentsCreateIntentRequest, PaymentsGetIntentRequest, PaymentsIntentResponse, PaymentsRequest,
RecoveryPaymentListResponse, RecoveryPaymentsCreate, RecoveryPaymentsResponse,
RevenueRecoveryGetIntentResponse,
};
#[cfg(feature = "v2")]
use crate::payment_methods::{
ListMethodsForPaymentMethodsRequest, PaymentMethodGetTokenDetailsResponse,
PaymentMethodListResponseForSession,
};
use crate::{
payment_methods::{
self, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse,
PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest,
PaymentMethodCollectLinkResponse, PaymentMethodMigrateResponse, PaymentMethodResponse,
PaymentMethodUpdate,
},
payments::{
self, PaymentListConstraints, PaymentListFilters, PaymentListFiltersV2,
PaymentListResponse, PaymentsAggregateResponse, PaymentsSessionResponse,
RedirectionResponse,
},
};
#[cfg(feature = "v1")]
use crate::{
payment_methods::{
CustomerPaymentMethodUpdateResponse, PaymentMethodListRequest, PaymentMethodListResponse,
},
payments::{
ExtendedCardInfoResponse, PaymentIdType, PaymentListFilterConstraints,
PaymentListResponseV2, PaymentsApproveRequest, PaymentsCancelPostCaptureRequest,
PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest,
PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse,
PaymentsExtendAuthorizationRequest, PaymentsExternalAuthenticationRequest,
PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest,
PaymentsManualUpdateRequest, PaymentsManualUpdateResponse,
PaymentsPostSessionTokensRequest, PaymentsPostSessionTokensResponse, PaymentsRejectRequest,
PaymentsRetrieveRequest, PaymentsStartRequest, PaymentsUpdateMetadataRequest,
PaymentsUpdateMetadataResponse,
},
};
#[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 PaymentsUpdateMetadataRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsUpdateMetadataResponse {
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 PaymentsCancelPostCaptureRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsExtendAuthorizationRequest {
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 = "v1")]
impl ApiEventMetric for payments::PaymentsEligibilityRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for payments::PaymentsEligibilityResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentsCreateIntentRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for payments::CheckAndApplyPaymentMethodDataResponse {
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 PaymentAttemptListRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_intent_id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentAttemptListResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentsIntentResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.id.clone(),
})
}
}
#[cfg(all(feature = "v2", feature = "olap"))]
impl ApiEventMetric for RevenueRecoveryGetIntentResponse {
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 = "v2")]
impl ApiEventMetric for payments::PaymentsCancelRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for payments::PaymentsCancelResponse {
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(feature = "v1")]
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(feature = "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,
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for CustomerPaymentMethodUpdateResponse {
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,
})
}
}
impl ApiEventMetric for PaymentMethodMigrateResponse {
#[cfg(feature = "v1")]
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(feature = "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 payment_methods::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 payment_methods::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 payment_methods::CustomerPaymentMethodsListResponse {}
#[cfg(feature = "v1")]
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()),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for ListMethodsForPaymentMethodsRequest {
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 {}
#[cfg(feature = "v1")]
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 = "v2")]
impl ApiEventMetric for RecoveryPaymentsCreate {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for RecoveryPaymentsResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for RecoveryPaymentListResponse {
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 PaymentMethodListResponseForSession {}
#[cfg(feature = "v2")]
impl ApiEventMetric for payments::PaymentsCaptureResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for payment_methods::PaymentMethodGetTokenDetailsResponse {
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,
})
}
}
|
crates__api_models__src__events__routing.rs
|
use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::routing::{
ContractBasedRoutingPayloadWrapper, ContractBasedRoutingSetupPayloadWrapper,
CreateDynamicRoutingWrapper, DynamicRoutingUpdateConfigQuery, EliminationRoutingPayloadWrapper,
LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig,
RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind,
RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery,
RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, RoutingVolumeSplit,
RoutingVolumeSplitResponse, RoutingVolumeSplitWrapper, RuleMigrationError, RuleMigrationQuery,
RuleMigrationResponse, RuleMigrationResult, SuccessBasedRoutingConfig,
SuccessBasedRoutingPayloadWrapper, ToggleDynamicRoutingPath, 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 EliminationRoutingPayloadWrapper {
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 CreateDynamicRoutingWrapper {
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)
}
}
impl ApiEventMetric for ToggleDynamicRoutingPath {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RoutingVolumeSplitResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RoutingVolumeSplit {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RuleMigrationQuery {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RuleMigrationResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RuleMigrationResult {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RuleMigrationError {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for crate::open_router::DecideGatewayResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for crate::open_router::OpenRouterDecideGatewayRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for crate::open_router::UpdateScorePayload {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for crate::open_router::UpdateScoreResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
|
crates__api_models__src__payment_methods.rs
|
use std::collections::{HashMap, HashSet};
#[cfg(feature = "v2")]
use std::str::FromStr;
use cards::CardNumber;
#[cfg(feature = "v1")]
use common_utils::crypto::OptionalEncryptableName;
use common_utils::{
consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH,
errors,
ext_traits::OptionExt,
id_type, link_utils, pii,
types::{MinorUnit, Percentage, Surcharge},
};
use masking::PeekInterface;
use serde::de;
use utoipa::ToSchema;
#[cfg(feature = "v1")]
use crate::payments::BankCodeResponse;
#[cfg(feature = "payouts")]
use crate::payouts;
use crate::{admin, enums as api_enums, open_router, payments};
#[cfg(feature = "v1")]
#[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(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PaymentMethodRetrieveRequest {
#[serde(default)]
pub fetch_raw_detail: bool,
}
#[cfg(feature = "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 = Option<PaymentMethodType>,example = "credit")]
pub payment_method_subtype: Option<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: Option<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>,
/// The storage type for the payment method
#[schema(value_type = StorageType)]
pub storage_type: common_enums::StorageType,
}
#[cfg(feature = "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(feature = "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(feature = "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(_) | PaymentMethodCreateData::ProxyCard(_)
)
}
_ => false,
}
}
}
/// This struct is used internally only
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct PaymentMethodIntentConfirmInternal {
pub id: id_type::GlobalPaymentMethodId,
pub request: PaymentMethodIntentConfirm,
}
#[cfg(feature = "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>,
//payment method data migration status (bank debit, wallet, etc.)
pub payment_method_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, serde::Serialize, ToSchema)]
pub struct PaymentMethodRecordUpdateResponse {
pub payment_method_id: String,
pub status: common_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub connector_mandate_details: Option<pii::SecretSerdeValue>,
pub updated_payment_method_data: 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>,
pub connector_customer_id: Option<String>,
}
#[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(feature = "v1")]
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_issuing_country_code: payment_method_migrate_card
.card_issuing_country_code
.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(),
card_cvc: None,
});
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(),
}
}
pub fn get_payment_method_create_from_payment_method_data_migrate(
payment_method_data: PaymentMethodCreateData,
payment_method_migrate: &PaymentMethodMigrate,
) -> Self {
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: Some(payment_method_data),
connector_mandate_details: payment_method_migrate
.connector_mandate_details
.clone()
.map(PaymentsMandateReference::from),
client_secret: None,
billing: payment_method_migrate.billing.clone(),
card: None,
card_network: None,
#[cfg(feature = "payouts")]
bank_transfer: None,
#[cfg(feature = "payouts")]
wallet: None,
network_transaction_id: payment_method_migrate.network_transaction_id.clone(),
}
}
}
#[cfg(feature = "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(_) | PaymentMethodCreateData::ProxyCard(_)
)
}
_ => 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(feature = "v1")]
#[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>,
/// Wallet Details
pub wallet: Option<PaymentMethodDataWalletInfo>,
/// 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(feature = "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>,
/// The network transaction ID provided by the card network during a Customer Initiated Transaction (CIT)
/// when `setup_future_usage` is set to `off_session`.
#[schema(value_type = Option<String>)]
pub network_transaction_id: Option<masking::Secret<String>>,
}
#[cfg(feature = "v2")]
impl PaymentMethodUpdate {
pub fn fetch_card_cvc_update(&self) -> Option<masking::Secret<String>> {
match &self.payment_method_data {
Some(PaymentMethodUpdateData::Card(card_update)) => card_update.card_cvc.clone(),
_ => None,
}
}
pub fn is_payment_method_metadata_update(&self) -> bool {
match &self.payment_method_data {
Some(PaymentMethodUpdateData::Card(card_update)) => {
card_update.card_holder_name.is_some() || card_update.nick_name.is_some()
}
_ => false,
}
}
pub fn is_payment_method_update_required(&self) -> bool {
self.is_payment_method_metadata_update()
|| self.connector_token_details.is_some()
|| self.network_transaction_id.is_some()
}
}
#[cfg(feature = "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(feature = "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),
ProxyCard(ProxyCardDetails),
}
#[cfg(feature = "v2")]
impl PaymentMethodCreateData {
pub fn get_card(&self) -> Option<CardDetail> {
match self {
Self::Card(card_detail) => Some(card_detail.clone()),
_ => None,
}
}
}
#[cfg(feature = "v1")]
#[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),
BankDebit(BankDebitDetail),
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "snake_case")]
pub enum BankDebitDetail {
Ach {
#[schema(value_type = String)]
account_number: masking::Secret<String>,
#[schema(value_type = String)]
routing_number: masking::Secret<String>,
},
}
impl BankDebitDetail {
pub fn get_masked_account_number(&self) -> String {
match self {
Self::Ach {
account_number,
routing_number: _,
} => account_number
.peek()
.chars()
.rev()
.take(4)
.collect::<String>()
.chars()
.rev()
.collect::<String>(),
}
}
pub fn get_masked_routing_number(&self) -> String {
match self {
Self::Ach {
account_number: _,
routing_number,
} => routing_number
.peek()
.chars()
.rev()
.take(4)
.collect::<String>()
.chars()
.rev()
.collect::<String>(),
}
}
}
#[cfg(feature = "v1")]
#[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 CVC for Volatile Storage
#[schema(value_type = Option<String>,example = "123")]
pub card_cvc: 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>>,
/// Card Issuing Country
pub card_issuing_country: Option<String>,
/// Card Issuing Country Code
pub card_issuing_country_code: 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(feature = "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>>,
}
// This struct is for collecting Proxy Card Data
// All card related data present in this struct are tokenzied
// No strict type is present to accept tokenized data
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct ProxyCardDetails {
/// Tokenized Card Number
#[schema(value_type = String,example = "tok_sjfowhoejsldj")]
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>,
/// First Six Digit of Card Number
pub bin_number: Option<String>,
///Last Four Digit of Card Number
pub last_four: Option<String>,
/// Issuer Bank for Card
pub card_issuer: Option<String>,
/// Card's Network
#[schema(value_type = Option<CardNetwork>)]
pub card_network: Option<common_enums::CardNetwork>,
/// Card Type
pub card_type: Option<String>,
/// Issuing Country of the Card
pub card_issuing_country: Option<String>,
/// Card Holder's Nick Name
#[schema(value_type = Option<String>,example = "John Doe")]
pub nick_name: Option<masking::Secret<String>>,
/// Card Holder Name
#[schema(value_type = String,example = "John Doe")]
pub card_holder_name: Option<masking::Secret<String>>,
/// 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 Issuing Country Code
pub card_issuing_country_code: 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 Issuing Country
pub card_issuing_country_code: 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(feature = "v1")]
#[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>>,
/// Card's Last 4 Digits
#[schema(value_type = Option<String>, example = "1111")]
pub last4_digits: Option<String>,
/// Issuing Bank of the Particular Card
#[schema(value_type = Option<String>, example = "Bank of America")]
pub card_issuer: Option<String>,
/// The country where that particular card was issued
#[schema(value_type = Option<String>, example = "US")]
pub issuer_country: Option<String>,
/// The country code where that particular card was issued
#[schema(value_type = Option<String>, example = "US")]
pub issuer_country_code: Option<String>,
/// The card network
#[schema(value_type = Option<String>, example = "VISA")]
pub card_network: Option<common_enums::CardNetwork>,
}
#[cfg(feature = "v1")]
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_cvc: None,
card_issuing_country: None,
card_issuing_country_code: None,
card_network: None,
card_issuer: None,
card_type: None,
}
}
}
#[cfg(feature = "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>>,
/// The CVC number for the card
#[schema(value_type = Option<String>, example = "242")]
pub card_cvc: Option<masking::Secret<String>>,
}
#[cfg(feature = "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(feature = "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(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "snake_case")]
pub enum RawPaymentMethodData {
Card(CardDetail),
}
#[cfg(feature = "v1")]
#[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 supports recurring payments. Optional.
#[schema(example = true)]
pub recurring_enabled: Option<bool>,
/// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional.
#[schema(example = true)]
pub installment_payment_enabled: Option<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(feature = "v1")]
#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct CustomerPaymentMethodUpdateResponse {
/// 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>,
/// Updated Wallet Details
pub wallet: Option<PaymentMethodDataWalletInfo>,
/// Indicates whether the payment method supports recurring payments. Optional.
#[schema(example = true)]
pub recurring_enabled: Option<bool>,
/// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional.
#[schema(example = true)]
pub installment_payment_enabled: Option<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(feature = "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(feature = "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: Option<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 supports recurring payments. Optional.
#[schema(example = true)]
pub recurring_enabled: Option<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>>,
/// Network token details if available
pub network_token: Option<NetworkTokenResponse>,
/// The storage type for the payment method
#[schema(value_type = StorageType)]
pub storage_type: common_enums::StorageType,
/// Card CVC token storage details
pub card_cvc_token_storage: Option<CardCVCTokenStorageDetails>,
/// The network transaction ID provided by the card network during a Customer Initiated Transaction (CIT)
/// when `setup_future_usage` is set to `off_session`.
#[schema(value_type = String)]
pub network_transaction_id: Option<masking::Secret<String>>,
/// The raw data associated with the payment method
#[schema(value_type = RawPaymentMethodData)]
pub raw_payment_method_data: Option<RawPaymentMethodData>,
/// Billing details of the payment method
#[schema(value_type = Option<Address>)]
pub billing: Option<payments::Address>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Copy, Debug, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct CardCVCTokenStorageDetails {
/// Indicates whether the card cvc is stored or not
#[schema(example = true)]
pub is_stored: bool,
/// A timestamp (ISO 8601 code) that determines expiry for stored card cvc token
#[schema(value_type = Option<PrimitiveDateTime>, example = "2024-02-24T11:04:09.922Z")]
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub expires_at: Option<time::PrimitiveDateTime>,
}
#[cfg(feature = "v2")]
impl CardCVCTokenStorageDetails {
pub fn generate_expiry_timestamp(duration_in_secs: i64) -> Self {
let current_time = common_utils::date_time::now();
let expiry_time = current_time + time::Duration::seconds(duration_in_secs);
Self {
is_stored: true,
expires_at: Some(expiry_time),
}
}
}
#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum PaymentMethodsData {
Card(CardDetailsPaymentMethod),
BankDetails(PaymentMethodDataBankCreds),
WalletDetails(PaymentMethodDataWalletInfo),
}
impl PaymentMethodsData {
pub fn get_card_details(&self) -> Option<CardDetailsPaymentMethod> {
match self {
Self::Card(card_details) => Some(card_details.clone()),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct ExternalVaultTokenData {
/// Tokenized reference for Card Number
pub tokenized_card_number: masking::Secret<String>,
}
#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct CardDetailsPaymentMethod {
pub last4_digits: Option<String>,
pub issuer_country: Option<String>,
pub issuer_country_code: 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,
pub co_badged_card_data: Option<CoBadgedCardDataToBeSaved>,
}
impl From<&CoBadgedCardData> for CoBadgedCardDataToBeSaved {
fn from(co_badged_card_data: &CoBadgedCardData) -> Self {
Self {
co_badged_card_networks: co_badged_card_data
.co_badged_card_networks_info
.get_card_networks(),
issuer_country_code: co_badged_card_data.issuer_country_code,
is_regulated: co_badged_card_data.is_regulated,
regulated_name: co_badged_card_data.regulated_name.clone(),
}
}
}
#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct CoBadgedCardData {
pub co_badged_card_networks_info: open_router::CoBadgedCardNetworks,
pub issuer_country_code: common_enums::CountryAlpha2,
pub is_regulated: bool,
pub regulated_name: Option<common_enums::RegulatedName>,
}
#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct CoBadgedCardDataToBeSaved {
pub co_badged_card_networks: Vec<common_enums::CardNetwork>,
pub issuer_country_code: common_enums::CountryAlpha2,
pub is_regulated: bool,
pub regulated_name: Option<common_enums::RegulatedName>,
}
impl From<CoBadgedCardDataToBeSaved> for CoBadgedCardData {
fn from(data: CoBadgedCardDataToBeSaved) -> Self {
Self {
co_badged_card_networks_info: open_router::CoBadgedCardNetworks(
data.co_badged_card_networks
.iter()
.map(|card_network| open_router::CoBadgedCardNetworksInfo {
network: card_network.clone(),
saving_percentage: None,
})
.collect(),
),
issuer_country_code: data.issuer_country_code,
is_regulated: data.is_regulated,
regulated_name: data.regulated_name,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct NetworkTokenDetailsPaymentMethod {
#[schema(value_type = Option<String>, example = "4242")]
pub last4_digits: Option<String>,
#[schema(value_type = Option<CountryAlpha2>)]
pub issuer_country: Option<common_enums::CountryAlpha2>,
#[schema(value_type = Option<String>, example = "05")]
pub network_token_expiry_month: Option<masking::Secret<String>>,
#[schema(value_type = Option<String>, example = "27")]
pub network_token_expiry_year: Option<masking::Secret<String>>,
#[schema(value_type = Option<String>, example = "Card")]
pub nick_name: Option<masking::Secret<String>>,
#[schema(value_type = Option<String>, example = "John Doe")]
pub card_holder_name: Option<masking::Secret<String>>,
#[schema(value_type = Option<String>, example = "16712672")]
pub card_isin: Option<String>,
#[schema(value_type = Option<String>, example = "Bank of America")]
pub card_issuer: Option<String>,
#[schema(value_type = Option<CardNetwork>, example = "VISA")]
pub card_network: Option<api_enums::CardNetwork>,
#[schema(value_type = Option<String>, example = "Credit")]
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, ToSchema)]
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>,
/// The card's expiry month
#[schema(value_type = Option<String>,example = "10")]
pub card_exp_month: Option<masking::Secret<String>>,
/// The card's expiry year
#[schema(value_type = Option<String>,example = "25")]
pub card_exp_year: Option<masking::Secret<String>>,
/// Unique authorisation code for the payment
#[schema(value_type = Option<String>,example = "003225")]
pub auth_code: 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,
card_exp_month: item.card_exp_month,
card_exp_year: item.card_exp_year,
auth_code: item.auth_code,
}
}
}
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,
card_exp_month: item.card_exp_month,
card_exp_year: item.card_exp_year,
auth_code: item.auth_code,
}
}
}
impl From<payments::ApplepayPaymentMethod> for PaymentMethodDataWalletInfo {
fn from(item: payments::ApplepayPaymentMethod) -> Self {
Self {
last4: item
.display_name
.chars()
.rev()
.take(4)
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect(),
card_network: item.network,
card_type: Some(item.pm_type),
card_exp_month: item.card_exp_month,
card_exp_year: item.card_exp_year,
auth_code: item.auth_code,
}
}
}
impl TryFrom<PaymentMethodDataWalletInfo> for Box<payments::ApplepayPaymentMethod> {
type Error = error_stack::Report<errors::ValidationError>;
fn try_from(item: PaymentMethodDataWalletInfo) -> Result<Self, Self::Error> {
Ok(Self::new(payments::ApplepayPaymentMethod {
display_name: item.last4,
network: item.card_network,
pm_type: item.card_type.get_required_value("card_type")?,
card_exp_month: item.card_exp_month,
card_exp_year: item.card_exp_year,
auth_code: item.auth_code,
}))
}
}
#[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 LockerCardResponse {
card: Card,
metadata: Option<pii::SecretSerdeValue>,
}
impl LockerCardResponse {
pub fn new(card: Card, metadata: Option<pii::SecretSerdeValue>) -> Self {
Self { card, metadata }
}
pub fn get_card(&self) -> Card {
self.card.clone()
}
pub fn get_metadata(&self) -> Option<pii::SecretSerdeValue> {
self.metadata.clone()
}
}
#[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(feature = "v1")]
impl From<(Card, Option<common_enums::CardNetwork>)> for CardDetail {
fn from((card, card_network): (Card, Option<common_enums::CardNetwork>)) -> Self {
Self {
card_number: card.card_number.clone(),
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.map(masking::Secret::new),
card_cvc: None,
card_issuing_country: None,
card_issuing_country_code: None,
card_network,
card_issuer: None,
card_type: None,
}
}
}
#[cfg(feature = "v1")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct CardDetailFromLocker {
pub scheme: Option<String>,
pub issuer_country: Option<String>,
pub issuer_country_code: 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(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct CardDetailFromLocker {
#[schema(value_type = Option<CountryAlpha2>)]
pub issuer_country: Option<api_enums::CountryAlpha2>,
#[schema(value_type = Option<String>, example = "4242")]
pub last4_digits: Option<String>,
#[serde(skip)]
#[schema(value_type=Option<String>)]
pub card_number: Option<CardNumber>,
#[schema(value_type=Option<String>, example = "10")]
pub expiry_month: Option<masking::Secret<String>>,
#[schema(value_type=Option<String>, example = "25")]
pub expiry_year: Option<masking::Secret<String>>,
#[schema(value_type=Option<String>, example = "John Doe")]
pub card_holder_name: Option<masking::Secret<String>>,
#[schema(value_type=Option<String>, example = "fingerprint_12345")]
pub card_fingerprint: Option<masking::Secret<String>>,
#[schema(value_type=Option<String>, example = "Card")]
pub nick_name: Option<masking::Secret<String>>,
#[schema(value_type = Option<CardNetwork>, example = "VISA")]
pub card_network: Option<api_enums::CardNetwork>,
#[schema(value_type=Option<String>, example = "4567890")]
pub card_isin: Option<String>,
#[schema(value_type=Option<String>, example = "Issuer Bank")]
pub card_issuer: Option<String>,
#[schema(value_type=Option<String>, example = "Credit")]
pub card_type: Option<String>,
#[schema(value_type=bool, example = true)]
pub saved_to_locker: bool,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct NetworkTokenResponse {
pub payment_method_data: NetworkTokenDetailsPaymentMethod,
}
fn saved_in_locker_default() -> bool {
true
}
#[cfg(feature = "v1")]
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,
card_issuing_country_code: item.issuer_country_code,
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,
is_regulated: None,
signature_network: None,
auth_code: None,
}
}
}
#[cfg(feature = "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()),
card_issuing_country_code: None,
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,
is_regulated: None,
signature_network: None,
auth_code: None,
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct PaymentMethodListResponseForSession {
/// 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<CustomerPaymentMethodResponseItem>,
}
#[cfg(feature = "v1")]
impl From<CardDetailsPaymentMethod> for CardDetailFromLocker {
fn from(item: CardDetailsPaymentMethod) -> Self {
Self {
scheme: None,
issuer_country: item.issuer_country,
issuer_country_code: item.issuer_country_code,
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(feature = "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(feature = "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(feature = "v1")]
impl From<CardDetail> for CardDetailFromLocker {
fn from(item: CardDetail) -> Self {
// scheme should be updated in case of co-badged cards
let card_scheme = item
.card_network
.clone()
.map(|card_network| card_network.to_string());
Self {
issuer_country: item.card_issuing_country,
issuer_country_code: item.card_issuing_country_code,
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,
scheme: card_scheme,
card_token: None,
}
}
}
#[cfg(feature = "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,
co_badged_card_data: None,
issuer_country_code: None,
}
}
}
#[cfg(feature = "v1")]
impl From<(CardDetailFromLocker, Option<&CoBadgedCardData>)> for CardDetailsPaymentMethod {
fn from(
(item, co_badged_card_data): (CardDetailFromLocker, Option<&CoBadgedCardData>),
) -> Self {
Self {
issuer_country: item.issuer_country,
issuer_country_code: item.issuer_country_code,
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,
co_badged_card_data: co_badged_card_data.map(CoBadgedCardDataToBeSaved::from),
}
}
}
#[cfg(feature = "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,
co_badged_card_data: None,
issuer_country_code: None,
}
}
}
#[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(feature = "v1")]
#[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>>,
#[schema(deprecated)]
/// The list of banks enabled, if applicable for a payment method type . To be deprecated soon.
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(feature = "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 {
#[schema(value_type = BankNames)]
bank_names: Vec<common_enums::BankNames>,
},
}
#[cfg(feature = "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>,
/// Indicates whether the payment method supports recurring payments. Optional.
#[schema(example = false)]
pub recurring_enabled: Option<bool>,
/// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional.
#[schema(example = true)]
pub installment_payment_enabled: Option<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(feature = "v1")]
//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 supports recurring payments. Optional.
#[schema(example = true)]
pub recurring_enabled: Option<bool>,
/// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional.
#[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(feature = "v1")]
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(feature = "v2")]
//List Payment Method
#[derive(Debug, Clone, serde::Serialize, Default, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct ListMethodsForPaymentMethodsRequest {
/// 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 supports recurring payments. Optional.
#[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(feature = "v2")]
impl<'de> serde::Deserialize<'de> for ListMethodsForPaymentMethodsRequest {
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 = ListMethodsForPaymentMethodsRequest;
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 = ListMethodsForPaymentMethodsRequest::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,
/// indicates the next action to be performed by the SDK
#[schema(value_type = SdkNextAction)]
pub sdk_next_action: payments::SdkNextAction,
/// indicates whether this is a guest customer flow
pub is_guest_customer: bool,
}
#[cfg(feature = "v1")]
#[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>,
}
// OLAP PML Response
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct CustomerPaymentMethodsListResponse {
/// List of payment methods for customer
pub customer_payment_methods: Vec<PaymentMethodResponseItem>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct GetTokenDataRequest {
/// Indicates the type of token to be fetched
pub token_type: api_enums::TokenDataType,
}
#[cfg(feature = "v2")]
impl common_utils::events::ApiEventMetric for GetTokenDataRequest {}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct TokenDataResponse {
/// The unique identifier of the payment method.
#[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")]
pub payment_method_id: id_type::GlobalPaymentMethodId,
/// token type of the payment method
#[schema(value_type = TokenDataType)]
pub token_type: api_enums::TokenDataType,
/// token details of the payment method
pub token_details: TokenDetailsResponse,
}
#[cfg(feature = "v2")]
impl common_utils::events::ApiEventMetric for TokenDataResponse {}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, ToSchema)]
#[serde(untagged)]
pub enum TokenDetailsResponse {
NetworkTokenDetails(NetworkTokenDetailsResponse),
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct NetworkTokenDetailsResponse {
/// Network token generated against the Card Number
#[schema(value_type = String)]
pub network_token: cards::NetworkToken,
/// Expiry month of the network token
#[schema(value_type = String)]
pub network_token_exp_month: masking::Secret<String>,
/// Expiry year of the network token
#[schema(value_type = String)]
pub network_token_exp_year: masking::Secret<String>,
/// Cryptogram generated by the Network
#[schema(value_type = Option<String>)]
pub cryptogram: Option<masking::Secret<String>>,
/// Issuer of the card
pub card_issuer: Option<String>,
/// Card network of the token
#[schema(value_type = Option<CardNetwork>)]
pub card_network: Option<common_enums::CardNetwork>,
/// Card type of the token
pub card_type: Option<CardType>,
/// Issuing country of the card
#[schema(value_type = Option<CountryAlpha2>)]
pub card_issuing_country: Option<common_enums::CountryAlpha2>,
/// Bank code of the card
pub bank_code: Option<String>,
/// Name of the card holder
#[schema(value_type = Option<String>)]
pub card_holder_name: Option<masking::Secret<String>>,
/// Nick name of the card holder
#[schema(value_type = Option<String>)]
pub nick_name: Option<masking::Secret<String>>,
/// ECI indicator of the card
pub eci: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct TotalPaymentMethodCountResponse {
/// total count of payment methods under the merchant
pub total_count: i64,
}
#[cfg(feature = "v2")]
impl common_utils::events::ApiEventMetric for TotalPaymentMethodCountResponse {}
#[cfg(feature = "v1")]
#[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(feature = "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 = "v2")]
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct PaymentMethodDeleteSessionResponse {
/// The unique identifier of the Payment method
#[schema(value_type = String, example = "token_9wcXDRVkfEtLEsSnYKgQ")]
pub payment_method_token: String,
}
#[cfg(feature = "v2")]
impl common_utils::events::ApiEventMetric for PaymentMethodDeleteSessionResponse {}
#[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(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct PaymentMethodResponseItem {
/// 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 supports recurring payments. Optional.
#[schema(example = true)]
pub recurring_enabled: Option<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(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct CustomerPaymentMethodResponseItem {
/// Temporary Token for payment method in vault which gets refreshed for every payment
#[schema(example = "7ebf443f-a050-4067-84e5-e6f6d4800aef")]
pub payment_method_token: String,
/// 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(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>,
}
#[cfg(feature = "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(feature = "v1")]
#[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 supports recurring payments. Optional.
#[schema(example = true)]
pub recurring_enabled: Option<bool>,
/// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional.
#[schema(example = true)]
pub installment_payment_enabled: Option<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>,
pub card_network: Option<api_enums::CardNetwork>,
}
#[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 card_holder_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: Option<masking::Secret<String>>,
pub payment_instrument_id: Option<masking::Secret<String>>,
pub connector_customer_id: Option<String>,
// Card fields are optional to support non-card CSV rows (e.g., ACH bank debit).
// For card rows these will still be populated normally from the CSV columns.
#[serde(default)]
pub card_number_masked: Option<masking::Secret<String>>,
#[serde(default)]
pub card_expiry_month: Option<masking::Secret<String>>,
#[serde(default)]
pub card_expiry_year: Option<masking::Secret<String>>,
pub card_scheme: Option<String>,
pub original_transaction_id: Option<String>,
pub billing_address_zip: Option<masking::Secret<String>>,
pub billing_address_state: Option<masking::Secret<String>>,
pub billing_address_first_name: Option<masking::Secret<String>>,
pub billing_address_last_name: Option<masking::Secret<String>>,
pub billing_address_city: Option<String>,
pub billing_address_country: Option<api_enums::CountryAlpha2>,
pub billing_address_line1: Option<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 merchant_connector_ids: Option<String>,
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>,
#[serde(default)]
pub account_number: Option<masking::Secret<String>>,
#[serde(default)]
pub routing_number: Option<masking::Secret<String>>,
}
#[cfg(feature = "v1")]
impl PaymentMethodRecord {
/// Constructs `PaymentMethodCreateData` from the CSV record fields.
/// Returns `None` for card records (cards are handled via `MigrateCardDetail`).
/// Extend the match arms here to support additional payment method types
/// (e.g., SEPA, BACS, wallets) in the future.
pub fn get_payment_method_data(&self) -> Option<PaymentMethodCreateData> {
match (self.account_number.as_ref(), self.routing_number.as_ref()) {
(Some(account_number), Some(routing_number))
if !account_number.peek().is_empty() && !routing_number.peek().is_empty() =>
{
Some(PaymentMethodCreateData::BankDebit(BankDebitDetail::Ach {
account_number: account_number.clone(),
routing_number: routing_number.clone(),
}))
}
_ => None,
}
}
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct UpdatePaymentMethodRecord {
pub payment_method_id: String,
pub status: Option<common_enums::PaymentMethodStatus>,
pub network_transaction_id: Option<String>,
pub line_number: Option<i64>,
pub payment_instrument_id: Option<masking::Secret<String>>,
pub connector_customer_id: Option<String>,
pub merchant_connector_ids: Option<String>,
pub card_expiry_month: Option<masking::Secret<String>>,
pub card_expiry_year: Option<masking::Secret<String>>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct PaymentMethodsBatchRecord {
pub payment_method_id: String,
#[serde(skip_deserializing, default)]
pub line_number: Option<i64>,
}
#[derive(Debug, serde::Serialize)]
pub struct PaymentMethodsBatchRetrieveResponse {
pub payment_method_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_type: Option<api_enums::PaymentMethod>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_subtype: Option<api_enums::PaymentMethodType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_data: Option<PaymentMethodsData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error_message: Option<String>,
pub line_number: Option<i64>,
}
impl common_utils::events::ApiEventMetric for PaymentMethodsBatchRecord {}
impl common_utils::events::ApiEventMetric for PaymentMethodsBatchRetrieveResponse {}
#[derive(Debug, serde::Serialize)]
pub struct PaymentMethodUpdateResponse {
pub payment_method_id: String,
pub status: Option<common_enums::PaymentMethodStatus>,
pub network_transaction_id: Option<String>,
pub connector_mandate_details: Option<pii::SecretSerdeValue>,
pub update_status: UpdateStatus,
#[serde(skip_serializing_if = "Option::is_none")]
pub update_error: Option<String>,
pub updated_payment_method_data: Option<bool>,
pub line_number: Option<i64>,
}
#[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 payment_method_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,
}
#[derive(Debug, Default, serde::Serialize)]
pub enum UpdateStatus {
Success,
#[default]
Failed,
}
impl PaymentMethodRecord {
fn create_address(&self) -> Option<payments::AddressDetails> {
if self.billing_address_first_name.is_some()
&& self.billing_address_line1.is_some()
&& self.billing_address_zip.is_some()
&& self.billing_address_city.is_some()
&& self.billing_address_country.is_some()
{
Some(payments::AddressDetails {
city: self.billing_address_city.clone(),
country: self.billing_address_country,
line1: self.billing_address_line1.clone(),
line2: self.billing_address_line2.clone(),
state: self.billing_address_state.clone(),
line3: self.billing_address_line3.clone(),
zip: self.billing_address_zip.clone(),
first_name: self.billing_address_first_name.clone(),
last_name: self.billing_address_last_name.clone(),
origin_zip: None,
})
} else {
None
}
}
fn create_phone(&self) -> Option<payments::PhoneDetails> {
if self.phone.is_some() || self.phone_country_code.is_some() {
Some(payments::PhoneDetails {
number: self.phone.clone(),
country_code: self.phone_country_code.clone(),
})
} else {
None
}
}
fn create_billing(&self) -> Option<payments::Address> {
let address = self.create_address();
let phone = self.create_phone();
if address.is_some() || phone.is_some() || self.email.is_some() {
Some(payments::Address {
address,
phone,
email: self.email.clone(),
})
} else {
None
}
}
}
#[cfg(feature = "v1")]
type PaymentMethodMigrationResponseType = (
Result<PaymentMethodMigrateResponse, String>,
PaymentMethodRecord,
);
#[cfg(feature = "v1")]
type PaymentMethodUpdateResponseType = (
Result<PaymentMethodRecordUpdateResponse, String>,
UpdatePaymentMethodRecord,
);
#[cfg(feature = "v1")]
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: record.card_number_masked.clone(),
line_number: record.line_number,
card_migrated: res.card_migrated,
payment_method_migrated: res.payment_method_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.clone()),
migration_status: MigrationStatus::Failed,
migration_error: Some(e),
card_number_masked: record.card_number_masked.clone(),
line_number: record.line_number,
..Self::default()
},
}
}
}
#[cfg(feature = "v1")]
impl From<PaymentMethodUpdateResponseType> for PaymentMethodUpdateResponse {
fn from((response, record): PaymentMethodUpdateResponseType) -> Self {
match response {
Ok(res) => Self {
payment_method_id: res.payment_method_id,
status: Some(res.status),
network_transaction_id: res.network_transaction_id,
connector_mandate_details: res.connector_mandate_details,
updated_payment_method_data: res.updated_payment_method_data,
update_status: UpdateStatus::Success,
update_error: None,
line_number: record.line_number,
},
Err(e) => Self {
payment_method_id: record.payment_method_id,
status: record.status,
network_transaction_id: record.network_transaction_id,
connector_mandate_details: None,
updated_payment_method_data: None,
update_status: UpdateStatus::Failed,
update_error: Some(e),
line_number: record.line_number,
},
}
}
}
#[cfg(feature = "v1")]
impl
TryFrom<(
&PaymentMethodRecord,
id_type::MerchantId,
Option<&Vec<id_type::MerchantConnectorAccountId>>,
)> for PaymentMethodMigrate
{
type Error = error_stack::Report<errors::ValidationError>;
fn try_from(
item: (
&PaymentMethodRecord,
id_type::MerchantId,
Option<&Vec<id_type::MerchantConnectorAccountId>>,
),
) -> Result<Self, Self::Error> {
let (record, merchant_id, mca_ids) = item;
let billing = record.create_billing();
let connector_mandate_details = if let Some(payment_instrument_id) =
&record.payment_instrument_id
{
let ids = mca_ids.get_required_value("mca_ids")?;
let mandate_map: HashMap<_, _> = ids
.iter()
.map(|mca_id| {
(
mca_id.clone(),
PaymentsMandateReferenceRecord {
connector_mandate_id: 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,
connector_customer_id: record.connector_customer_id.clone(),
},
)
})
.collect();
Some(PaymentsMandateReference(mandate_map))
} else {
None
};
let payment_method_data = record.get_payment_method_data();
let is_non_card = payment_method_data.is_some();
let card = if is_non_card {
None
} else {
Some(MigrateCardDetail {
card_number: record
.raw_card_number
.clone()
.unwrap_or_else(|| record.card_number_masked.clone().unwrap_or_default()),
card_exp_month: record.card_expiry_month.clone().unwrap_or_default(),
card_exp_year: record.card_expiry_year.clone().unwrap_or_default(),
card_holder_name: record.card_holder_name.clone().or(record.name.clone()),
card_network: None,
card_type: None,
card_issuer: None,
card_issuing_country: None,
card_issuing_country_code: None,
nick_name: record.nick_name.clone(),
})
};
let network_token = if is_non_card {
None
} else {
Some(MigrateNetworkTokenDetail {
network_token_data: MigrateNetworkTokenData {
network_token_number: record.network_token_number.clone().unwrap_or_default(),
network_token_exp_month: record
.network_token_expiry_month
.clone()
.unwrap_or_default(),
network_token_exp_year: record
.network_token_expiry_year
.clone()
.unwrap_or_default(),
card_holder_name: record.card_holder_name.clone().or(record.name.clone()),
nick_name: record.nick_name.clone(),
card_issuing_country: None,
card_issuing_country_code: None,
card_network: None,
card_issuer: None,
card_type: None,
},
network_token_requestor_ref_id: record
.network_token_requestor_ref_id
.clone()
.unwrap_or_default(),
})
};
Ok(Self {
merchant_id,
customer_id: Some(record.customer_id.clone()),
card,
network_token,
payment_method: record.payment_method,
payment_method_type: record.payment_method_type,
payment_method_issuer: None,
billing,
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,
network_transaction_id: record.original_transaction_id.clone(),
})
}
}
#[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 Issuing Country
pub card_issuing_country_code: 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_issuing_country_code: 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 = Option<String>, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
pub customer_id: Option<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>,
/// Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data
#[schema(value_type = Option<serde_json::Value>)]
pub tokenization_data: Option<pii::SecretSerdeValue>,
/// The storage type for the payment method
#[schema(value_type = StorageType)]
pub storage_type: common_enums::StorageType,
}
#[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>,
/// Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data
#[schema(value_type = Option<serde_json::Value>)]
pub tokenization_data: Option<pii::SecretSerdeValue>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct PaymentMethodSessionUpdateSavedPaymentMethod {
/// The payment method token associated with the payment method session
#[schema(value_type = String, example = "token_9wcXDRVkfEtLEsSnYKgQ")]
pub payment_method_token: String,
/// The update request for the payment method update
#[serde(flatten)]
pub payment_method_update_request: PaymentMethodUpdate,
}
#[cfg(feature = "v2")]
impl PaymentMethodSessionUpdateSavedPaymentMethod {
pub fn fetch_card_cvc_update(&self) -> Option<masking::Secret<String>> {
match &self.payment_method_update_request.payment_method_data {
Some(PaymentMethodUpdateData::Card(card_update)) => card_update.card_cvc.clone(),
_ => None,
}
}
pub fn is_payment_method_metadata_update(&self) -> bool {
match &self.payment_method_update_request.payment_method_data {
Some(PaymentMethodUpdateData::Card(card_update)) => {
card_update.card_holder_name.is_some() || card_update.nick_name.is_some()
}
_ => false,
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct PaymentMethodSessionDeleteSavedPaymentMethod {
/// The payment method token associated with the payment method to be deleted
#[schema(value_type = String, example = "token_9wcXDRVkfEtLEsSnYKgQ")]
pub payment_method_token: String,
}
#[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 = Option<PaymentMethodType>, example = "credit")]
pub payment_method_subtype: Option<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>,
/// The storage type for the payment method
#[schema(value_type = Option<StorageType>)]
pub storage_type: Option<common_enums::StorageType>,
}
#[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 = Option<String>, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")]
pub customer_id: Option<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>,
/// Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data
#[schema(value_type = Option<serde_json::Value>)]
pub tokenization_data: Option<pii::SecretSerdeValue>,
/// 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, example = "cs_9wcXDRVkfEtLEsSnYKgQ")]
pub client_secret: masking::Secret<String>,
/// The return url to which the user should be redirected to
#[schema(value_type = Option<String>, example = "https://merchant-website.com/return")]
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<AssociatedPaymentMethods>>)]
pub associated_payment_methods:
Option<Vec<common_types::payment_methods::AssociatedPaymentMethods>>,
/// The token-id created if there is tokenization_data present
#[schema(value_type = Option<String>, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")]
pub associated_token_id: Option<id_type::GlobalTokenId>,
/// The storage type for the payment method
#[schema(value_type = Option<StorageType>)]
pub storage_type: Option<common_enums::StorageType>,
/// Card CVC token storage details
#[schema(value_type = Option<CardCVCTokenStorageDetails>)]
pub card_cvc_token_storage: Option<CardCVCTokenStorageDetails>,
/// payment method data to be sent in session response
#[schema(value_type = Option<PaymentMethodResponseData>)]
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_data: Option<PaymentMethodResponseData>,
}
#[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>,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct NetworkTokenStatusCheckSuccessResponse {
/// The status of the network token
#[schema(value_type = TokenStatus)]
pub status: api_enums::TokenStatus,
/// The expiry month of the network token if active
#[schema(value_type = Option<String>)]
pub token_expiry_month: Option<masking::Secret<String>>,
/// The expiry year of the network token if active
#[schema(value_type = Option<String>)]
pub token_expiry_year: Option<masking::Secret<String>>,
/// The last four digits of the card if active
pub card_last_four: Option<String>,
/// The last four digits of the network token if active
pub token_last_four: Option<String>,
/// The expiry month of the card if active
#[schema(value_type = Option<String>)]
pub card_expiry_month: Option<masking::Secret<String>>,
/// The expiry year of the card if active
#[schema(value_type = Option<String>)]
pub card_expiry_year: Option<masking::Secret<String>>,
/// The payment method ID that was checked
#[schema(value_type = String, example = "12345_pm_019959146f92737389eb6927ce1eb7dc")]
pub payment_method_id: id_type::GlobalPaymentMethodId,
/// The customer ID associated with the payment method
#[schema(value_type = String, example = "12345_cus_0195dc62bb8e7312a44484536da76aef")]
pub customer_id: id_type::GlobalCustomerId,
}
#[cfg(feature = "v2")]
impl common_utils::events::ApiEventMetric for NetworkTokenStatusCheckResponse {}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct NetworkTokenStatusCheckFailureResponse {
/// Error message describing what went wrong
pub error_message: String,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, ToSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum NetworkTokenStatusCheckResponse {
/// Successful network token status check response
SuccessResponse(NetworkTokenStatusCheckSuccessResponse),
/// Error response for network token status check
FailureResponse(NetworkTokenStatusCheckFailureResponse),
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct NetworkTokenEligibilityRequest {
/// The card bin to retrieve information for
pub card_bin: String,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct GetNetworkTokenEiligibilityResponse {
/// Indicates if the card bin is eligible for network tokenization for the particular merchant
pub eligible_for_network_tokenization: bool,
}
#[cfg(feature = "v2")]
impl common_utils::events::ApiEventMetric for NetworkTokenEligibilityRequest {}
#[cfg(feature = "v2")]
impl common_utils::events::ApiEventMetric for GetNetworkTokenEiligibilityResponse {}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct PaymentMethodGetTokenDetailsResponse {
/// The payment method ID associated with the token
#[schema(value_type = String, example = "12345_pm_019959146f92737389eb6927ce1eb7dc")]
pub id: id_type::GlobalPaymentMethodId,
/// The token associated with the payment method
#[schema(value_type = String, example = "token_CSum555d9YxDOpGwYq6q")]
pub payment_method_token: String,
}
|
crates__api_models__src__payouts.rs
|
use std::collections::HashMap;
use cards::CardNumber;
use common_enums::CardNetwork;
#[cfg(feature = "v2")]
use common_utils::types::BrowserInformation;
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;
#[cfg(feature = "v1")]
use payments::BrowserInformation;
use router_derive::FlatStruct;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;
use crate::{admin, enums as api_enums, payment_methods::RequiredFieldInfo, payments};
#[derive(Debug, 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<id_type::PayoutId>,
/// 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>,
/// Your unique identifier for this payout or order. This ID helps you reconcile payouts on your system. If provided, it is passed to the connector if supported.
#[schema(value_type = Option<String>, max_length = 255, example = "merchant_order_ref_123")]
pub merchant_order_reference_id: Option<String>,
/// 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<StaticRoutingAlgorithm>, 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>,
/// Additional details required by 3DS 2.0
#[schema(value_type = Option<BrowserInformation>)]
pub browser_info: Option<BrowserInformation>,
}
impl PayoutCreateRequest {
pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> {
self.customer_id.as_ref().or(self
.customer
.as_ref()
.and_then(|customer| customer.id.as_ref()))
}
}
/// 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),
BankRedirect(BankRedirect),
Passthrough(Passthrough),
}
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>>,
/// The card's network
#[schema(value_type = Option<CardNetwork>, example = "Visa")]
pub card_network: Option<CardNetwork>,
}
#[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 {
ApplePayDecrypt(ApplePayDecrypt),
Paypal(Paypal),
Venmo(Venmo),
}
#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum BankRedirect {
Interac(Interac),
}
#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
pub struct Interac {
/// Customer email linked with interac account
#[schema(value_type = String, example = "john.doe@example.com")]
pub email: Email,
}
#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct Passthrough {
/// PSP token generated for the payout method
#[schema(value_type = String, example = "token_12345")]
pub psp_token: Secret<String>,
/// Payout method type of the token
#[schema(value_type = PaymentMethodType, example = "paypal")]
pub token_type: api_enums::PaymentMethodType,
}
#[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(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
pub struct ApplePayDecrypt {
/// The dpan number associated with card number
#[schema(value_type = String, example = "4242424242424242")]
pub dpan: 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>>,
/// The card's network
#[schema(value_type = Option<CardNetwork>, example = "Visa")]
pub card_network: Option<CardNetwork>,
}
#[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: id_type::PayoutId,
/// 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,
/// Your unique identifier for this payout or order. This ID helps you reconcile payouts on your system. If provided, it is passed to the connector if supported.
#[schema(value_type = Option<String>, max_length = 255, example = "merchant_order_ref_123")]
pub merchant_order_reference_id: Option<String>,
/// 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>),
#[schema(value_type = BankRedirectAdditionalData)]
BankRedirect(Box<payout_method_utils::BankRedirectAdditionalData>),
#[schema(value_type = PassthroughAddtionalData)]
Passthrough(Box<payout_method_utils::PassthroughAddtionalData>),
}
#[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(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: id_type::PayoutId,
/// `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(Debug, 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"
)]
pub payout_id: id_type::PayoutId,
}
#[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 = "payout_fafa124123", value_type = Option<String>,)]
pub starting_after: Option<id_type::PayoutId>,
/// A cursor for use in pagination, fetch the previous list before some object
#[schema(example = "payout_fafa124123", value_type = Option<String>,)]
pub ending_before: Option<id_type::PayoutId>,
/// 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<id_type::PayoutId>,
/// The merchant order reference ID for payout
#[schema(value_type = Option<String>, max_length = 255, example = "merchant_order_ref_123")]
pub merchant_order_reference_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 PayoutListFiltersV2 {
/// The list of available connector filters
#[schema(value_type = Vec<PayoutConnectors>)]
pub connector: HashMap<String, Vec<admin::MerchantConnectorInfo>>,
/// 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,
#[schema(value_type = String)]
pub payout_id: id_type::PayoutId,
}
#[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: id_type::PayoutId,
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: id_type::PayoutId,
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),
}))
}
Wallet::ApplePayDecrypt(ApplePayDecrypt {
expiry_month,
expiry_year,
card_holder_name,
..
}) => Self::ApplePayDecrypt(Box::new(
payout_method_utils::ApplePayDecryptAdditionalData {
card_exp_month: expiry_month,
card_exp_year: expiry_year,
card_holder_name,
},
)),
}
}
}
impl From<BankRedirect> for payout_method_utils::BankRedirectAdditionalData {
fn from(bank_redirect: BankRedirect) -> Self {
match bank_redirect {
BankRedirect::Interac(Interac { email }) => {
Self::Interac(Box::new(payout_method_utils::InteracAdditionalData {
email: Some(ForeignFrom::foreign_from(email)),
}))
}
}
}
}
impl From<Passthrough> for payout_method_utils::PassthroughAddtionalData {
fn from(passthrough_data: Passthrough) -> Self {
Self {
psp_token: passthrough_data.psp_token.into(),
token_type: passthrough_data.token_type,
}
}
}
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)
}
payout_method_utils::AdditionalPayoutMethodData::BankRedirect(bank_redirect) => {
Self::BankRedirect(bank_redirect)
}
payout_method_utils::AdditionalPayoutMethodData::Passthrough(passthrough) => {
Self::Passthrough(passthrough)
}
}
}
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct PayoutsAggregateResponse {
/// The list of intent status with their count
pub status_with_count: HashMap<common_enums::PayoutStatus, i64>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct PayoutsManualUpdateRequest {
/// The identifier for the payout
#[schema(value_type = String)]
pub payout_id: id_type::PayoutId,
/// The identifier for the payout attempt
pub payout_attempt_id: String,
/// Merchant ID
#[schema(value_type = String)]
pub merchant_id: id_type::MerchantId,
/// The status of the payout attempt
#[schema(value_type = Option<PayoutStatus>)]
pub status: Option<api_enums::PayoutStatus>,
/// Error code of the connector
pub error_code: Option<String>,
/// Error message of the connector
pub error_message: Option<String>,
/// A unique identifier for a payout provided by the connector
pub connector_payout_id: Option<String>,
}
impl PayoutsManualUpdateRequest {
pub fn is_update_parameter_present(&self) -> bool {
self.status.is_some()
|| self.error_code.is_some()
|| self.error_message.is_some()
|| self.connector_payout_id.is_some()
}
}
#[derive(Debug, serde::Serialize, Clone, ToSchema)]
pub struct PayoutsManualUpdateResponse {
/// The identifier for the payout
#[schema(value_type = String)]
pub payout_id: id_type::PayoutId,
/// The identifier for the payout attempt
pub payout_attempt_id: String,
/// Merchant ID
#[schema(value_type = String)]
pub merchant_id: id_type::MerchantId,
/// The status of the payout attempt
#[schema(value_type = PayoutStatus)]
pub attempt_status: api_enums::PayoutStatus,
/// Error code of the connector
pub error_code: Option<String>,
/// Error message of the connector
pub error_message: Option<String>,
/// A unique identifier for a payout provided by the connector
pub connector_payout_id: Option<String>,
}
|
crates__api_models__src__routing.rs
|
use std::{fmt::Debug, ops::Deref};
use common_types::three_ds_decision_rule_engine::{ThreeDSDecision, ThreeDSDecisionRule};
use common_utils::{
errors::{ParsingError, ValidationError},
ext_traits::ValueExt,
fp_utils, pii,
};
use euclid::frontend::ast::Program;
pub use euclid::{
dssa::types::EuclidAnalysable,
enums::RoutableConnectors,
frontend::{
ast,
dir::{DirKeyKind, EuclidDirFilter},
},
};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::{enums::TransactionType, open_router};
// Define constants for default values
const DEFAULT_LATENCY_THRESHOLD: f64 = 90.0;
const DEFAULT_BUCKET_SIZE: i32 = 200;
const DEFAULT_HEDGING_PERCENT: f64 = 5.0;
const DEFAULT_ELIMINATION_THRESHOLD: f64 = 0.35;
const DEFAULT_PAYMENT_METHOD: &str = "CARD";
const MAX_NAME_LENGTH: usize = 64;
#[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: StaticRoutingAlgorithm,
#[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 {
#[schema(value_type = Option<String>)]
pub name: Option<RoutingConfigName>,
pub description: Option<String>,
pub algorithm: Option<StaticRoutingAlgorithm>,
#[schema(value_type = Option<String>)]
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub transaction_type: Option<TransactionType>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(try_from = "String")]
#[schema(value_type = String)]
pub struct RoutingConfigName(String);
impl RoutingConfigName {
pub fn new(name: impl Into<String>) -> Result<Self, ValidationError> {
let name = name.into();
if name.len() > MAX_NAME_LENGTH {
return Err(ValidationError::InvalidValue {
message: format!(
"Length of name field must not exceed {} characters",
MAX_NAME_LENGTH
),
});
}
Ok(Self(name))
}
}
impl TryFrom<String> for RoutingConfigName {
type Error = ValidationError;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl Deref for RoutingConfigName {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[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>,
pub transaction_type: Option<TransactionType>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingActivatePayload {
pub transaction_type: Option<TransactionType>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingRetrieveLinkQuery {
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub transaction_type: Option<TransactionType>,
}
#[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(Box<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: RoutingAlgorithmWrapper,
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::ExtendedCardBin,
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::IssuerCountry,
DirKeyKind::BusinessCountry,
DirKeyKind::BusinessLabel,
DirKeyKind::MetaData,
DirKeyKind::RewardType,
DirKeyKind::VoucherType,
DirKeyKind::CardRedirectType,
DirKeyKind::BankTransferType,
DirKeyKind::RealTimePaymentType,
DirKeyKind::TransactionInitiator,
DirKeyKind::NetworkTokenType,
];
}
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, PartialEq, 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,
ThreeDsDecisionRule,
}
#[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(untagged)]
pub enum RoutingAlgorithmWrapper {
Static(StaticRoutingAlgorithm),
Dynamic(DynamicRoutingAlgorithm),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(untagged)]
pub enum DynamicRoutingAlgorithm {
EliminationBasedAlgorithm(EliminationRoutingConfig),
SuccessBasedAlgorithm(SuccessBasedRoutingConfig),
ContractBasedAlgorithm(ContractBasedRoutingConfig),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(
tag = "type",
content = "data",
rename_all = "snake_case",
try_from = "RoutingAlgorithmSerde"
)]
pub enum StaticRoutingAlgorithm {
Single(Box<RoutableConnectorChoice>),
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
#[schema(value_type=ProgramConnectorSelection)]
Advanced(Program<ConnectorSelection>),
#[schema(value_type=ProgramThreeDsDecisionRule)]
ThreeDsDecisionRule(Program<ThreeDSDecisionRule>),
}
#[derive(Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ProgramThreeDsDecisionRule {
pub default_selection: ThreeDSDecisionRule,
#[schema(value_type = RuleThreeDsDecisionRule)]
pub rules: Vec<ast::Rule<ThreeDSDecisionRule>>,
#[schema(value_type = HashMap<String, serde_json::Value>)]
pub metadata: std::collections::HashMap<String, serde_json::Value>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct RuleThreeDsDecisionRule {
pub name: String,
pub connector_selection: ThreeDSDecision,
#[schema(value_type = Vec<IfStatement>)]
pub statements: Vec<ast::IfStatement>,
}
impl StaticRoutingAlgorithm {
pub fn should_validate_connectors_in_routing_config(&self) -> bool {
match self {
Self::Single(_) | Self::Priority(_) | Self::VolumeSplit(_) | Self::Advanced(_) => true,
Self::ThreeDsDecisionRule(_) => false,
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum RoutingAlgorithmSerde {
Single(Box<RoutableConnectorChoice>),
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
Advanced(Program<ConnectorSelection>),
ThreeDsDecisionRule(Program<ThreeDSDecisionRule>),
}
impl TryFrom<RoutingAlgorithmSerde> for StaticRoutingAlgorithm {
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),
RoutingAlgorithmSerde::ThreeDsDecisionRule(i) => Self::ThreeDsDecisionRule(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 StaticRoutingAlgorithm {
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 StaticRoutingAlgorithm {
pub fn get_kind(&self) -> RoutingAlgorithmKind {
match self {
Self::Single(_) => RoutingAlgorithmKind::Single,
Self::Priority(_) => RoutingAlgorithmKind::Priority,
Self::VolumeSplit(_) => RoutingAlgorithmKind::VolumeSplit,
Self::Advanced(_) => RoutingAlgorithmKind::Advanced,
Self::ThreeDsDecisionRule(_) => RoutingAlgorithmKind::ThreeDsDecisionRule,
}
}
}
#[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>,
pub decision_engine_routing_id: Option<String>,
}
#[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>,
#[serde(default)]
pub is_merchant_created_in_decision_engine: bool,
}
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
}
pub fn update_merchant_creation_status_in_decision_engine(&mut self, is_created: bool) {
self.is_merchant_created_in_decision_engine = is_created;
}
pub fn is_success_rate_routing_enabled(&self) -> bool {
self.success_based_algorithm
.as_ref()
.map(|success_based_routing| {
if success_based_routing
.algorithm_id_with_timestamp
.algorithm_id
.is_none()
{
return false;
}
success_based_routing.enabled_feature
== DynamicRoutingFeatures::DynamicConnectorSelection
})
.unwrap_or_default()
}
pub fn is_elimination_enabled(&self) -> bool {
self.elimination_routing_algorithm
.as_ref()
.map(|elimination_routing| {
if elimination_routing
.algorithm_id_with_timestamp
.algorithm_id
.is_none()
{
return false;
}
elimination_routing.enabled_feature
== DynamicRoutingFeatures::DynamicConnectorSelection
})
.unwrap_or_default()
}
}
#[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 update_feature(
&mut self,
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(None),
enabled_feature,
})
}
DynamicRoutingType::EliminationRouting => {
self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature,
})
}
DynamicRoutingType::ContractBasedRouting => {
self.contract_based_routing = Some(ContractRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
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, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct CreateDynamicRoutingQuery {
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(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct CreateDynamicRoutingWrapper {
pub profile_id: common_utils::id_type::ProfileId,
pub feature_to_enable: DynamicRoutingFeatures,
pub payload: Option<DynamicRoutingPayload>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum DynamicRoutingPayload {
SuccessBasedRoutingPayload(SuccessBasedRoutingConfig),
EliminationRoutingPayload(EliminationRoutingConfig),
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct RoutingVolumeSplitResponse {
pub split: u8,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct EliminationRoutingConfig {
pub params: Option<Vec<DynamicRoutingConfigParams>>,
pub elimination_analyser_config: Option<EliminationAnalyserConfig>,
#[schema(value_type = DecisionEngineEliminationData)]
pub decision_engine_configs: Option<open_router::DecisionEngineEliminationData>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct EliminationAnalyserConfig {
pub bucket_size: Option<u64>,
pub bucket_leak_interval_in_secs: Option<u64>,
}
impl EliminationAnalyserConfig {
pub fn update(&mut self, new: Self) {
if let Some(bucket_size) = new.bucket_size {
self.bucket_size = Some(bucket_size)
}
if let Some(bucket_leak_interval_in_secs) = new.bucket_leak_interval_in_secs {
self.bucket_leak_interval_in_secs = Some(bucket_leak_interval_in_secs)
}
}
}
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(60),
}),
decision_engine_configs: None,
}
}
}
impl EliminationRoutingConfig {
pub fn update(&mut self, new: Self) {
if let Some(params) = new.params {
self.params = Some(params)
}
if let Some(new_config) = new.elimination_analyser_config {
self.elimination_analyser_config
.as_mut()
.map(|config| config.update(new_config));
}
if let Some(new_config) = new.decision_engine_configs {
self.decision_engine_configs
.as_mut()
.map(|config| config.update(new_config));
}
}
pub fn open_router_config_default() -> Self {
Self {
elimination_analyser_config: None,
params: None,
decision_engine_configs: Some(open_router::DecisionEngineEliminationData {
threshold: DEFAULT_ELIMINATION_THRESHOLD,
}),
}
}
pub fn get_decision_engine_configs(
&self,
) -> Result<open_router::DecisionEngineEliminationData, error_stack::Report<ValidationError>>
{
self.decision_engine_configs
.clone()
.ok_or(error_stack::Report::new(
ValidationError::MissingRequiredField {
field_name: "decision_engine_configs".to_string(),
},
))
}
pub fn validate(&self) -> Result<(), error_stack::Report<ValidationError>> {
fp_utils::when(
self.params.is_none()
&& self.elimination_analyser_config.is_none()
&& self.decision_engine_configs.is_none(),
|| {
Err(ValidationError::MissingRequiredField {
field_name: "All fields in EliminationRoutingConfig cannot be null".to_string(),
}
.into())
},
)
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct SuccessBasedRoutingConfig {
pub params: Option<Vec<DynamicRoutingConfigParams>>,
pub config: Option<SuccessBasedRoutingConfigBody>,
#[schema(value_type = DecisionEngineSuccessRateData)]
pub decision_engine_configs: Option<open_router::DecisionEngineSuccessRateData>,
}
impl Default for SuccessBasedRoutingConfig {
fn default() -> Self {
Self {
params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]),
config: Some(SuccessBasedRoutingConfigBody {
min_aggregates_size: Some(5),
default_success_rate: Some(100.0),
max_aggregates_size: Some(8),
current_block_threshold: Some(CurrentBlockThreshold {
duration_in_mins: None,
max_total_count: Some(5),
}),
specificity_level: SuccessRateSpecificityLevel::default(),
exploration_percent: Some(20.0),
shuffle_on_tie_during_exploitation: Some(false),
}),
decision_engine_configs: None,
}
}
}
#[derive(
serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema, PartialEq, 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,
pub exploration_percent: Option<f64>,
pub shuffle_on_tie_during_exploitation: Option<bool>,
}
#[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, Copy, 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 EliminationRoutingPayloadWrapper {
pub updated_config: EliminationRoutingConfig,
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));
}
if let Some(new_config) = new.decision_engine_configs {
self.decision_engine_configs
.as_mut()
.map(|config| config.update(new_config));
}
}
pub fn open_router_config_default() -> Self {
Self {
params: None,
config: None,
decision_engine_configs: Some(open_router::DecisionEngineSuccessRateData {
default_latency_threshold: Some(DEFAULT_LATENCY_THRESHOLD),
default_bucket_size: Some(DEFAULT_BUCKET_SIZE),
default_hedging_percent: Some(DEFAULT_HEDGING_PERCENT),
default_lower_reset_factor: None,
default_upper_reset_factor: None,
default_gateway_extra_score: None,
sub_level_input_config: Some(vec![
open_router::DecisionEngineSRSubLevelInputConfig {
payment_method_type: Some(DEFAULT_PAYMENT_METHOD.to_string()),
payment_method: None,
latency_threshold: None,
bucket_size: Some(DEFAULT_BUCKET_SIZE),
hedging_percent: Some(DEFAULT_HEDGING_PERCENT),
lower_reset_factor: None,
upper_reset_factor: None,
gateway_extra_score: None,
},
]),
}),
}
}
pub fn get_decision_engine_configs(
&self,
) -> Result<open_router::DecisionEngineSuccessRateData, error_stack::Report<ValidationError>>
{
self.decision_engine_configs
.clone()
.ok_or(error_stack::Report::new(
ValidationError::MissingRequiredField {
field_name: "decision_engine_configs".to_string(),
},
))
}
pub fn validate(&self) -> Result<(), error_stack::Report<ValidationError>> {
fp_utils::when(
self.params.is_none()
&& self.config.is_none()
&& self.decision_engine_configs.is_none(),
|| {
Err(ValidationError::MissingRequiredField {
field_name: "All fields in SuccessBasedRoutingConfig cannot be null"
.to_string(),
}
.into())
},
)
}
}
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;
if let Some(exploration_percent) = new.exploration_percent {
self.exploration_percent = Some(exploration_percent);
}
if let Some(shuffle_on_tie_during_exploitation) = new.shuffle_on_tie_during_exploitation {
self.shuffle_on_tie_during_exploitation = Some(shuffle_on_tie_during_exploitation);
}
}
}
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,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalSuccessRateConfigEventRequest {
pub min_aggregates_size: Option<u32>,
pub default_success_rate: Option<f64>,
pub specificity_level: SuccessRateSpecificityLevel,
pub exploration_percent: Option<f64>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalSuccessRateEventRequest {
pub id: String,
pub params: String,
pub labels: Vec<String>,
pub config: Option<CalSuccessRateConfigEventRequest>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct EliminationRoutingEventBucketConfig {
pub bucket_size: Option<u64>,
pub bucket_leak_interval_in_secs: Option<u64>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct EliminationRoutingEventRequest {
pub id: String,
pub params: String,
pub labels: Vec<String>,
pub config: Option<EliminationRoutingEventBucketConfig>,
}
/// API-1 types
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalContractScoreEventRequest {
pub id: String,
pub params: String,
pub labels: Vec<String>,
pub config: Option<ContractBasedRoutingConfig>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct LabelWithScoreEventResponse {
pub score: f64,
pub label: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalSuccessRateEventResponse {
pub labels_with_score: Vec<LabelWithScoreEventResponse>,
pub routing_approach: RoutingApproach,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RoutingApproach {
Exploitation,
Exploration,
Elimination,
ContractBased,
Default,
}
impl RoutingApproach {
pub fn from_decision_engine_approach(approach: &str) -> Self {
match approach {
"SR_SELECTION_V3_ROUTING" => Self::Exploitation,
"SR_V3_HEDGING" => Self::Exploration,
_ => Self::Default,
}
}
}
impl std::fmt::Display for RoutingApproach {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Exploitation => write!(f, "Exploitation"),
Self::Exploration => write!(f, "Exploration"),
Self::Elimination => write!(f, "Elimination"),
Self::ContractBased => write!(f, "ContractBased"),
Self::Default => write!(f, "Default"),
}
}
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RuleMigrationQuery {
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_id: common_utils::id_type::MerchantId,
pub limit: Option<u32>,
pub offset: Option<u32>,
}
impl RuleMigrationQuery {
pub fn validated_limit(&self) -> u32 {
self.limit.unwrap_or(50).min(1000)
}
}
#[derive(Debug, serde::Serialize)]
pub struct RuleMigrationResult {
pub success: Vec<RuleMigrationResponse>,
pub errors: Vec<RuleMigrationError>,
}
#[derive(Debug, serde::Serialize)]
pub struct RuleMigrationResponse {
pub profile_id: common_utils::id_type::ProfileId,
pub euclid_algorithm_id: common_utils::id_type::RoutingId,
pub decision_engine_algorithm_id: String,
pub is_active_rule: bool,
}
#[derive(Debug, serde::Serialize)]
pub struct RuleMigrationError {
pub profile_id: common_utils::id_type::ProfileId,
pub algorithm_id: common_utils::id_type::RoutingId,
pub error: String,
}
impl RuleMigrationResponse {
pub fn new(
profile_id: common_utils::id_type::ProfileId,
euclid_algorithm_id: common_utils::id_type::RoutingId,
decision_engine_algorithm_id: String,
is_active_rule: bool,
) -> Self {
Self {
profile_id,
euclid_algorithm_id,
decision_engine_algorithm_id,
is_active_rule,
}
}
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RoutingResultSource {
/// External Decision Engine
DecisionEngine,
/// Inbuilt Hyperswitch Routing Engine
HyperswitchRouting,
}
//TODO: temporary change will be refactored afterwards
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, ToSchema)]
pub struct RoutingEvaluateRequest {
pub created_by: String,
#[schema(value_type = Object)]
///Parameters that can be used in the routing evaluate request.
///eg: {"parameters": {
/// "payment_method": {"type": "enum_variant", "value": "card"},
/// "payment_method_type": {"type": "enum_variant", "value": "credit"},
/// "amount": {"type": "number", "value": 10},
/// "currency": {"type": "str_value", "value": "INR"},
/// "authentication_type": {"type": "enum_variant", "value": "three_ds"},
/// "card_bin": {"type": "str_value", "value": "424242"},
/// "capture_method": {"type": "enum_variant", "value": "scheduled"},
/// "business_country": {"type": "str_value", "value": "IN"},
/// "billing_country": {"type": "str_value", "value": "IN"},
/// "business_label": {"type": "str_value", "value": "business_label"},
/// "setup_future_usage": {"type": "enum_variant", "value": "off_session"},
/// "card_network": {"type": "enum_variant", "value": "visa"},
/// "payment_type": {"type": "enum_variant", "value": "recurring_mandate"},
/// "mandate_type": {"type": "enum_variant", "value": "single_use"},
/// "mandate_acceptance_type": {"type": "enum_variant", "value": "online"},
/// "metadata":{"type": "metadata_variant", "value": {"key": "key1", "value": "value1"}}
/// }}
pub parameters: std::collections::HashMap<String, Option<ValueType>>,
pub fallback_output: Vec<DeRoutableConnectorChoice>,
}
impl common_utils::events::ApiEventMetric for RoutingEvaluateRequest {}
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
pub struct RoutingEvaluateResponse {
pub status: String,
pub output: serde_json::Value,
#[serde(deserialize_with = "deserialize_connector_choices")]
pub evaluated_output: Vec<RoutableConnectorChoice>,
#[serde(deserialize_with = "deserialize_connector_choices")]
pub eligible_connectors: Vec<RoutableConnectorChoice>,
}
impl common_utils::events::ApiEventMetric for RoutingEvaluateResponse {}
fn deserialize_connector_choices<'de, D>(
deserializer: D,
) -> Result<Vec<RoutableConnectorChoice>, D::Error>
where
D: serde::Deserializer<'de>,
{
let infos = Vec::<DeRoutableConnectorChoice>::deserialize(deserializer)?;
Ok(infos
.into_iter()
.map(RoutableConnectorChoice::from)
.collect())
}
impl From<DeRoutableConnectorChoice> for RoutableConnectorChoice {
fn from(choice: DeRoutableConnectorChoice) -> Self {
Self {
choice_kind: RoutableChoiceKind::FullStruct,
connector: choice.gateway_name,
merchant_connector_id: choice.gateway_id,
}
}
}
/// Routable Connector chosen for a payment
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct DeRoutableConnectorChoice {
pub gateway_name: RoutableConnectors,
#[schema(value_type = String)]
pub gateway_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
/// Represents a value in the DSL
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum ValueType {
/// Represents a number literal
Number(u64),
/// Represents an enum variant
EnumVariant(String),
/// Represents a Metadata variant
MetadataVariant(MetadataValue),
/// Represents a arbitrary String value
StrValue(String),
/// Represents a global reference, which is a reference to a global variable
GlobalRef(String),
/// Represents an array of numbers. This is basically used for
/// "one of the given numbers" operations
/// eg: payment.method.amount = (1, 2, 3)
NumberArray(Vec<u64>),
/// Similar to NumberArray but for enum variants
/// eg: payment.method.cardtype = (debit, credit)
EnumVariantArray(Vec<String>),
/// Like a number array but can include comparisons. Useful for
/// conditions like "500 < amount < 1000"
/// eg: payment.amount = (> 500, < 1000)
NumberComparisonArray(Vec<NumberComparison>),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
pub struct MetadataValue {
pub key: String,
pub value: String,
}
/// Represents a number comparison for "NumberComparisonArrayValue"
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct NumberComparison {
pub comparison_type: ComparisonType,
pub number: u64,
}
/// Conditional comparison type
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ComparisonType {
Equal,
NotEqual,
LessThan,
LessThanEqual,
GreaterThan,
GreaterThanEqual,
}
|
crates__api_models__src__subscription.rs
|
use common_enums::{InvoiceStatus, SubscriptionStatus};
use common_types::payments::CustomerAcceptance;
use common_utils::{
errors::ValidationError,
events::ApiEventMetric,
fp_utils,
id_type::{
CustomerId, InvoiceId, MerchantConnectorAccountId, MerchantId, PaymentId, ProfileId,
SubscriptionId,
},
types::{MinorUnit, Url},
};
use masking::Secret;
use utoipa::ToSchema;
use crate::{
enums::{
AuthenticationType, CaptureMethod, Currency, FutureUsage, IntentStatus, PaymentExperience,
PaymentMethod, PaymentMethodType, PaymentType,
},
mandates::RecurringDetails,
payments::{Address, NextActionData, PaymentMethodDataRequest},
};
/// Request payload for creating a subscription.
///
/// This struct captures details required to create a subscription,
/// including plan, profile, merchant connector, and optional customer info.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct CreateSubscriptionRequest {
/// Merchant specific Unique identifier.
pub merchant_reference_id: Option<String>,
/// Identifier for the associated item_price_id for the subscription.
pub item_price_id: String,
/// Identifier for the subscription plan.
pub plan_id: Option<String>,
/// Optional coupon code applied to the subscription.
pub coupon_code: Option<String>,
/// customer ID associated with this subscription.
pub customer_id: CustomerId,
/// payment details for the subscription.
pub payment_details: CreateSubscriptionPaymentDetails,
/// billing address for the subscription.
pub billing: Option<Address>,
/// shipping address for the subscription.
pub shipping: Option<Address>,
}
/// Response payload returned after successfully creating a subscription.
///
/// Includes details such as subscription ID, status, plan, merchant, and customer info.
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct SubscriptionResponse {
/// Unique identifier for the subscription.
pub id: SubscriptionId,
/// Merchant specific Unique identifier.
pub merchant_reference_id: Option<String>,
/// Current status of the subscription.
pub status: SubscriptionStatus,
/// Identifier for the associated subscription plan.
pub plan_id: Option<String>,
/// Identifier for the associated item_price_id for the subscription.
pub item_price_id: Option<String>,
/// Associated profile ID.
pub profile_id: ProfileId,
#[schema(value_type = Option<String>)]
/// 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<Secret<String>>,
/// Merchant identifier owning this subscription.
pub merchant_id: MerchantId,
/// Optional coupon code applied to this subscription.
pub coupon_code: Option<String>,
/// Optional customer ID associated with this subscription.
pub customer_id: CustomerId,
/// Payment details for the invoice.
pub payment: Option<PaymentResponseData>,
/// Invoice Details for the subscription.
pub invoice: Option<Invoice>,
}
impl SubscriptionResponse {
/// Creates a new [`CreateSubscriptionResponse`] with the given identifiers.
///
/// By default, `client_secret`, `coupon_code`, and `customer` fields are `None`.
#[allow(clippy::too_many_arguments)]
pub fn new(
id: SubscriptionId,
merchant_reference_id: Option<String>,
status: SubscriptionStatus,
plan_id: Option<String>,
item_price_id: Option<String>,
profile_id: ProfileId,
merchant_id: MerchantId,
client_secret: Option<Secret<String>>,
customer_id: CustomerId,
payment: Option<PaymentResponseData>,
invoice: Option<Invoice>,
) -> Self {
Self {
id,
merchant_reference_id,
status,
plan_id,
item_price_id,
profile_id,
client_secret,
merchant_id,
coupon_code: None,
customer_id,
payment,
invoice,
}
}
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct GetSubscriptionItemsResponse {
pub item_id: String,
pub name: String,
pub description: Option<String>,
pub price_id: Vec<SubscriptionItemPrices>,
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct SubscriptionItemPrices {
pub price_id: String,
// This can be plan_id or addon_id
pub item_id: Option<String>,
pub amount: MinorUnit,
pub currency: Currency,
pub interval: PeriodUnit,
pub interval_count: i64,
pub trial_period: Option<i64>,
pub trial_period_unit: Option<PeriodUnit>,
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub enum PeriodUnit {
Day,
Week,
Month,
Year,
}
/// For Client based calls, SDK will use the client_secret\nin order to call /payment_methods\nClient secret will be generated whenever a new\npayment method is created
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ClientSecret(String);
impl ClientSecret {
pub fn new(secret: String) -> Self {
Self(secret)
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn as_string(&self) -> &String {
&self.0
}
}
#[derive(serde::Deserialize, serde::Serialize, Debug, ToSchema)]
pub struct GetSubscriptionItemsQuery {
#[schema(value_type = Option<String>)]
/// 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<ClientSecret>,
pub limit: Option<u32>,
pub offset: Option<u32>,
pub item_type: SubscriptionItemType,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "lowercase")]
pub enum SubscriptionItemType {
/// This is a subscription plan
Plan,
/// This is a subscription addon
Addon,
}
impl ApiEventMetric for SubscriptionResponse {}
impl ApiEventMetric for CreateSubscriptionRequest {}
impl ApiEventMetric for GetSubscriptionItemsQuery {}
impl ApiEventMetric for GetSubscriptionItemsResponse {}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ConfirmSubscriptionPaymentDetails {
pub shipping: Option<Address>,
pub billing: Option<Address>,
pub payment_method: PaymentMethod,
pub payment_method_type: Option<PaymentMethodType>,
pub payment_method_data: Option<PaymentMethodDataRequest>,
pub customer_acceptance: Option<CustomerAcceptance>,
pub payment_type: Option<PaymentType>,
#[schema(value_type = Option<String>, example = "token_sxJdmpUnpNsJk5VWzcjl")]
pub payment_token: Option<Secret<String>>,
}
impl ConfirmSubscriptionPaymentDetails {
pub fn validate(&self) -> Result<(), error_stack::Report<ValidationError>> {
fp_utils::when(
self.payment_method_data.is_none() && self.payment_token.is_none(),
|| {
Err(ValidationError::MissingRequiredField {
field_name: String::from(
"Either payment_method_data or payment_token must be present",
),
}
.into())
},
)
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct CreateSubscriptionPaymentDetails {
/// The url to which user must be redirected to after completion of the purchase
#[schema(value_type = String)]
pub return_url: Url,
pub setup_future_usage: Option<FutureUsage>,
pub capture_method: Option<CaptureMethod>,
pub authentication_type: Option<AuthenticationType>,
pub payment_type: Option<PaymentType>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct PaymentDetails {
pub payment_method: Option<PaymentMethod>,
pub payment_method_type: Option<PaymentMethodType>,
pub payment_method_data: Option<PaymentMethodDataRequest>,
pub setup_future_usage: Option<FutureUsage>,
pub customer_acceptance: Option<CustomerAcceptance>,
/// The url to which user must be redirected to after completion of the purchase
#[schema(value_type = Option<String>)]
pub return_url: Option<Url>,
pub capture_method: Option<CaptureMethod>,
pub authentication_type: Option<AuthenticationType>,
pub payment_type: Option<PaymentType>,
#[schema(value_type = Option<String>, example = "pm_01926c58bc6e77c09e809964e72af8c8")]
pub payment_method_id: Option<Secret<String>>,
}
impl PaymentDetails {
pub fn validate(&self) -> Result<(), error_stack::Report<ValidationError>> {
fp_utils::when(
self.payment_method_data.is_none() && self.payment_method_id.is_none(),
|| {
Err(ValidationError::MissingRequiredField {
field_name: String::from(
"Either payment_method_data or payment_method_id must be present",
),
}
.into())
},
)
}
}
// Creating new type for PaymentRequest API call as usage of api_models::PaymentsRequest will result in invalid payment request during serialization
// Eg: Amount will be serialized as { amount: {Value: 100 }}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct CreatePaymentsRequestData {
pub amount: MinorUnit,
pub currency: Currency,
pub customer_id: Option<CustomerId>,
pub billing: Option<Address>,
pub shipping: Option<Address>,
pub profile_id: Option<ProfileId>,
pub setup_future_usage: Option<FutureUsage>,
/// The url to which user must be redirected to after completion of the purchase
#[schema(value_type = Option<String>)]
pub return_url: Option<Url>,
pub capture_method: Option<CaptureMethod>,
pub authentication_type: Option<AuthenticationType>,
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct ConfirmPaymentsRequestData {
pub billing: Option<Address>,
pub shipping: Option<Address>,
pub profile_id: Option<ProfileId>,
pub payment_method: PaymentMethod,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_type: Option<PaymentMethodType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_data: Option<PaymentMethodDataRequest>,
pub customer_acceptance: Option<CustomerAcceptance>,
pub payment_type: Option<PaymentType>,
#[serde(skip_serializing_if = "Option::is_none")]
#[schema(value_type = Option<String>, example = "token_sxJdmpUnpNsJk5VWzcjl")]
pub payment_token: Option<Secret<String>>,
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct CreateAndConfirmPaymentsRequestData {
pub amount: MinorUnit,
pub currency: Currency,
pub customer_id: Option<CustomerId>,
pub confirm: bool,
pub billing: Option<Address>,
pub shipping: Option<Address>,
pub profile_id: Option<ProfileId>,
pub setup_future_usage: Option<FutureUsage>,
/// The url to which user must be redirected to after completion of the purchase
#[schema(value_type = Option<String>)]
pub return_url: Option<Url>,
pub capture_method: Option<CaptureMethod>,
pub authentication_type: Option<AuthenticationType>,
pub payment_method: Option<PaymentMethod>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_type: Option<PaymentMethodType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_data: Option<PaymentMethodDataRequest>,
pub customer_acceptance: Option<CustomerAcceptance>,
pub payment_type: Option<PaymentType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub recurring_details: Option<RecurringDetails>,
#[serde(skip_serializing_if = "Option::is_none")]
pub off_session: Option<bool>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct PaymentResponseData {
pub payment_id: PaymentId,
pub status: IntentStatus,
pub amount: MinorUnit,
pub currency: Currency,
pub profile_id: Option<ProfileId>,
pub connector: Option<String>,
/// Identifier for Payment Method
#[schema(value_type = Option<String>, example = "pm_01926c58bc6e77c09e809964e72af8c8")]
pub payment_method_id: Option<Secret<String>>,
/// The url to which user must be redirected to after completion of the purchase
#[schema(value_type = Option<String>)]
pub return_url: Option<Url>,
pub next_action: Option<NextActionData>,
pub payment_experience: Option<PaymentExperience>,
pub error_code: Option<String>,
pub error_message: Option<String>,
pub payment_method_type: Option<PaymentMethodType>,
#[schema(value_type = Option<String>)]
/// 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<Secret<String>>,
pub billing: Option<Address>,
pub shipping: Option<Address>,
pub payment_type: Option<PaymentType>,
#[schema(value_type = Option<String>, example = "token_sxJdmpUnpNsJk5VWzcjl")]
pub payment_token: Option<Secret<String>>,
}
impl PaymentResponseData {
pub fn get_billing_address(&self) -> Option<Address> {
self.billing.clone()
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct CreateMitPaymentRequestData {
pub amount: MinorUnit,
pub currency: Currency,
pub confirm: bool,
pub customer_id: Option<CustomerId>,
pub recurring_details: Option<RecurringDetails>,
pub off_session: Option<bool>,
pub profile_id: Option<ProfileId>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ConfirmSubscriptionRequest {
#[schema(value_type = Option<String>)]
/// 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<ClientSecret>,
/// Payment details for the invoice.
pub payment_details: ConfirmSubscriptionPaymentDetails,
}
impl ConfirmSubscriptionRequest {
pub fn get_billing_address(&self) -> Option<Address> {
self.payment_details
.payment_method_data
.as_ref()
.and_then(|data| data.billing.clone())
.or(self.payment_details.billing.clone())
}
// Perform validation on ConfirmSubscriptionRequest fields
pub fn validate(&self) -> Result<(), error_stack::Report<ValidationError>> {
self.payment_details.validate()
}
}
impl ApiEventMetric for ConfirmSubscriptionRequest {}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct CreateAndConfirmSubscriptionRequest {
/// Identifier for the associated plan_id.
pub plan_id: Option<String>,
/// Identifier for the associated item_price_id for the subscription.
pub item_price_id: String,
/// Identifier for the coupon code for the subscription.
pub coupon_code: Option<String>,
/// Identifier for customer.
pub customer_id: CustomerId,
/// Billing address for the subscription.
pub billing: Option<Address>,
/// Shipping address for the subscription.
pub shipping: Option<Address>,
/// Payment details for the invoice.
pub payment_details: PaymentDetails,
/// Merchant specific Unique identifier.
pub merchant_reference_id: Option<String>,
}
impl CreateAndConfirmSubscriptionRequest {
pub fn get_billing_address(&self) -> Option<Address> {
self.payment_details
.payment_method_data
.as_ref()
.and_then(|data| data.billing.clone())
.or(self.billing.clone())
}
pub fn validate(&self) -> Result<(), error_stack::Report<ValidationError>> {
self.payment_details.validate()
}
}
impl ApiEventMetric for CreateAndConfirmSubscriptionRequest {}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct ConfirmSubscriptionResponse {
/// Unique identifier for the subscription.
pub id: SubscriptionId,
/// Merchant specific Unique identifier.
pub merchant_reference_id: Option<String>,
/// Current status of the subscription.
pub status: SubscriptionStatus,
/// Identifier for the associated subscription plan.
pub plan_id: Option<String>,
/// Identifier for the associated item_price_id for the subscription.
pub item_price_id: Option<String>,
/// Optional coupon code applied to this subscription.
pub coupon: Option<String>,
/// Associated profile ID.
pub profile_id: ProfileId,
/// Payment details for the invoice.
pub payment: Option<PaymentResponseData>,
/// Customer ID associated with this subscription.
pub customer_id: Option<CustomerId>,
/// Invoice Details for the subscription.
pub invoice: Option<Invoice>,
/// Billing Processor subscription ID.
pub billing_processor_subscription_id: Option<String>,
}
impl ConfirmSubscriptionResponse {
pub fn get_optional_invoice_id(&self) -> Option<InvoiceId> {
self.invoice.as_ref().map(|invoice| invoice.id.to_owned())
}
pub fn get_optional_payment_id(&self) -> Option<PaymentId> {
self.payment
.as_ref()
.map(|payment| payment.payment_id.to_owned())
}
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct Invoice {
/// Unique identifier for the invoice.
pub id: InvoiceId,
/// Unique identifier for the subscription.
pub subscription_id: SubscriptionId,
/// Identifier for the merchant.
pub merchant_id: MerchantId,
/// Identifier for the profile.
pub profile_id: ProfileId,
/// Identifier for the merchant connector account.
pub merchant_connector_id: MerchantConnectorAccountId,
/// Identifier for the Payment.
pub payment_intent_id: Option<PaymentId>,
/// Identifier for Payment Method
#[schema(value_type = Option<String>, example = "pm_01926c58bc6e77c09e809964e72af8c8")]
pub payment_method_id: Option<String>,
/// Identifier for the Customer.
pub customer_id: CustomerId,
/// Invoice amount.
pub amount: MinorUnit,
/// Currency for the invoice payment.
pub currency: Currency,
/// Status of the invoice.
pub status: InvoiceStatus,
/// billing processor invoice id
pub billing_processor_invoice_id: Option<String>,
}
impl ApiEventMetric for ConfirmSubscriptionResponse {}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct UpdateSubscriptionRequest {
/// Identifier for the associated plan_id.
pub plan_id: String,
/// Identifier for the associated item_price_id for the subscription.
pub item_price_id: String,
}
impl ApiEventMetric for UpdateSubscriptionRequest {}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct EstimateSubscriptionQuery {
/// Identifier for the associated subscription plan.
pub plan_id: Option<String>,
/// Identifier for the associated item_price_id for the subscription.
pub item_price_id: String,
/// Identifier for the coupon code for the subscription.
pub coupon_code: Option<String>,
}
impl ApiEventMetric for EstimateSubscriptionQuery {}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ListSubscriptionQuery {
/// Number of records to return.
pub limit: Option<i64>,
/// Offset for pagination.
pub offset: Option<i64>,
}
impl ApiEventMetric for ListSubscriptionQuery {}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct EstimateSubscriptionResponse {
/// Estimated amount to be charged for the invoice.
pub amount: MinorUnit,
/// Currency for the amount.
pub currency: Currency,
/// Identifier for the associated plan_id.
pub plan_id: Option<String>,
/// Identifier for the associated item_price_id for the subscription.
pub item_price_id: Option<String>,
/// Identifier for the coupon code for the subscription.
pub coupon_code: Option<String>,
/// Identifier for customer.
pub customer_id: Option<CustomerId>,
pub line_items: Vec<SubscriptionLineItem>,
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct SubscriptionLineItem {
/// Unique identifier for the line item.
pub item_id: String,
/// Type of the line item.
pub item_type: String,
/// Description of the line item.
pub description: String,
/// Amount for the line item.
pub amount: MinorUnit,
/// Currency for the line item
pub currency: Currency,
/// Quantity of the line item.
pub quantity: i64,
}
impl ApiEventMetric for EstimateSubscriptionResponse {}
/// Request payload for pausing a subscription.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct PauseSubscriptionRequest {
/// List of options to pause the subscription.
pub pause_option: Option<PauseOption>,
/// Optional date when the subscription should be paused (if not provided, pauses immediately)
#[schema(value_type = Option<String>)]
pub pause_at: Option<time::PrimitiveDateTime>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum PauseOption {
/// Pause immediately
Immediately,
/// Pause at the end of current term
EndOfTerm,
/// Pause on a specific date,
SpecificDate,
}
/// Response payload returned after successfully pausing a subscription.
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct PauseSubscriptionResponse {
/// Unique identifier for the subscription.
pub id: SubscriptionId,
/// Current status of the subscription.
pub status: SubscriptionStatus,
/// Merchant specific Unique identifier.
pub merchant_reference_id: Option<String>,
/// Associated profile ID.
pub profile_id: ProfileId,
/// Merchant identifier owning this subscription.
pub merchant_id: MerchantId,
/// Customer ID associated with this subscription.
pub customer_id: CustomerId,
/// Date when the subscription was paused
#[schema(value_type = Option<String>)]
pub paused_at: Option<time::PrimitiveDateTime>,
}
/// Request payload for resuming a subscription.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ResumeSubscriptionRequest {
/// Options to resume the subscription.
pub resume_option: Option<ResumeOption>,
/// Optional date when the subscription should be resumed (if not provided, resumes immediately)
#[schema(value_type = Option<String>)]
pub resume_date: Option<time::PrimitiveDateTime>,
/// Applicable when charges get added during this operation and resume_option is set as 'immediately'. Allows to raise invoice immediately or add them to unbilled charges.
pub charges_handling: Option<ChargesHandling>,
/// Applicable when the subscription has past due invoices and resume_option is set as 'immediately'. Allows to collect past due invoices or retain them as unpaid. If 'schedule_payment_collection' option is chosen in this field, remaining refundable credits and excess payments are applied
pub unpaid_invoices_handling: Option<UnpaidInvoicesHandling>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ResumeOption {
/// Resume immediately
Immediately,
/// Resume on a specific date,
SpecificDate,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ChargesHandling {
InvoiceImmediately,
AddToUnbilledCharges,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum UnpaidInvoicesHandling {
NoAction,
SchedulePaymentCollection,
}
/// Response payload returned after successfully resuming a subscription.
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct ResumeSubscriptionResponse {
/// Unique identifier for the subscription.
pub id: SubscriptionId,
/// Current status of the subscription.
pub status: SubscriptionStatus,
/// Merchant specific Unique identifier.
pub merchant_reference_id: Option<String>,
/// Associated profile ID.
pub profile_id: ProfileId,
/// Merchant identifier owning this subscription.
pub merchant_id: MerchantId,
/// Customer ID associated with this subscription.
pub customer_id: CustomerId,
/// Date when the subscription was resumed
#[schema(value_type = Option<String>)]
pub next_billing_at: Option<time::PrimitiveDateTime>,
}
/// Request payload for cancelling a subscription.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct CancelSubscriptionRequest {
/// Optional reason for cancelling the subscription
pub cancel_option: Option<CancelOption>,
/// Optional date when the subscription should be cancelled (if not provided, cancels immediately)
#[schema(value_type = Option<String>)]
pub cancel_at: Option<time::PrimitiveDateTime>,
/// Specifies how to handle unbilled charges when canceling immediately
pub unbilled_charges_option: Option<UnbilledChargesOption>,
/// Specifies how to handle credits for current term charges when canceling immediately
pub credit_option_for_current_term_charges: Option<CreditOption>,
/// Specifies how to handle past due invoices when canceling immediately
pub account_receivables_handling: Option<AccountReceivablesHandling>,
/// Specifies how to handle refundable credits when canceling immediately
pub refundable_credits_handling: Option<RefundableCreditsHandling>,
/// Reason code for canceling the subscription
pub cancel_reason_code: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum CancelOption {
Immediately,
EndOfTerm,
SpecificDate,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum RefundableCreditsHandling {
NoAction,
ScheduleRefund,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum AccountReceivablesHandling {
NoAction,
SchedulePaymentCollection,
WriteOff,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum CreditOption {
None,
Prorate,
Full,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum UnbilledChargesOption {
Invoice,
Delete,
}
/// Response payload returned after successfully cancelling a subscription.
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct CancelSubscriptionResponse {
/// Unique identifier for the subscription.
pub id: SubscriptionId,
/// Current status of the subscription.
pub status: SubscriptionStatus,
/// Merchant specific Unique identifier.
pub merchant_reference_id: Option<String>,
/// Associated profile ID.
pub profile_id: ProfileId,
/// Merchant identifier owning this subscription.
pub merchant_id: MerchantId,
/// Customer ID associated with this subscription.
pub customer_id: CustomerId,
/// Date when the subscription was cancelled
#[schema(value_type = Option<String>)]
pub cancelled_at: Option<time::PrimitiveDateTime>,
}
impl ApiEventMetric for PauseSubscriptionRequest {}
impl ApiEventMetric for PauseSubscriptionResponse {}
impl ApiEventMetric for ResumeSubscriptionRequest {}
impl ApiEventMetric for ResumeSubscriptionResponse {}
impl ApiEventMetric for CancelSubscriptionRequest {}
impl ApiEventMetric for CancelSubscriptionResponse {}
|
crates__api_models__src__user.rs
|
use std::fmt::Debug;
use common_enums::{EntityType, TokenPurpose};
use common_utils::{crypto::OptionalEncryptableName, id_type, pii};
use masking::Secret;
use utoipa::ToSchema;
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 organization_type: Option<common_enums::OrganizationType>,
}
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 ValidateOnlyQueryParam {
pub status_check: Option<bool>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub enum InvitationAcceptanceStatus {
AlreadyAccepted,
SuccessfullyAccepted,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum AcceptInviteResponse {
Token(TokenResponse),
Status(InvitationAcceptanceStatus),
}
#[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(Debug, serde::Deserialize, serde::Serialize)]
pub struct CloneConnectorSource {
pub mca_id: id_type::MerchantConnectorAccountId,
pub merchant_id: id_type::MerchantId,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct CloneConnectorDestination {
pub connector_label: Option<String>,
pub profile_id: id_type::ProfileId,
pub merchant_id: id_type::MerchantId,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct CloneConnectorRequest {
pub source: CloneConnectorSource,
pub destination: CloneConnectorDestination,
}
#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct CreateInternalUserRequest {
pub name: Secret<String>,
pub email: pii::Email,
pub password: Secret<String>,
pub role_id: 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, Clone, ToSchema)]
pub struct PlatformAccountCreateRequest {
#[schema(max_length = 64, value_type = String, example = "organization_abc")]
pub organization_name: Secret<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct PlatformAccountCreateResponse {
#[schema(value_type = String, max_length = 64, min_length = 1, example = "org_abc")]
pub org_id: id_type::OrganizationId,
#[schema(value_type = Option<String>, example = "organization_abc")]
pub org_name: Option<String>,
#[schema(value_type = OrganizationType, example = "standard")]
pub org_type: common_enums::OrganizationType,
#[schema(value_type = String, example = "merchant_abc")]
pub merchant_id: id_type::MerchantId,
#[schema(value_type = MerchantAccountType, example = "standard")]
pub merchant_account_type: common_enums::MerchantAccountType,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UserMerchantCreate {
pub company_name: String,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: Option<common_enums::MerchantAccountRequestType>,
}
#[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, Clone)]
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)]
pub struct CreateUserAuthenticationMethodResponse {
pub id: String,
pub auth_id: String,
pub owner_id: String,
pub owner_type: common_enums::Owner,
pub auth_type: common_enums::UserAuthType,
pub email_domain: Option<String>,
pub allow_signup: bool,
}
#[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>,
pub org_type: common_enums::OrganizationType,
}
#[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 merchant_account_type: common_enums::MerchantAccountType,
pub version: common_enums::ApiVersion,
}
#[derive(Debug, serde::Serialize)]
pub struct ListProfilesForUserInOrgAndMerchantAccountResponse {
pub profile_id: id_type::ProfileId,
pub profile_name: String,
}
#[derive(Debug, serde::Serialize)]
pub struct IssueEmbeddedTokenResponse {
pub token: Secret<String>,
}
#[derive(Debug, serde::Serialize)]
pub struct EmbeddedTokenInfoResponse {
pub org_id: id_type::OrganizationId,
pub merchant_id: id_type::MerchantId,
pub merchant_account_version: common_enums::ApiVersion,
pub profile_id: id_type::ProfileId,
}
|
crates__common_enums__src__transformers.rs
|
use std::fmt::{Display, Formatter};
use serde::{Deserialize, Serialize};
#[cfg(feature = "payouts")]
use crate::enums::PayoutStatus;
use crate::enums::{
AttemptStatus, Country, CountryAlpha2, CountryAlpha3, DisputeStatus, EventType, IntentStatus,
MandateStatus, PaymentMethod, PaymentMethodType, RefundStatus, SubscriptionStatus,
};
impl Display for NumericCountryCodeParseError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "Invalid Country Code")
}
}
impl CountryAlpha2 {
pub const fn from_alpha2_to_alpha3(code: Self) -> CountryAlpha3 {
match code {
Self::AF => CountryAlpha3::AFG,
Self::AX => CountryAlpha3::ALA,
Self::AL => CountryAlpha3::ALB,
Self::DZ => CountryAlpha3::DZA,
Self::AS => CountryAlpha3::ASM,
Self::AD => CountryAlpha3::AND,
Self::AO => CountryAlpha3::AGO,
Self::AI => CountryAlpha3::AIA,
Self::AQ => CountryAlpha3::ATA,
Self::AG => CountryAlpha3::ATG,
Self::AR => CountryAlpha3::ARG,
Self::AM => CountryAlpha3::ARM,
Self::AW => CountryAlpha3::ABW,
Self::AU => CountryAlpha3::AUS,
Self::AT => CountryAlpha3::AUT,
Self::AZ => CountryAlpha3::AZE,
Self::BS => CountryAlpha3::BHS,
Self::BH => CountryAlpha3::BHR,
Self::BD => CountryAlpha3::BGD,
Self::BB => CountryAlpha3::BRB,
Self::BY => CountryAlpha3::BLR,
Self::BE => CountryAlpha3::BEL,
Self::BZ => CountryAlpha3::BLZ,
Self::BJ => CountryAlpha3::BEN,
Self::BM => CountryAlpha3::BMU,
Self::BT => CountryAlpha3::BTN,
Self::BO => CountryAlpha3::BOL,
Self::BQ => CountryAlpha3::BES,
Self::BA => CountryAlpha3::BIH,
Self::BW => CountryAlpha3::BWA,
Self::BV => CountryAlpha3::BVT,
Self::BR => CountryAlpha3::BRA,
Self::IO => CountryAlpha3::IOT,
Self::BN => CountryAlpha3::BRN,
Self::BG => CountryAlpha3::BGR,
Self::BF => CountryAlpha3::BFA,
Self::BI => CountryAlpha3::BDI,
Self::CV => CountryAlpha3::CPV,
Self::KH => CountryAlpha3::KHM,
Self::CM => CountryAlpha3::CMR,
Self::CA => CountryAlpha3::CAN,
Self::KY => CountryAlpha3::CYM,
Self::CF => CountryAlpha3::CAF,
Self::TD => CountryAlpha3::TCD,
Self::CL => CountryAlpha3::CHL,
Self::CN => CountryAlpha3::CHN,
Self::CX => CountryAlpha3::CXR,
Self::CC => CountryAlpha3::CCK,
Self::CO => CountryAlpha3::COL,
Self::KM => CountryAlpha3::COM,
Self::CG => CountryAlpha3::COG,
Self::CD => CountryAlpha3::COD,
Self::CK => CountryAlpha3::COK,
Self::CR => CountryAlpha3::CRI,
Self::CI => CountryAlpha3::CIV,
Self::HR => CountryAlpha3::HRV,
Self::CU => CountryAlpha3::CUB,
Self::CW => CountryAlpha3::CUW,
Self::CY => CountryAlpha3::CYP,
Self::CZ => CountryAlpha3::CZE,
Self::DK => CountryAlpha3::DNK,
Self::DJ => CountryAlpha3::DJI,
Self::DM => CountryAlpha3::DMA,
Self::DO => CountryAlpha3::DOM,
Self::EC => CountryAlpha3::ECU,
Self::EG => CountryAlpha3::EGY,
Self::SV => CountryAlpha3::SLV,
Self::GQ => CountryAlpha3::GNQ,
Self::ER => CountryAlpha3::ERI,
Self::EE => CountryAlpha3::EST,
Self::ET => CountryAlpha3::ETH,
Self::FK => CountryAlpha3::FLK,
Self::FO => CountryAlpha3::FRO,
Self::FJ => CountryAlpha3::FJI,
Self::FI => CountryAlpha3::FIN,
Self::FR => CountryAlpha3::FRA,
Self::GF => CountryAlpha3::GUF,
Self::PF => CountryAlpha3::PYF,
Self::TF => CountryAlpha3::ATF,
Self::GA => CountryAlpha3::GAB,
Self::GM => CountryAlpha3::GMB,
Self::GE => CountryAlpha3::GEO,
Self::DE => CountryAlpha3::DEU,
Self::GH => CountryAlpha3::GHA,
Self::GI => CountryAlpha3::GIB,
Self::GR => CountryAlpha3::GRC,
Self::GL => CountryAlpha3::GRL,
Self::GD => CountryAlpha3::GRD,
Self::GP => CountryAlpha3::GLP,
Self::GU => CountryAlpha3::GUM,
Self::GT => CountryAlpha3::GTM,
Self::GG => CountryAlpha3::GGY,
Self::GN => CountryAlpha3::GIN,
Self::GW => CountryAlpha3::GNB,
Self::GY => CountryAlpha3::GUY,
Self::HT => CountryAlpha3::HTI,
Self::HM => CountryAlpha3::HMD,
Self::VA => CountryAlpha3::VAT,
Self::HN => CountryAlpha3::HND,
Self::HK => CountryAlpha3::HKG,
Self::HU => CountryAlpha3::HUN,
Self::IS => CountryAlpha3::ISL,
Self::IN => CountryAlpha3::IND,
Self::ID => CountryAlpha3::IDN,
Self::IR => CountryAlpha3::IRN,
Self::IQ => CountryAlpha3::IRQ,
Self::IE => CountryAlpha3::IRL,
Self::IM => CountryAlpha3::IMN,
Self::IL => CountryAlpha3::ISR,
Self::IT => CountryAlpha3::ITA,
Self::JM => CountryAlpha3::JAM,
Self::JP => CountryAlpha3::JPN,
Self::JE => CountryAlpha3::JEY,
Self::JO => CountryAlpha3::JOR,
Self::KZ => CountryAlpha3::KAZ,
Self::KE => CountryAlpha3::KEN,
Self::KI => CountryAlpha3::KIR,
Self::KP => CountryAlpha3::PRK,
Self::KR => CountryAlpha3::KOR,
Self::KW => CountryAlpha3::KWT,
Self::KG => CountryAlpha3::KGZ,
Self::LA => CountryAlpha3::LAO,
Self::LV => CountryAlpha3::LVA,
Self::LB => CountryAlpha3::LBN,
Self::LS => CountryAlpha3::LSO,
Self::LR => CountryAlpha3::LBR,
Self::LY => CountryAlpha3::LBY,
Self::LI => CountryAlpha3::LIE,
Self::LT => CountryAlpha3::LTU,
Self::LU => CountryAlpha3::LUX,
Self::MO => CountryAlpha3::MAC,
Self::MK => CountryAlpha3::MKD,
Self::MG => CountryAlpha3::MDG,
Self::MW => CountryAlpha3::MWI,
Self::MY => CountryAlpha3::MYS,
Self::MV => CountryAlpha3::MDV,
Self::ML => CountryAlpha3::MLI,
Self::MT => CountryAlpha3::MLT,
Self::MH => CountryAlpha3::MHL,
Self::MQ => CountryAlpha3::MTQ,
Self::MR => CountryAlpha3::MRT,
Self::MU => CountryAlpha3::MUS,
Self::YT => CountryAlpha3::MYT,
Self::MX => CountryAlpha3::MEX,
Self::FM => CountryAlpha3::FSM,
Self::MD => CountryAlpha3::MDA,
Self::MC => CountryAlpha3::MCO,
Self::MN => CountryAlpha3::MNG,
Self::ME => CountryAlpha3::MNE,
Self::MS => CountryAlpha3::MSR,
Self::MA => CountryAlpha3::MAR,
Self::MZ => CountryAlpha3::MOZ,
Self::MM => CountryAlpha3::MMR,
Self::NA => CountryAlpha3::NAM,
Self::NR => CountryAlpha3::NRU,
Self::NP => CountryAlpha3::NPL,
Self::NL => CountryAlpha3::NLD,
Self::NC => CountryAlpha3::NCL,
Self::NZ => CountryAlpha3::NZL,
Self::NI => CountryAlpha3::NIC,
Self::NE => CountryAlpha3::NER,
Self::NG => CountryAlpha3::NGA,
Self::NU => CountryAlpha3::NIU,
Self::NF => CountryAlpha3::NFK,
Self::MP => CountryAlpha3::MNP,
Self::NO => CountryAlpha3::NOR,
Self::OM => CountryAlpha3::OMN,
Self::PK => CountryAlpha3::PAK,
Self::PW => CountryAlpha3::PLW,
Self::PS => CountryAlpha3::PSE,
Self::PA => CountryAlpha3::PAN,
Self::PG => CountryAlpha3::PNG,
Self::PY => CountryAlpha3::PRY,
Self::PE => CountryAlpha3::PER,
Self::PH => CountryAlpha3::PHL,
Self::PN => CountryAlpha3::PCN,
Self::PL => CountryAlpha3::POL,
Self::PT => CountryAlpha3::PRT,
Self::PR => CountryAlpha3::PRI,
Self::QA => CountryAlpha3::QAT,
Self::RE => CountryAlpha3::REU,
Self::RO => CountryAlpha3::ROU,
Self::RU => CountryAlpha3::RUS,
Self::RW => CountryAlpha3::RWA,
Self::BL => CountryAlpha3::BLM,
Self::SH => CountryAlpha3::SHN,
Self::KN => CountryAlpha3::KNA,
Self::LC => CountryAlpha3::LCA,
Self::MF => CountryAlpha3::MAF,
Self::PM => CountryAlpha3::SPM,
Self::VC => CountryAlpha3::VCT,
Self::WS => CountryAlpha3::WSM,
Self::SM => CountryAlpha3::SMR,
Self::ST => CountryAlpha3::STP,
Self::SA => CountryAlpha3::SAU,
Self::SN => CountryAlpha3::SEN,
Self::RS => CountryAlpha3::SRB,
Self::SC => CountryAlpha3::SYC,
Self::SL => CountryAlpha3::SLE,
Self::SG => CountryAlpha3::SGP,
Self::SX => CountryAlpha3::SXM,
Self::SK => CountryAlpha3::SVK,
Self::SI => CountryAlpha3::SVN,
Self::SB => CountryAlpha3::SLB,
Self::SO => CountryAlpha3::SOM,
Self::ZA => CountryAlpha3::ZAF,
Self::GS => CountryAlpha3::SGS,
Self::SS => CountryAlpha3::SSD,
Self::ES => CountryAlpha3::ESP,
Self::LK => CountryAlpha3::LKA,
Self::SD => CountryAlpha3::SDN,
Self::SR => CountryAlpha3::SUR,
Self::SJ => CountryAlpha3::SJM,
Self::SZ => CountryAlpha3::SWZ,
Self::SE => CountryAlpha3::SWE,
Self::CH => CountryAlpha3::CHE,
Self::SY => CountryAlpha3::SYR,
Self::TW => CountryAlpha3::TWN,
Self::TJ => CountryAlpha3::TJK,
Self::TZ => CountryAlpha3::TZA,
Self::TH => CountryAlpha3::THA,
Self::TL => CountryAlpha3::TLS,
Self::TG => CountryAlpha3::TGO,
Self::TK => CountryAlpha3::TKL,
Self::TO => CountryAlpha3::TON,
Self::TT => CountryAlpha3::TTO,
Self::TN => CountryAlpha3::TUN,
Self::TR => CountryAlpha3::TUR,
Self::TM => CountryAlpha3::TKM,
Self::TC => CountryAlpha3::TCA,
Self::TV => CountryAlpha3::TUV,
Self::UG => CountryAlpha3::UGA,
Self::UA => CountryAlpha3::UKR,
Self::AE => CountryAlpha3::ARE,
Self::GB => CountryAlpha3::GBR,
Self::US => CountryAlpha3::USA,
Self::UM => CountryAlpha3::UMI,
Self::UY => CountryAlpha3::URY,
Self::UZ => CountryAlpha3::UZB,
Self::VU => CountryAlpha3::VUT,
Self::VE => CountryAlpha3::VEN,
Self::VN => CountryAlpha3::VNM,
Self::VG => CountryAlpha3::VGB,
Self::VI => CountryAlpha3::VIR,
Self::WF => CountryAlpha3::WLF,
Self::EH => CountryAlpha3::ESH,
Self::YE => CountryAlpha3::YEM,
Self::ZM => CountryAlpha3::ZMB,
Self::ZW => CountryAlpha3::ZWE,
}
}
}
impl Country {
pub const fn from_alpha2(code: CountryAlpha2) -> Self {
match code {
CountryAlpha2::AF => Self::Afghanistan,
CountryAlpha2::AX => Self::AlandIslands,
CountryAlpha2::AL => Self::Albania,
CountryAlpha2::DZ => Self::Algeria,
CountryAlpha2::AS => Self::AmericanSamoa,
CountryAlpha2::AD => Self::Andorra,
CountryAlpha2::AO => Self::Angola,
CountryAlpha2::AI => Self::Anguilla,
CountryAlpha2::AQ => Self::Antarctica,
CountryAlpha2::AG => Self::AntiguaAndBarbuda,
CountryAlpha2::AR => Self::Argentina,
CountryAlpha2::AM => Self::Armenia,
CountryAlpha2::AW => Self::Aruba,
CountryAlpha2::AU => Self::Australia,
CountryAlpha2::AT => Self::Austria,
CountryAlpha2::AZ => Self::Azerbaijan,
CountryAlpha2::BS => Self::Bahamas,
CountryAlpha2::BH => Self::Bahrain,
CountryAlpha2::BD => Self::Bangladesh,
CountryAlpha2::BB => Self::Barbados,
CountryAlpha2::BY => Self::Belarus,
CountryAlpha2::BE => Self::Belgium,
CountryAlpha2::BZ => Self::Belize,
CountryAlpha2::BJ => Self::Benin,
CountryAlpha2::BM => Self::Bermuda,
CountryAlpha2::BT => Self::Bhutan,
CountryAlpha2::BO => Self::BoliviaPlurinationalState,
CountryAlpha2::BQ => Self::BonaireSintEustatiusAndSaba,
CountryAlpha2::BA => Self::BosniaAndHerzegovina,
CountryAlpha2::BW => Self::Botswana,
CountryAlpha2::BV => Self::BouvetIsland,
CountryAlpha2::BR => Self::Brazil,
CountryAlpha2::IO => Self::BritishIndianOceanTerritory,
CountryAlpha2::BN => Self::BruneiDarussalam,
CountryAlpha2::BG => Self::Bulgaria,
CountryAlpha2::BF => Self::BurkinaFaso,
CountryAlpha2::BI => Self::Burundi,
CountryAlpha2::CV => Self::CaboVerde,
CountryAlpha2::KH => Self::Cambodia,
CountryAlpha2::CM => Self::Cameroon,
CountryAlpha2::CA => Self::Canada,
CountryAlpha2::KY => Self::CaymanIslands,
CountryAlpha2::CF => Self::CentralAfricanRepublic,
CountryAlpha2::TD => Self::Chad,
CountryAlpha2::CL => Self::Chile,
CountryAlpha2::CN => Self::China,
CountryAlpha2::CX => Self::ChristmasIsland,
CountryAlpha2::CC => Self::CocosKeelingIslands,
CountryAlpha2::CO => Self::Colombia,
CountryAlpha2::KM => Self::Comoros,
CountryAlpha2::CG => Self::Congo,
CountryAlpha2::CD => Self::CongoDemocraticRepublic,
CountryAlpha2::CK => Self::CookIslands,
CountryAlpha2::CR => Self::CostaRica,
CountryAlpha2::CI => Self::CotedIvoire,
CountryAlpha2::HR => Self::Croatia,
CountryAlpha2::CU => Self::Cuba,
CountryAlpha2::CW => Self::Curacao,
CountryAlpha2::CY => Self::Cyprus,
CountryAlpha2::CZ => Self::Czechia,
CountryAlpha2::DK => Self::Denmark,
CountryAlpha2::DJ => Self::Djibouti,
CountryAlpha2::DM => Self::Dominica,
CountryAlpha2::DO => Self::DominicanRepublic,
CountryAlpha2::EC => Self::Ecuador,
CountryAlpha2::EG => Self::Egypt,
CountryAlpha2::SV => Self::ElSalvador,
CountryAlpha2::GQ => Self::EquatorialGuinea,
CountryAlpha2::ER => Self::Eritrea,
CountryAlpha2::EE => Self::Estonia,
CountryAlpha2::ET => Self::Ethiopia,
CountryAlpha2::FK => Self::FalklandIslandsMalvinas,
CountryAlpha2::FO => Self::FaroeIslands,
CountryAlpha2::FJ => Self::Fiji,
CountryAlpha2::FI => Self::Finland,
CountryAlpha2::FR => Self::France,
CountryAlpha2::GF => Self::FrenchGuiana,
CountryAlpha2::PF => Self::FrenchPolynesia,
CountryAlpha2::TF => Self::FrenchSouthernTerritories,
CountryAlpha2::GA => Self::Gabon,
CountryAlpha2::GM => Self::Gambia,
CountryAlpha2::GE => Self::Georgia,
CountryAlpha2::DE => Self::Germany,
CountryAlpha2::GH => Self::Ghana,
CountryAlpha2::GI => Self::Gibraltar,
CountryAlpha2::GR => Self::Greece,
CountryAlpha2::GL => Self::Greenland,
CountryAlpha2::GD => Self::Grenada,
CountryAlpha2::GP => Self::Guadeloupe,
CountryAlpha2::GU => Self::Guam,
CountryAlpha2::GT => Self::Guatemala,
CountryAlpha2::GG => Self::Guernsey,
CountryAlpha2::GN => Self::Guinea,
CountryAlpha2::GW => Self::GuineaBissau,
CountryAlpha2::GY => Self::Guyana,
CountryAlpha2::HT => Self::Haiti,
CountryAlpha2::HM => Self::HeardIslandAndMcDonaldIslands,
CountryAlpha2::VA => Self::HolySee,
CountryAlpha2::HN => Self::Honduras,
CountryAlpha2::HK => Self::HongKong,
CountryAlpha2::HU => Self::Hungary,
CountryAlpha2::IS => Self::Iceland,
CountryAlpha2::IN => Self::India,
CountryAlpha2::ID => Self::Indonesia,
CountryAlpha2::IR => Self::IranIslamicRepublic,
CountryAlpha2::IQ => Self::Iraq,
CountryAlpha2::IE => Self::Ireland,
CountryAlpha2::IM => Self::IsleOfMan,
CountryAlpha2::IL => Self::Israel,
CountryAlpha2::IT => Self::Italy,
CountryAlpha2::JM => Self::Jamaica,
CountryAlpha2::JP => Self::Japan,
CountryAlpha2::JE => Self::Jersey,
CountryAlpha2::JO => Self::Jordan,
CountryAlpha2::KZ => Self::Kazakhstan,
CountryAlpha2::KE => Self::Kenya,
CountryAlpha2::KI => Self::Kiribati,
CountryAlpha2::KP => Self::KoreaDemocraticPeoplesRepublic,
CountryAlpha2::KR => Self::KoreaRepublic,
CountryAlpha2::KW => Self::Kuwait,
CountryAlpha2::KG => Self::Kyrgyzstan,
CountryAlpha2::LA => Self::LaoPeoplesDemocraticRepublic,
CountryAlpha2::LV => Self::Latvia,
CountryAlpha2::LB => Self::Lebanon,
CountryAlpha2::LS => Self::Lesotho,
CountryAlpha2::LR => Self::Liberia,
CountryAlpha2::LY => Self::Libya,
CountryAlpha2::LI => Self::Liechtenstein,
CountryAlpha2::LT => Self::Lithuania,
CountryAlpha2::LU => Self::Luxembourg,
CountryAlpha2::MO => Self::Macao,
CountryAlpha2::MK => Self::MacedoniaTheFormerYugoslavRepublic,
CountryAlpha2::MG => Self::Madagascar,
CountryAlpha2::MW => Self::Malawi,
CountryAlpha2::MY => Self::Malaysia,
CountryAlpha2::MV => Self::Maldives,
CountryAlpha2::ML => Self::Mali,
CountryAlpha2::MT => Self::Malta,
CountryAlpha2::MH => Self::MarshallIslands,
CountryAlpha2::MQ => Self::Martinique,
CountryAlpha2::MR => Self::Mauritania,
CountryAlpha2::MU => Self::Mauritius,
CountryAlpha2::YT => Self::Mayotte,
CountryAlpha2::MX => Self::Mexico,
CountryAlpha2::FM => Self::MicronesiaFederatedStates,
CountryAlpha2::MD => Self::MoldovaRepublic,
CountryAlpha2::MC => Self::Monaco,
CountryAlpha2::MN => Self::Mongolia,
CountryAlpha2::ME => Self::Montenegro,
CountryAlpha2::MS => Self::Montserrat,
CountryAlpha2::MA => Self::Morocco,
CountryAlpha2::MZ => Self::Mozambique,
CountryAlpha2::MM => Self::Myanmar,
CountryAlpha2::NA => Self::Namibia,
CountryAlpha2::NR => Self::Nauru,
CountryAlpha2::NP => Self::Nepal,
CountryAlpha2::NL => Self::Netherlands,
CountryAlpha2::NC => Self::NewCaledonia,
CountryAlpha2::NZ => Self::NewZealand,
CountryAlpha2::NI => Self::Nicaragua,
CountryAlpha2::NE => Self::Niger,
CountryAlpha2::NG => Self::Nigeria,
CountryAlpha2::NU => Self::Niue,
CountryAlpha2::NF => Self::NorfolkIsland,
CountryAlpha2::MP => Self::NorthernMarianaIslands,
CountryAlpha2::NO => Self::Norway,
CountryAlpha2::OM => Self::Oman,
CountryAlpha2::PK => Self::Pakistan,
CountryAlpha2::PW => Self::Palau,
CountryAlpha2::PS => Self::PalestineState,
CountryAlpha2::PA => Self::Panama,
CountryAlpha2::PG => Self::PapuaNewGuinea,
CountryAlpha2::PY => Self::Paraguay,
CountryAlpha2::PE => Self::Peru,
CountryAlpha2::PH => Self::Philippines,
CountryAlpha2::PN => Self::Pitcairn,
CountryAlpha2::PL => Self::Poland,
CountryAlpha2::PT => Self::Portugal,
CountryAlpha2::PR => Self::PuertoRico,
CountryAlpha2::QA => Self::Qatar,
CountryAlpha2::RE => Self::Reunion,
CountryAlpha2::RO => Self::Romania,
CountryAlpha2::RU => Self::RussianFederation,
CountryAlpha2::RW => Self::Rwanda,
CountryAlpha2::BL => Self::SaintBarthelemy,
CountryAlpha2::SH => Self::SaintHelenaAscensionAndTristandaCunha,
CountryAlpha2::KN => Self::SaintKittsAndNevis,
CountryAlpha2::LC => Self::SaintLucia,
CountryAlpha2::MF => Self::SaintMartinFrenchpart,
CountryAlpha2::PM => Self::SaintPierreAndMiquelon,
CountryAlpha2::VC => Self::SaintVincentAndTheGrenadines,
CountryAlpha2::WS => Self::Samoa,
CountryAlpha2::SM => Self::SanMarino,
CountryAlpha2::ST => Self::SaoTomeAndPrincipe,
CountryAlpha2::SA => Self::SaudiArabia,
CountryAlpha2::SN => Self::Senegal,
CountryAlpha2::RS => Self::Serbia,
CountryAlpha2::SC => Self::Seychelles,
CountryAlpha2::SL => Self::SierraLeone,
CountryAlpha2::SG => Self::Singapore,
CountryAlpha2::SX => Self::SintMaartenDutchpart,
CountryAlpha2::SK => Self::Slovakia,
CountryAlpha2::SI => Self::Slovenia,
CountryAlpha2::SB => Self::SolomonIslands,
CountryAlpha2::SO => Self::Somalia,
CountryAlpha2::ZA => Self::SouthAfrica,
CountryAlpha2::GS => Self::SouthGeorgiaAndTheSouthSandwichIslands,
CountryAlpha2::SS => Self::SouthSudan,
CountryAlpha2::ES => Self::Spain,
CountryAlpha2::LK => Self::SriLanka,
CountryAlpha2::SD => Self::Sudan,
CountryAlpha2::SR => Self::Suriname,
CountryAlpha2::SJ => Self::SvalbardAndJanMayen,
CountryAlpha2::SZ => Self::Swaziland,
CountryAlpha2::SE => Self::Sweden,
CountryAlpha2::CH => Self::Switzerland,
CountryAlpha2::SY => Self::SyrianArabRepublic,
CountryAlpha2::TW => Self::TaiwanProvinceOfChina,
CountryAlpha2::TJ => Self::Tajikistan,
CountryAlpha2::TZ => Self::TanzaniaUnitedRepublic,
CountryAlpha2::TH => Self::Thailand,
CountryAlpha2::TL => Self::TimorLeste,
CountryAlpha2::TG => Self::Togo,
CountryAlpha2::TK => Self::Tokelau,
CountryAlpha2::TO => Self::Tonga,
CountryAlpha2::TT => Self::TrinidadAndTobago,
CountryAlpha2::TN => Self::Tunisia,
CountryAlpha2::TR => Self::Turkey,
CountryAlpha2::TM => Self::Turkmenistan,
CountryAlpha2::TC => Self::TurksAndCaicosIslands,
CountryAlpha2::TV => Self::Tuvalu,
CountryAlpha2::UG => Self::Uganda,
CountryAlpha2::UA => Self::Ukraine,
CountryAlpha2::AE => Self::UnitedArabEmirates,
CountryAlpha2::GB => Self::UnitedKingdomOfGreatBritainAndNorthernIreland,
CountryAlpha2::US => Self::UnitedStatesOfAmerica,
CountryAlpha2::UM => Self::UnitedStatesMinorOutlyingIslands,
CountryAlpha2::UY => Self::Uruguay,
CountryAlpha2::UZ => Self::Uzbekistan,
CountryAlpha2::VU => Self::Vanuatu,
CountryAlpha2::VE => Self::VenezuelaBolivarianRepublic,
CountryAlpha2::VN => Self::Vietnam,
CountryAlpha2::VG => Self::VirginIslandsBritish,
CountryAlpha2::VI => Self::VirginIslandsUS,
CountryAlpha2::WF => Self::WallisAndFutuna,
CountryAlpha2::EH => Self::WesternSahara,
CountryAlpha2::YE => Self::Yemen,
CountryAlpha2::ZM => Self::Zambia,
CountryAlpha2::ZW => Self::Zimbabwe,
}
}
pub const fn to_alpha2(self) -> CountryAlpha2 {
match self {
Self::Afghanistan => CountryAlpha2::AF,
Self::AlandIslands => CountryAlpha2::AX,
Self::Albania => CountryAlpha2::AL,
Self::Algeria => CountryAlpha2::DZ,
Self::AmericanSamoa => CountryAlpha2::AS,
Self::Andorra => CountryAlpha2::AD,
Self::Angola => CountryAlpha2::AO,
Self::Anguilla => CountryAlpha2::AI,
Self::Antarctica => CountryAlpha2::AQ,
Self::AntiguaAndBarbuda => CountryAlpha2::AG,
Self::Argentina => CountryAlpha2::AR,
Self::Armenia => CountryAlpha2::AM,
Self::Aruba => CountryAlpha2::AW,
Self::Australia => CountryAlpha2::AU,
Self::Austria => CountryAlpha2::AT,
Self::Azerbaijan => CountryAlpha2::AZ,
Self::Bahamas => CountryAlpha2::BS,
Self::Bahrain => CountryAlpha2::BH,
Self::Bangladesh => CountryAlpha2::BD,
Self::Barbados => CountryAlpha2::BB,
Self::Belarus => CountryAlpha2::BY,
Self::Belgium => CountryAlpha2::BE,
Self::Belize => CountryAlpha2::BZ,
Self::Benin => CountryAlpha2::BJ,
Self::Bermuda => CountryAlpha2::BM,
Self::Bhutan => CountryAlpha2::BT,
Self::BoliviaPlurinationalState => CountryAlpha2::BO,
Self::BonaireSintEustatiusAndSaba => CountryAlpha2::BQ,
Self::BosniaAndHerzegovina => CountryAlpha2::BA,
Self::Botswana => CountryAlpha2::BW,
Self::BouvetIsland => CountryAlpha2::BV,
Self::Brazil => CountryAlpha2::BR,
Self::BritishIndianOceanTerritory => CountryAlpha2::IO,
Self::BruneiDarussalam => CountryAlpha2::BN,
Self::Bulgaria => CountryAlpha2::BG,
Self::BurkinaFaso => CountryAlpha2::BF,
Self::Burundi => CountryAlpha2::BI,
Self::CaboVerde => CountryAlpha2::CV,
Self::Cambodia => CountryAlpha2::KH,
Self::Cameroon => CountryAlpha2::CM,
Self::Canada => CountryAlpha2::CA,
Self::CaymanIslands => CountryAlpha2::KY,
Self::CentralAfricanRepublic => CountryAlpha2::CF,
Self::Chad => CountryAlpha2::TD,
Self::Chile => CountryAlpha2::CL,
Self::China => CountryAlpha2::CN,
Self::ChristmasIsland => CountryAlpha2::CX,
Self::CocosKeelingIslands => CountryAlpha2::CC,
Self::Colombia => CountryAlpha2::CO,
Self::Comoros => CountryAlpha2::KM,
Self::Congo => CountryAlpha2::CG,
Self::CongoDemocraticRepublic => CountryAlpha2::CD,
Self::CookIslands => CountryAlpha2::CK,
Self::CostaRica => CountryAlpha2::CR,
Self::CotedIvoire => CountryAlpha2::CI,
Self::Croatia => CountryAlpha2::HR,
Self::Cuba => CountryAlpha2::CU,
Self::Curacao => CountryAlpha2::CW,
Self::Cyprus => CountryAlpha2::CY,
Self::Czechia => CountryAlpha2::CZ,
Self::Denmark => CountryAlpha2::DK,
Self::Djibouti => CountryAlpha2::DJ,
Self::Dominica => CountryAlpha2::DM,
Self::DominicanRepublic => CountryAlpha2::DO,
Self::Ecuador => CountryAlpha2::EC,
Self::Egypt => CountryAlpha2::EG,
Self::ElSalvador => CountryAlpha2::SV,
Self::EquatorialGuinea => CountryAlpha2::GQ,
Self::Eritrea => CountryAlpha2::ER,
Self::Estonia => CountryAlpha2::EE,
Self::Ethiopia => CountryAlpha2::ET,
Self::FalklandIslandsMalvinas => CountryAlpha2::FK,
Self::FaroeIslands => CountryAlpha2::FO,
Self::Fiji => CountryAlpha2::FJ,
Self::Finland => CountryAlpha2::FI,
Self::France => CountryAlpha2::FR,
Self::FrenchGuiana => CountryAlpha2::GF,
Self::FrenchPolynesia => CountryAlpha2::PF,
Self::FrenchSouthernTerritories => CountryAlpha2::TF,
Self::Gabon => CountryAlpha2::GA,
Self::Gambia => CountryAlpha2::GM,
Self::Georgia => CountryAlpha2::GE,
Self::Germany => CountryAlpha2::DE,
Self::Ghana => CountryAlpha2::GH,
Self::Gibraltar => CountryAlpha2::GI,
Self::Greece => CountryAlpha2::GR,
Self::Greenland => CountryAlpha2::GL,
Self::Grenada => CountryAlpha2::GD,
Self::Guadeloupe => CountryAlpha2::GP,
Self::Guam => CountryAlpha2::GU,
Self::Guatemala => CountryAlpha2::GT,
Self::Guernsey => CountryAlpha2::GG,
Self::Guinea => CountryAlpha2::GN,
Self::GuineaBissau => CountryAlpha2::GW,
Self::Guyana => CountryAlpha2::GY,
Self::Haiti => CountryAlpha2::HT,
Self::HeardIslandAndMcDonaldIslands => CountryAlpha2::HM,
Self::HolySee => CountryAlpha2::VA,
Self::Honduras => CountryAlpha2::HN,
Self::HongKong => CountryAlpha2::HK,
Self::Hungary => CountryAlpha2::HU,
Self::Iceland => CountryAlpha2::IS,
Self::India => CountryAlpha2::IN,
Self::Indonesia => CountryAlpha2::ID,
Self::IranIslamicRepublic => CountryAlpha2::IR,
Self::Iraq => CountryAlpha2::IQ,
Self::Ireland => CountryAlpha2::IE,
Self::IsleOfMan => CountryAlpha2::IM,
Self::Israel => CountryAlpha2::IL,
Self::Italy => CountryAlpha2::IT,
Self::Jamaica => CountryAlpha2::JM,
Self::Japan => CountryAlpha2::JP,
Self::Jersey => CountryAlpha2::JE,
Self::Jordan => CountryAlpha2::JO,
Self::Kazakhstan => CountryAlpha2::KZ,
Self::Kenya => CountryAlpha2::KE,
Self::Kiribati => CountryAlpha2::KI,
Self::KoreaDemocraticPeoplesRepublic => CountryAlpha2::KP,
Self::KoreaRepublic => CountryAlpha2::KR,
Self::Kuwait => CountryAlpha2::KW,
Self::Kyrgyzstan => CountryAlpha2::KG,
Self::LaoPeoplesDemocraticRepublic => CountryAlpha2::LA,
Self::Latvia => CountryAlpha2::LV,
Self::Lebanon => CountryAlpha2::LB,
Self::Lesotho => CountryAlpha2::LS,
Self::Liberia => CountryAlpha2::LR,
Self::Libya => CountryAlpha2::LY,
Self::Liechtenstein => CountryAlpha2::LI,
Self::Lithuania => CountryAlpha2::LT,
Self::Luxembourg => CountryAlpha2::LU,
Self::Macao => CountryAlpha2::MO,
Self::MacedoniaTheFormerYugoslavRepublic => CountryAlpha2::MK,
Self::Madagascar => CountryAlpha2::MG,
Self::Malawi => CountryAlpha2::MW,
Self::Malaysia => CountryAlpha2::MY,
Self::Maldives => CountryAlpha2::MV,
Self::Mali => CountryAlpha2::ML,
Self::Malta => CountryAlpha2::MT,
Self::MarshallIslands => CountryAlpha2::MH,
Self::Martinique => CountryAlpha2::MQ,
Self::Mauritania => CountryAlpha2::MR,
Self::Mauritius => CountryAlpha2::MU,
Self::Mayotte => CountryAlpha2::YT,
Self::Mexico => CountryAlpha2::MX,
Self::MicronesiaFederatedStates => CountryAlpha2::FM,
Self::MoldovaRepublic => CountryAlpha2::MD,
Self::Monaco => CountryAlpha2::MC,
Self::Mongolia => CountryAlpha2::MN,
Self::Montenegro => CountryAlpha2::ME,
Self::Montserrat => CountryAlpha2::MS,
Self::Morocco => CountryAlpha2::MA,
Self::Mozambique => CountryAlpha2::MZ,
Self::Myanmar => CountryAlpha2::MM,
Self::Namibia => CountryAlpha2::NA,
Self::Nauru => CountryAlpha2::NR,
Self::Nepal => CountryAlpha2::NP,
Self::Netherlands => CountryAlpha2::NL,
Self::NewCaledonia => CountryAlpha2::NC,
Self::NewZealand => CountryAlpha2::NZ,
Self::Nicaragua => CountryAlpha2::NI,
Self::Niger => CountryAlpha2::NE,
Self::Nigeria => CountryAlpha2::NG,
Self::Niue => CountryAlpha2::NU,
Self::NorfolkIsland => CountryAlpha2::NF,
Self::NorthernMarianaIslands => CountryAlpha2::MP,
Self::Norway => CountryAlpha2::NO,
Self::Oman => CountryAlpha2::OM,
Self::Pakistan => CountryAlpha2::PK,
Self::Palau => CountryAlpha2::PW,
Self::PalestineState => CountryAlpha2::PS,
Self::Panama => CountryAlpha2::PA,
Self::PapuaNewGuinea => CountryAlpha2::PG,
Self::Paraguay => CountryAlpha2::PY,
Self::Peru => CountryAlpha2::PE,
Self::Philippines => CountryAlpha2::PH,
Self::Pitcairn => CountryAlpha2::PN,
Self::Poland => CountryAlpha2::PL,
Self::Portugal => CountryAlpha2::PT,
Self::PuertoRico => CountryAlpha2::PR,
Self::Qatar => CountryAlpha2::QA,
Self::Reunion => CountryAlpha2::RE,
Self::Romania => CountryAlpha2::RO,
Self::RussianFederation => CountryAlpha2::RU,
Self::Rwanda => CountryAlpha2::RW,
Self::SaintBarthelemy => CountryAlpha2::BL,
Self::SaintHelenaAscensionAndTristandaCunha => CountryAlpha2::SH,
Self::SaintKittsAndNevis => CountryAlpha2::KN,
Self::SaintLucia => CountryAlpha2::LC,
Self::SaintMartinFrenchpart => CountryAlpha2::MF,
Self::SaintPierreAndMiquelon => CountryAlpha2::PM,
Self::SaintVincentAndTheGrenadines => CountryAlpha2::VC,
Self::Samoa => CountryAlpha2::WS,
Self::SanMarino => CountryAlpha2::SM,
Self::SaoTomeAndPrincipe => CountryAlpha2::ST,
Self::SaudiArabia => CountryAlpha2::SA,
Self::Senegal => CountryAlpha2::SN,
Self::Serbia => CountryAlpha2::RS,
Self::Seychelles => CountryAlpha2::SC,
Self::SierraLeone => CountryAlpha2::SL,
Self::Singapore => CountryAlpha2::SG,
Self::SintMaartenDutchpart => CountryAlpha2::SX,
Self::Slovakia => CountryAlpha2::SK,
Self::Slovenia => CountryAlpha2::SI,
Self::SolomonIslands => CountryAlpha2::SB,
Self::Somalia => CountryAlpha2::SO,
Self::SouthAfrica => CountryAlpha2::ZA,
Self::SouthGeorgiaAndTheSouthSandwichIslands => CountryAlpha2::GS,
Self::SouthSudan => CountryAlpha2::SS,
Self::Spain => CountryAlpha2::ES,
Self::SriLanka => CountryAlpha2::LK,
Self::Sudan => CountryAlpha2::SD,
Self::Suriname => CountryAlpha2::SR,
Self::SvalbardAndJanMayen => CountryAlpha2::SJ,
Self::Swaziland => CountryAlpha2::SZ,
Self::Sweden => CountryAlpha2::SE,
Self::Switzerland => CountryAlpha2::CH,
Self::SyrianArabRepublic => CountryAlpha2::SY,
Self::TaiwanProvinceOfChina => CountryAlpha2::TW,
Self::Tajikistan => CountryAlpha2::TJ,
Self::TanzaniaUnitedRepublic => CountryAlpha2::TZ,
Self::Thailand => CountryAlpha2::TH,
Self::TimorLeste => CountryAlpha2::TL,
Self::Togo => CountryAlpha2::TG,
Self::Tokelau => CountryAlpha2::TK,
Self::Tonga => CountryAlpha2::TO,
Self::TrinidadAndTobago => CountryAlpha2::TT,
Self::Tunisia => CountryAlpha2::TN,
Self::Turkey => CountryAlpha2::TR,
Self::Turkmenistan => CountryAlpha2::TM,
Self::TurksAndCaicosIslands => CountryAlpha2::TC,
Self::Tuvalu => CountryAlpha2::TV,
Self::Uganda => CountryAlpha2::UG,
Self::Ukraine => CountryAlpha2::UA,
Self::UnitedArabEmirates => CountryAlpha2::AE,
Self::UnitedKingdomOfGreatBritainAndNorthernIreland => CountryAlpha2::GB,
Self::UnitedStatesOfAmerica => CountryAlpha2::US,
Self::UnitedStatesMinorOutlyingIslands => CountryAlpha2::UM,
Self::Uruguay => CountryAlpha2::UY,
Self::Uzbekistan => CountryAlpha2::UZ,
Self::Vanuatu => CountryAlpha2::VU,
Self::VenezuelaBolivarianRepublic => CountryAlpha2::VE,
Self::Vietnam => CountryAlpha2::VN,
Self::VirginIslandsBritish => CountryAlpha2::VG,
Self::VirginIslandsUS => CountryAlpha2::VI,
Self::WallisAndFutuna => CountryAlpha2::WF,
Self::WesternSahara => CountryAlpha2::EH,
Self::Yemen => CountryAlpha2::YE,
Self::Zambia => CountryAlpha2::ZM,
Self::Zimbabwe => CountryAlpha2::ZW,
}
}
pub const fn from_alpha3(code: CountryAlpha3) -> Self {
match code {
CountryAlpha3::AFG => Self::Afghanistan,
CountryAlpha3::ALA => Self::AlandIslands,
CountryAlpha3::ALB => Self::Albania,
CountryAlpha3::DZA => Self::Algeria,
CountryAlpha3::ASM => Self::AmericanSamoa,
CountryAlpha3::AND => Self::Andorra,
CountryAlpha3::AGO => Self::Angola,
CountryAlpha3::AIA => Self::Anguilla,
CountryAlpha3::ATA => Self::Antarctica,
CountryAlpha3::ATG => Self::AntiguaAndBarbuda,
CountryAlpha3::ARG => Self::Argentina,
CountryAlpha3::ARM => Self::Armenia,
CountryAlpha3::ABW => Self::Aruba,
CountryAlpha3::AUS => Self::Australia,
CountryAlpha3::AUT => Self::Austria,
CountryAlpha3::AZE => Self::Azerbaijan,
CountryAlpha3::BHS => Self::Bahamas,
CountryAlpha3::BHR => Self::Bahrain,
CountryAlpha3::BGD => Self::Bangladesh,
CountryAlpha3::BRB => Self::Barbados,
CountryAlpha3::BLR => Self::Belarus,
CountryAlpha3::BEL => Self::Belgium,
CountryAlpha3::BLZ => Self::Belize,
CountryAlpha3::BEN => Self::Benin,
CountryAlpha3::BMU => Self::Bermuda,
CountryAlpha3::BTN => Self::Bhutan,
CountryAlpha3::BOL => Self::BoliviaPlurinationalState,
CountryAlpha3::BES => Self::BonaireSintEustatiusAndSaba,
CountryAlpha3::BIH => Self::BosniaAndHerzegovina,
CountryAlpha3::BWA => Self::Botswana,
CountryAlpha3::BVT => Self::BouvetIsland,
CountryAlpha3::BRA => Self::Brazil,
CountryAlpha3::IOT => Self::BritishIndianOceanTerritory,
CountryAlpha3::BRN => Self::BruneiDarussalam,
CountryAlpha3::BGR => Self::Bulgaria,
CountryAlpha3::BFA => Self::BurkinaFaso,
CountryAlpha3::BDI => Self::Burundi,
CountryAlpha3::CPV => Self::CaboVerde,
CountryAlpha3::KHM => Self::Cambodia,
CountryAlpha3::CMR => Self::Cameroon,
CountryAlpha3::CAN => Self::Canada,
CountryAlpha3::CYM => Self::CaymanIslands,
CountryAlpha3::CAF => Self::CentralAfricanRepublic,
CountryAlpha3::TCD => Self::Chad,
CountryAlpha3::CHL => Self::Chile,
CountryAlpha3::CHN => Self::China,
CountryAlpha3::CXR => Self::ChristmasIsland,
CountryAlpha3::CCK => Self::CocosKeelingIslands,
CountryAlpha3::COL => Self::Colombia,
CountryAlpha3::COM => Self::Comoros,
CountryAlpha3::COG => Self::Congo,
CountryAlpha3::COD => Self::CongoDemocraticRepublic,
CountryAlpha3::COK => Self::CookIslands,
CountryAlpha3::CRI => Self::CostaRica,
CountryAlpha3::CIV => Self::CotedIvoire,
CountryAlpha3::HRV => Self::Croatia,
CountryAlpha3::CUB => Self::Cuba,
CountryAlpha3::CUW => Self::Curacao,
CountryAlpha3::CYP => Self::Cyprus,
CountryAlpha3::CZE => Self::Czechia,
CountryAlpha3::DNK => Self::Denmark,
CountryAlpha3::DJI => Self::Djibouti,
CountryAlpha3::DMA => Self::Dominica,
CountryAlpha3::DOM => Self::DominicanRepublic,
CountryAlpha3::ECU => Self::Ecuador,
CountryAlpha3::EGY => Self::Egypt,
CountryAlpha3::SLV => Self::ElSalvador,
CountryAlpha3::GNQ => Self::EquatorialGuinea,
CountryAlpha3::ERI => Self::Eritrea,
CountryAlpha3::EST => Self::Estonia,
CountryAlpha3::ETH => Self::Ethiopia,
CountryAlpha3::FLK => Self::FalklandIslandsMalvinas,
CountryAlpha3::FRO => Self::FaroeIslands,
CountryAlpha3::FJI => Self::Fiji,
CountryAlpha3::FIN => Self::Finland,
CountryAlpha3::FRA => Self::France,
CountryAlpha3::GUF => Self::FrenchGuiana,
CountryAlpha3::PYF => Self::FrenchPolynesia,
CountryAlpha3::ATF => Self::FrenchSouthernTerritories,
CountryAlpha3::GAB => Self::Gabon,
CountryAlpha3::GMB => Self::Gambia,
CountryAlpha3::GEO => Self::Georgia,
CountryAlpha3::DEU => Self::Germany,
CountryAlpha3::GHA => Self::Ghana,
CountryAlpha3::GIB => Self::Gibraltar,
CountryAlpha3::GRC => Self::Greece,
CountryAlpha3::GRL => Self::Greenland,
CountryAlpha3::GRD => Self::Grenada,
CountryAlpha3::GLP => Self::Guadeloupe,
CountryAlpha3::GUM => Self::Guam,
CountryAlpha3::GTM => Self::Guatemala,
CountryAlpha3::GGY => Self::Guernsey,
CountryAlpha3::GIN => Self::Guinea,
CountryAlpha3::GNB => Self::GuineaBissau,
CountryAlpha3::GUY => Self::Guyana,
CountryAlpha3::HTI => Self::Haiti,
CountryAlpha3::HMD => Self::HeardIslandAndMcDonaldIslands,
CountryAlpha3::VAT => Self::HolySee,
CountryAlpha3::HND => Self::Honduras,
CountryAlpha3::HKG => Self::HongKong,
CountryAlpha3::HUN => Self::Hungary,
CountryAlpha3::ISL => Self::Iceland,
CountryAlpha3::IND => Self::India,
CountryAlpha3::IDN => Self::Indonesia,
CountryAlpha3::IRN => Self::IranIslamicRepublic,
CountryAlpha3::IRQ => Self::Iraq,
CountryAlpha3::IRL => Self::Ireland,
CountryAlpha3::IMN => Self::IsleOfMan,
CountryAlpha3::ISR => Self::Israel,
CountryAlpha3::ITA => Self::Italy,
CountryAlpha3::JAM => Self::Jamaica,
CountryAlpha3::JPN => Self::Japan,
CountryAlpha3::JEY => Self::Jersey,
CountryAlpha3::JOR => Self::Jordan,
CountryAlpha3::KAZ => Self::Kazakhstan,
CountryAlpha3::KEN => Self::Kenya,
CountryAlpha3::KIR => Self::Kiribati,
CountryAlpha3::PRK => Self::KoreaDemocraticPeoplesRepublic,
CountryAlpha3::KOR => Self::KoreaRepublic,
CountryAlpha3::KWT => Self::Kuwait,
CountryAlpha3::KGZ => Self::Kyrgyzstan,
CountryAlpha3::LAO => Self::LaoPeoplesDemocraticRepublic,
CountryAlpha3::LVA => Self::Latvia,
CountryAlpha3::LBN => Self::Lebanon,
CountryAlpha3::LSO => Self::Lesotho,
CountryAlpha3::LBR => Self::Liberia,
CountryAlpha3::LBY => Self::Libya,
CountryAlpha3::LIE => Self::Liechtenstein,
CountryAlpha3::LTU => Self::Lithuania,
CountryAlpha3::LUX => Self::Luxembourg,
CountryAlpha3::MAC => Self::Macao,
CountryAlpha3::MKD => Self::MacedoniaTheFormerYugoslavRepublic,
CountryAlpha3::MDG => Self::Madagascar,
CountryAlpha3::MWI => Self::Malawi,
CountryAlpha3::MYS => Self::Malaysia,
CountryAlpha3::MDV => Self::Maldives,
CountryAlpha3::MLI => Self::Mali,
CountryAlpha3::MLT => Self::Malta,
CountryAlpha3::MHL => Self::MarshallIslands,
CountryAlpha3::MTQ => Self::Martinique,
CountryAlpha3::MRT => Self::Mauritania,
CountryAlpha3::MUS => Self::Mauritius,
CountryAlpha3::MYT => Self::Mayotte,
CountryAlpha3::MEX => Self::Mexico,
CountryAlpha3::FSM => Self::MicronesiaFederatedStates,
CountryAlpha3::MDA => Self::MoldovaRepublic,
CountryAlpha3::MCO => Self::Monaco,
CountryAlpha3::MNG => Self::Mongolia,
CountryAlpha3::MNE => Self::Montenegro,
CountryAlpha3::MSR => Self::Montserrat,
CountryAlpha3::MAR => Self::Morocco,
CountryAlpha3::MOZ => Self::Mozambique,
CountryAlpha3::MMR => Self::Myanmar,
CountryAlpha3::NAM => Self::Namibia,
CountryAlpha3::NRU => Self::Nauru,
CountryAlpha3::NPL => Self::Nepal,
CountryAlpha3::NLD => Self::Netherlands,
CountryAlpha3::NCL => Self::NewCaledonia,
CountryAlpha3::NZL => Self::NewZealand,
CountryAlpha3::NIC => Self::Nicaragua,
CountryAlpha3::NER => Self::Niger,
CountryAlpha3::NGA => Self::Nigeria,
CountryAlpha3::NIU => Self::Niue,
CountryAlpha3::NFK => Self::NorfolkIsland,
CountryAlpha3::MNP => Self::NorthernMarianaIslands,
CountryAlpha3::NOR => Self::Norway,
CountryAlpha3::OMN => Self::Oman,
CountryAlpha3::PAK => Self::Pakistan,
CountryAlpha3::PLW => Self::Palau,
CountryAlpha3::PSE => Self::PalestineState,
CountryAlpha3::PAN => Self::Panama,
CountryAlpha3::PNG => Self::PapuaNewGuinea,
CountryAlpha3::PRY => Self::Paraguay,
CountryAlpha3::PER => Self::Peru,
CountryAlpha3::PHL => Self::Philippines,
CountryAlpha3::PCN => Self::Pitcairn,
CountryAlpha3::POL => Self::Poland,
CountryAlpha3::PRT => Self::Portugal,
CountryAlpha3::PRI => Self::PuertoRico,
CountryAlpha3::QAT => Self::Qatar,
CountryAlpha3::REU => Self::Reunion,
CountryAlpha3::ROU => Self::Romania,
CountryAlpha3::RUS => Self::RussianFederation,
CountryAlpha3::RWA => Self::Rwanda,
CountryAlpha3::BLM => Self::SaintBarthelemy,
CountryAlpha3::SHN => Self::SaintHelenaAscensionAndTristandaCunha,
CountryAlpha3::KNA => Self::SaintKittsAndNevis,
CountryAlpha3::LCA => Self::SaintLucia,
CountryAlpha3::MAF => Self::SaintMartinFrenchpart,
CountryAlpha3::SPM => Self::SaintPierreAndMiquelon,
CountryAlpha3::VCT => Self::SaintVincentAndTheGrenadines,
CountryAlpha3::WSM => Self::Samoa,
CountryAlpha3::SMR => Self::SanMarino,
CountryAlpha3::STP => Self::SaoTomeAndPrincipe,
CountryAlpha3::SAU => Self::SaudiArabia,
CountryAlpha3::SEN => Self::Senegal,
CountryAlpha3::SRB => Self::Serbia,
CountryAlpha3::SYC => Self::Seychelles,
CountryAlpha3::SLE => Self::SierraLeone,
CountryAlpha3::SGP => Self::Singapore,
CountryAlpha3::SXM => Self::SintMaartenDutchpart,
CountryAlpha3::SVK => Self::Slovakia,
CountryAlpha3::SVN => Self::Slovenia,
CountryAlpha3::SLB => Self::SolomonIslands,
CountryAlpha3::SOM => Self::Somalia,
CountryAlpha3::ZAF => Self::SouthAfrica,
CountryAlpha3::SGS => Self::SouthGeorgiaAndTheSouthSandwichIslands,
CountryAlpha3::SSD => Self::SouthSudan,
CountryAlpha3::ESP => Self::Spain,
CountryAlpha3::LKA => Self::SriLanka,
CountryAlpha3::SDN => Self::Sudan,
CountryAlpha3::SUR => Self::Suriname,
CountryAlpha3::SJM => Self::SvalbardAndJanMayen,
CountryAlpha3::SWZ => Self::Swaziland,
CountryAlpha3::SWE => Self::Sweden,
CountryAlpha3::CHE => Self::Switzerland,
CountryAlpha3::SYR => Self::SyrianArabRepublic,
CountryAlpha3::TWN => Self::TaiwanProvinceOfChina,
CountryAlpha3::TJK => Self::Tajikistan,
CountryAlpha3::TZA => Self::TanzaniaUnitedRepublic,
CountryAlpha3::THA => Self::Thailand,
CountryAlpha3::TLS => Self::TimorLeste,
CountryAlpha3::TGO => Self::Togo,
CountryAlpha3::TKL => Self::Tokelau,
CountryAlpha3::TON => Self::Tonga,
CountryAlpha3::TTO => Self::TrinidadAndTobago,
CountryAlpha3::TUN => Self::Tunisia,
CountryAlpha3::TUR => Self::Turkey,
CountryAlpha3::TKM => Self::Turkmenistan,
CountryAlpha3::TCA => Self::TurksAndCaicosIslands,
CountryAlpha3::TUV => Self::Tuvalu,
CountryAlpha3::UGA => Self::Uganda,
CountryAlpha3::UKR => Self::Ukraine,
CountryAlpha3::ARE => Self::UnitedArabEmirates,
CountryAlpha3::GBR => Self::UnitedKingdomOfGreatBritainAndNorthernIreland,
CountryAlpha3::USA => Self::UnitedStatesOfAmerica,
CountryAlpha3::UMI => Self::UnitedStatesMinorOutlyingIslands,
CountryAlpha3::URY => Self::Uruguay,
CountryAlpha3::UZB => Self::Uzbekistan,
CountryAlpha3::VUT => Self::Vanuatu,
CountryAlpha3::VEN => Self::VenezuelaBolivarianRepublic,
CountryAlpha3::VNM => Self::Vietnam,
CountryAlpha3::VGB => Self::VirginIslandsBritish,
CountryAlpha3::VIR => Self::VirginIslandsUS,
CountryAlpha3::WLF => Self::WallisAndFutuna,
CountryAlpha3::ESH => Self::WesternSahara,
CountryAlpha3::YEM => Self::Yemen,
CountryAlpha3::ZMB => Self::Zambia,
CountryAlpha3::ZWE => Self::Zimbabwe,
}
}
pub const fn to_alpha3(self) -> CountryAlpha3 {
match self {
Self::Afghanistan => CountryAlpha3::AFG,
Self::AlandIslands => CountryAlpha3::ALA,
Self::Albania => CountryAlpha3::ALB,
Self::Algeria => CountryAlpha3::DZA,
Self::AmericanSamoa => CountryAlpha3::ASM,
Self::Andorra => CountryAlpha3::AND,
Self::Angola => CountryAlpha3::AGO,
Self::Anguilla => CountryAlpha3::AIA,
Self::Antarctica => CountryAlpha3::ATA,
Self::AntiguaAndBarbuda => CountryAlpha3::ATG,
Self::Argentina => CountryAlpha3::ARG,
Self::Armenia => CountryAlpha3::ARM,
Self::Aruba => CountryAlpha3::ABW,
Self::Australia => CountryAlpha3::AUS,
Self::Austria => CountryAlpha3::AUT,
Self::Azerbaijan => CountryAlpha3::AZE,
Self::Bahamas => CountryAlpha3::BHS,
Self::Bahrain => CountryAlpha3::BHR,
Self::Bangladesh => CountryAlpha3::BGD,
Self::Barbados => CountryAlpha3::BRB,
Self::Belarus => CountryAlpha3::BLR,
Self::Belgium => CountryAlpha3::BEL,
Self::Belize => CountryAlpha3::BLZ,
Self::Benin => CountryAlpha3::BEN,
Self::Bermuda => CountryAlpha3::BMU,
Self::Bhutan => CountryAlpha3::BTN,
Self::BoliviaPlurinationalState => CountryAlpha3::BOL,
Self::BonaireSintEustatiusAndSaba => CountryAlpha3::BES,
Self::BosniaAndHerzegovina => CountryAlpha3::BIH,
Self::Botswana => CountryAlpha3::BWA,
Self::BouvetIsland => CountryAlpha3::BVT,
Self::Brazil => CountryAlpha3::BRA,
Self::BritishIndianOceanTerritory => CountryAlpha3::IOT,
Self::BruneiDarussalam => CountryAlpha3::BRN,
Self::Bulgaria => CountryAlpha3::BGR,
Self::BurkinaFaso => CountryAlpha3::BFA,
Self::Burundi => CountryAlpha3::BDI,
Self::CaboVerde => CountryAlpha3::CPV,
Self::Cambodia => CountryAlpha3::KHM,
Self::Cameroon => CountryAlpha3::CMR,
Self::Canada => CountryAlpha3::CAN,
Self::CaymanIslands => CountryAlpha3::CYM,
Self::CentralAfricanRepublic => CountryAlpha3::CAF,
Self::Chad => CountryAlpha3::TCD,
Self::Chile => CountryAlpha3::CHL,
Self::China => CountryAlpha3::CHN,
Self::ChristmasIsland => CountryAlpha3::CXR,
Self::CocosKeelingIslands => CountryAlpha3::CCK,
Self::Colombia => CountryAlpha3::COL,
Self::Comoros => CountryAlpha3::COM,
Self::Congo => CountryAlpha3::COG,
Self::CongoDemocraticRepublic => CountryAlpha3::COD,
Self::CookIslands => CountryAlpha3::COK,
Self::CostaRica => CountryAlpha3::CRI,
Self::CotedIvoire => CountryAlpha3::CIV,
Self::Croatia => CountryAlpha3::HRV,
Self::Cuba => CountryAlpha3::CUB,
Self::Curacao => CountryAlpha3::CUW,
Self::Cyprus => CountryAlpha3::CYP,
Self::Czechia => CountryAlpha3::CZE,
Self::Denmark => CountryAlpha3::DNK,
Self::Djibouti => CountryAlpha3::DJI,
Self::Dominica => CountryAlpha3::DMA,
Self::DominicanRepublic => CountryAlpha3::DOM,
Self::Ecuador => CountryAlpha3::ECU,
Self::Egypt => CountryAlpha3::EGY,
Self::ElSalvador => CountryAlpha3::SLV,
Self::EquatorialGuinea => CountryAlpha3::GNQ,
Self::Eritrea => CountryAlpha3::ERI,
Self::Estonia => CountryAlpha3::EST,
Self::Ethiopia => CountryAlpha3::ETH,
Self::FalklandIslandsMalvinas => CountryAlpha3::FLK,
Self::FaroeIslands => CountryAlpha3::FRO,
Self::Fiji => CountryAlpha3::FJI,
Self::Finland => CountryAlpha3::FIN,
Self::France => CountryAlpha3::FRA,
Self::FrenchGuiana => CountryAlpha3::GUF,
Self::FrenchPolynesia => CountryAlpha3::PYF,
Self::FrenchSouthernTerritories => CountryAlpha3::ATF,
Self::Gabon => CountryAlpha3::GAB,
Self::Gambia => CountryAlpha3::GMB,
Self::Georgia => CountryAlpha3::GEO,
Self::Germany => CountryAlpha3::DEU,
Self::Ghana => CountryAlpha3::GHA,
Self::Gibraltar => CountryAlpha3::GIB,
Self::Greece => CountryAlpha3::GRC,
Self::Greenland => CountryAlpha3::GRL,
Self::Grenada => CountryAlpha3::GRD,
Self::Guadeloupe => CountryAlpha3::GLP,
Self::Guam => CountryAlpha3::GUM,
Self::Guatemala => CountryAlpha3::GTM,
Self::Guernsey => CountryAlpha3::GGY,
Self::Guinea => CountryAlpha3::GIN,
Self::GuineaBissau => CountryAlpha3::GNB,
Self::Guyana => CountryAlpha3::GUY,
Self::Haiti => CountryAlpha3::HTI,
Self::HeardIslandAndMcDonaldIslands => CountryAlpha3::HMD,
Self::HolySee => CountryAlpha3::VAT,
Self::Honduras => CountryAlpha3::HND,
Self::HongKong => CountryAlpha3::HKG,
Self::Hungary => CountryAlpha3::HUN,
Self::Iceland => CountryAlpha3::ISL,
Self::India => CountryAlpha3::IND,
Self::Indonesia => CountryAlpha3::IDN,
Self::IranIslamicRepublic => CountryAlpha3::IRN,
Self::Iraq => CountryAlpha3::IRQ,
Self::Ireland => CountryAlpha3::IRL,
Self::IsleOfMan => CountryAlpha3::IMN,
Self::Israel => CountryAlpha3::ISR,
Self::Italy => CountryAlpha3::ITA,
Self::Jamaica => CountryAlpha3::JAM,
Self::Japan => CountryAlpha3::JPN,
Self::Jersey => CountryAlpha3::JEY,
Self::Jordan => CountryAlpha3::JOR,
Self::Kazakhstan => CountryAlpha3::KAZ,
Self::Kenya => CountryAlpha3::KEN,
Self::Kiribati => CountryAlpha3::KIR,
Self::KoreaDemocraticPeoplesRepublic => CountryAlpha3::PRK,
Self::KoreaRepublic => CountryAlpha3::KOR,
Self::Kuwait => CountryAlpha3::KWT,
Self::Kyrgyzstan => CountryAlpha3::KGZ,
Self::LaoPeoplesDemocraticRepublic => CountryAlpha3::LAO,
Self::Latvia => CountryAlpha3::LVA,
Self::Lebanon => CountryAlpha3::LBN,
Self::Lesotho => CountryAlpha3::LSO,
Self::Liberia => CountryAlpha3::LBR,
Self::Libya => CountryAlpha3::LBY,
Self::Liechtenstein => CountryAlpha3::LIE,
Self::Lithuania => CountryAlpha3::LTU,
Self::Luxembourg => CountryAlpha3::LUX,
Self::Macao => CountryAlpha3::MAC,
Self::MacedoniaTheFormerYugoslavRepublic => CountryAlpha3::MKD,
Self::Madagascar => CountryAlpha3::MDG,
Self::Malawi => CountryAlpha3::MWI,
Self::Malaysia => CountryAlpha3::MYS,
Self::Maldives => CountryAlpha3::MDV,
Self::Mali => CountryAlpha3::MLI,
Self::Malta => CountryAlpha3::MLT,
Self::MarshallIslands => CountryAlpha3::MHL,
Self::Martinique => CountryAlpha3::MTQ,
Self::Mauritania => CountryAlpha3::MRT,
Self::Mauritius => CountryAlpha3::MUS,
Self::Mayotte => CountryAlpha3::MYT,
Self::Mexico => CountryAlpha3::MEX,
Self::MicronesiaFederatedStates => CountryAlpha3::FSM,
Self::MoldovaRepublic => CountryAlpha3::MDA,
Self::Monaco => CountryAlpha3::MCO,
Self::Mongolia => CountryAlpha3::MNG,
Self::Montenegro => CountryAlpha3::MNE,
Self::Montserrat => CountryAlpha3::MSR,
Self::Morocco => CountryAlpha3::MAR,
Self::Mozambique => CountryAlpha3::MOZ,
Self::Myanmar => CountryAlpha3::MMR,
Self::Namibia => CountryAlpha3::NAM,
Self::Nauru => CountryAlpha3::NRU,
Self::Nepal => CountryAlpha3::NPL,
Self::Netherlands => CountryAlpha3::NLD,
Self::NewCaledonia => CountryAlpha3::NCL,
Self::NewZealand => CountryAlpha3::NZL,
Self::Nicaragua => CountryAlpha3::NIC,
Self::Niger => CountryAlpha3::NER,
Self::Nigeria => CountryAlpha3::NGA,
Self::Niue => CountryAlpha3::NIU,
Self::NorfolkIsland => CountryAlpha3::NFK,
Self::NorthernMarianaIslands => CountryAlpha3::MNP,
Self::Norway => CountryAlpha3::NOR,
Self::Oman => CountryAlpha3::OMN,
Self::Pakistan => CountryAlpha3::PAK,
Self::Palau => CountryAlpha3::PLW,
Self::PalestineState => CountryAlpha3::PSE,
Self::Panama => CountryAlpha3::PAN,
Self::PapuaNewGuinea => CountryAlpha3::PNG,
Self::Paraguay => CountryAlpha3::PRY,
Self::Peru => CountryAlpha3::PER,
Self::Philippines => CountryAlpha3::PHL,
Self::Pitcairn => CountryAlpha3::PCN,
Self::Poland => CountryAlpha3::POL,
Self::Portugal => CountryAlpha3::PRT,
Self::PuertoRico => CountryAlpha3::PRI,
Self::Qatar => CountryAlpha3::QAT,
Self::Reunion => CountryAlpha3::REU,
Self::Romania => CountryAlpha3::ROU,
Self::RussianFederation => CountryAlpha3::RUS,
Self::Rwanda => CountryAlpha3::RWA,
Self::SaintBarthelemy => CountryAlpha3::BLM,
Self::SaintHelenaAscensionAndTristandaCunha => CountryAlpha3::SHN,
Self::SaintKittsAndNevis => CountryAlpha3::KNA,
Self::SaintLucia => CountryAlpha3::LCA,
Self::SaintMartinFrenchpart => CountryAlpha3::MAF,
Self::SaintPierreAndMiquelon => CountryAlpha3::SPM,
Self::SaintVincentAndTheGrenadines => CountryAlpha3::VCT,
Self::Samoa => CountryAlpha3::WSM,
Self::SanMarino => CountryAlpha3::SMR,
Self::SaoTomeAndPrincipe => CountryAlpha3::STP,
Self::SaudiArabia => CountryAlpha3::SAU,
Self::Senegal => CountryAlpha3::SEN,
Self::Serbia => CountryAlpha3::SRB,
Self::Seychelles => CountryAlpha3::SYC,
Self::SierraLeone => CountryAlpha3::SLE,
Self::Singapore => CountryAlpha3::SGP,
Self::SintMaartenDutchpart => CountryAlpha3::SXM,
Self::Slovakia => CountryAlpha3::SVK,
Self::Slovenia => CountryAlpha3::SVN,
Self::SolomonIslands => CountryAlpha3::SLB,
Self::Somalia => CountryAlpha3::SOM,
Self::SouthAfrica => CountryAlpha3::ZAF,
Self::SouthGeorgiaAndTheSouthSandwichIslands => CountryAlpha3::SGS,
Self::SouthSudan => CountryAlpha3::SSD,
Self::Spain => CountryAlpha3::ESP,
Self::SriLanka => CountryAlpha3::LKA,
Self::Sudan => CountryAlpha3::SDN,
Self::Suriname => CountryAlpha3::SUR,
Self::SvalbardAndJanMayen => CountryAlpha3::SJM,
Self::Swaziland => CountryAlpha3::SWZ,
Self::Sweden => CountryAlpha3::SWE,
Self::Switzerland => CountryAlpha3::CHE,
Self::SyrianArabRepublic => CountryAlpha3::SYR,
Self::TaiwanProvinceOfChina => CountryAlpha3::TWN,
Self::Tajikistan => CountryAlpha3::TJK,
Self::TanzaniaUnitedRepublic => CountryAlpha3::TZA,
Self::Thailand => CountryAlpha3::THA,
Self::TimorLeste => CountryAlpha3::TLS,
Self::Togo => CountryAlpha3::TGO,
Self::Tokelau => CountryAlpha3::TKL,
Self::Tonga => CountryAlpha3::TON,
Self::TrinidadAndTobago => CountryAlpha3::TTO,
Self::Tunisia => CountryAlpha3::TUN,
Self::Turkey => CountryAlpha3::TUR,
Self::Turkmenistan => CountryAlpha3::TKM,
Self::TurksAndCaicosIslands => CountryAlpha3::TCA,
Self::Tuvalu => CountryAlpha3::TUV,
Self::Uganda => CountryAlpha3::UGA,
Self::Ukraine => CountryAlpha3::UKR,
Self::UnitedArabEmirates => CountryAlpha3::ARE,
Self::UnitedKingdomOfGreatBritainAndNorthernIreland => CountryAlpha3::GBR,
Self::UnitedStatesOfAmerica => CountryAlpha3::USA,
Self::UnitedStatesMinorOutlyingIslands => CountryAlpha3::UMI,
Self::Uruguay => CountryAlpha3::URY,
Self::Uzbekistan => CountryAlpha3::UZB,
Self::Vanuatu => CountryAlpha3::VUT,
Self::VenezuelaBolivarianRepublic => CountryAlpha3::VEN,
Self::Vietnam => CountryAlpha3::VNM,
Self::VirginIslandsBritish => CountryAlpha3::VGB,
Self::VirginIslandsUS => CountryAlpha3::VIR,
Self::WallisAndFutuna => CountryAlpha3::WLF,
Self::WesternSahara => CountryAlpha3::ESH,
Self::Yemen => CountryAlpha3::YEM,
Self::Zambia => CountryAlpha3::ZMB,
Self::Zimbabwe => CountryAlpha3::ZWE,
}
}
pub const fn from_numeric(code: u32) -> Result<Self, NumericCountryCodeParseError> {
match code {
4 => Ok(Self::Afghanistan),
248 => Ok(Self::AlandIslands),
8 => Ok(Self::Albania),
12 => Ok(Self::Algeria),
16 => Ok(Self::AmericanSamoa),
20 => Ok(Self::Andorra),
24 => Ok(Self::Angola),
660 => Ok(Self::Anguilla),
10 => Ok(Self::Antarctica),
28 => Ok(Self::AntiguaAndBarbuda),
32 => Ok(Self::Argentina),
51 => Ok(Self::Armenia),
533 => Ok(Self::Aruba),
36 => Ok(Self::Australia),
40 => Ok(Self::Austria),
31 => Ok(Self::Azerbaijan),
44 => Ok(Self::Bahamas),
48 => Ok(Self::Bahrain),
50 => Ok(Self::Bangladesh),
52 => Ok(Self::Barbados),
112 => Ok(Self::Belarus),
56 => Ok(Self::Belgium),
84 => Ok(Self::Belize),
204 => Ok(Self::Benin),
60 => Ok(Self::Bermuda),
64 => Ok(Self::Bhutan),
68 => Ok(Self::BoliviaPlurinationalState),
535 => Ok(Self::BonaireSintEustatiusAndSaba),
70 => Ok(Self::BosniaAndHerzegovina),
72 => Ok(Self::Botswana),
74 => Ok(Self::BouvetIsland),
76 => Ok(Self::Brazil),
86 => Ok(Self::BritishIndianOceanTerritory),
96 => Ok(Self::BruneiDarussalam),
100 => Ok(Self::Bulgaria),
854 => Ok(Self::BurkinaFaso),
108 => Ok(Self::Burundi),
132 => Ok(Self::CaboVerde),
116 => Ok(Self::Cambodia),
120 => Ok(Self::Cameroon),
124 => Ok(Self::Canada),
136 => Ok(Self::CaymanIslands),
140 => Ok(Self::CentralAfricanRepublic),
148 => Ok(Self::Chad),
152 => Ok(Self::Chile),
156 => Ok(Self::China),
162 => Ok(Self::ChristmasIsland),
166 => Ok(Self::CocosKeelingIslands),
170 => Ok(Self::Colombia),
174 => Ok(Self::Comoros),
178 => Ok(Self::Congo),
180 => Ok(Self::CongoDemocraticRepublic),
184 => Ok(Self::CookIslands),
188 => Ok(Self::CostaRica),
384 => Ok(Self::CotedIvoire),
191 => Ok(Self::Croatia),
192 => Ok(Self::Cuba),
531 => Ok(Self::Curacao),
196 => Ok(Self::Cyprus),
203 => Ok(Self::Czechia),
208 => Ok(Self::Denmark),
262 => Ok(Self::Djibouti),
212 => Ok(Self::Dominica),
214 => Ok(Self::DominicanRepublic),
218 => Ok(Self::Ecuador),
818 => Ok(Self::Egypt),
222 => Ok(Self::ElSalvador),
226 => Ok(Self::EquatorialGuinea),
232 => Ok(Self::Eritrea),
233 => Ok(Self::Estonia),
231 => Ok(Self::Ethiopia),
238 => Ok(Self::FalklandIslandsMalvinas),
234 => Ok(Self::FaroeIslands),
242 => Ok(Self::Fiji),
246 => Ok(Self::Finland),
250 => Ok(Self::France),
254 => Ok(Self::FrenchGuiana),
258 => Ok(Self::FrenchPolynesia),
260 => Ok(Self::FrenchSouthernTerritories),
266 => Ok(Self::Gabon),
270 => Ok(Self::Gambia),
268 => Ok(Self::Georgia),
276 => Ok(Self::Germany),
288 => Ok(Self::Ghana),
292 => Ok(Self::Gibraltar),
300 => Ok(Self::Greece),
304 => Ok(Self::Greenland),
308 => Ok(Self::Grenada),
312 => Ok(Self::Guadeloupe),
316 => Ok(Self::Guam),
320 => Ok(Self::Guatemala),
831 => Ok(Self::Guernsey),
324 => Ok(Self::Guinea),
624 => Ok(Self::GuineaBissau),
328 => Ok(Self::Guyana),
332 => Ok(Self::Haiti),
334 => Ok(Self::HeardIslandAndMcDonaldIslands),
336 => Ok(Self::HolySee),
340 => Ok(Self::Honduras),
344 => Ok(Self::HongKong),
348 => Ok(Self::Hungary),
352 => Ok(Self::Iceland),
356 => Ok(Self::India),
360 => Ok(Self::Indonesia),
364 => Ok(Self::IranIslamicRepublic),
368 => Ok(Self::Iraq),
372 => Ok(Self::Ireland),
833 => Ok(Self::IsleOfMan),
376 => Ok(Self::Israel),
380 => Ok(Self::Italy),
388 => Ok(Self::Jamaica),
392 => Ok(Self::Japan),
832 => Ok(Self::Jersey),
400 => Ok(Self::Jordan),
398 => Ok(Self::Kazakhstan),
404 => Ok(Self::Kenya),
296 => Ok(Self::Kiribati),
408 => Ok(Self::KoreaDemocraticPeoplesRepublic),
410 => Ok(Self::KoreaRepublic),
414 => Ok(Self::Kuwait),
417 => Ok(Self::Kyrgyzstan),
418 => Ok(Self::LaoPeoplesDemocraticRepublic),
428 => Ok(Self::Latvia),
422 => Ok(Self::Lebanon),
426 => Ok(Self::Lesotho),
430 => Ok(Self::Liberia),
434 => Ok(Self::Libya),
438 => Ok(Self::Liechtenstein),
440 => Ok(Self::Lithuania),
442 => Ok(Self::Luxembourg),
446 => Ok(Self::Macao),
807 => Ok(Self::MacedoniaTheFormerYugoslavRepublic),
450 => Ok(Self::Madagascar),
454 => Ok(Self::Malawi),
458 => Ok(Self::Malaysia),
462 => Ok(Self::Maldives),
466 => Ok(Self::Mali),
470 => Ok(Self::Malta),
584 => Ok(Self::MarshallIslands),
474 => Ok(Self::Martinique),
478 => Ok(Self::Mauritania),
480 => Ok(Self::Mauritius),
175 => Ok(Self::Mayotte),
484 => Ok(Self::Mexico),
583 => Ok(Self::MicronesiaFederatedStates),
498 => Ok(Self::MoldovaRepublic),
492 => Ok(Self::Monaco),
496 => Ok(Self::Mongolia),
499 => Ok(Self::Montenegro),
500 => Ok(Self::Montserrat),
504 => Ok(Self::Morocco),
508 => Ok(Self::Mozambique),
104 => Ok(Self::Myanmar),
516 => Ok(Self::Namibia),
520 => Ok(Self::Nauru),
524 => Ok(Self::Nepal),
528 => Ok(Self::Netherlands),
540 => Ok(Self::NewCaledonia),
554 => Ok(Self::NewZealand),
558 => Ok(Self::Nicaragua),
562 => Ok(Self::Niger),
566 => Ok(Self::Nigeria),
570 => Ok(Self::Niue),
574 => Ok(Self::NorfolkIsland),
580 => Ok(Self::NorthernMarianaIslands),
578 => Ok(Self::Norway),
512 => Ok(Self::Oman),
586 => Ok(Self::Pakistan),
585 => Ok(Self::Palau),
275 => Ok(Self::PalestineState),
591 => Ok(Self::Panama),
598 => Ok(Self::PapuaNewGuinea),
600 => Ok(Self::Paraguay),
604 => Ok(Self::Peru),
608 => Ok(Self::Philippines),
612 => Ok(Self::Pitcairn),
616 => Ok(Self::Poland),
620 => Ok(Self::Portugal),
630 => Ok(Self::PuertoRico),
634 => Ok(Self::Qatar),
638 => Ok(Self::Reunion),
642 => Ok(Self::Romania),
643 => Ok(Self::RussianFederation),
646 => Ok(Self::Rwanda),
652 => Ok(Self::SaintBarthelemy),
654 => Ok(Self::SaintHelenaAscensionAndTristandaCunha),
659 => Ok(Self::SaintKittsAndNevis),
662 => Ok(Self::SaintLucia),
663 => Ok(Self::SaintMartinFrenchpart),
666 => Ok(Self::SaintPierreAndMiquelon),
670 => Ok(Self::SaintVincentAndTheGrenadines),
882 => Ok(Self::Samoa),
674 => Ok(Self::SanMarino),
678 => Ok(Self::SaoTomeAndPrincipe),
682 => Ok(Self::SaudiArabia),
686 => Ok(Self::Senegal),
688 => Ok(Self::Serbia),
690 => Ok(Self::Seychelles),
694 => Ok(Self::SierraLeone),
702 => Ok(Self::Singapore),
534 => Ok(Self::SintMaartenDutchpart),
703 => Ok(Self::Slovakia),
705 => Ok(Self::Slovenia),
90 => Ok(Self::SolomonIslands),
706 => Ok(Self::Somalia),
710 => Ok(Self::SouthAfrica),
239 => Ok(Self::SouthGeorgiaAndTheSouthSandwichIslands),
728 => Ok(Self::SouthSudan),
724 => Ok(Self::Spain),
144 => Ok(Self::SriLanka),
729 => Ok(Self::Sudan),
740 => Ok(Self::Suriname),
744 => Ok(Self::SvalbardAndJanMayen),
748 => Ok(Self::Swaziland),
752 => Ok(Self::Sweden),
756 => Ok(Self::Switzerland),
760 => Ok(Self::SyrianArabRepublic),
158 => Ok(Self::TaiwanProvinceOfChina),
762 => Ok(Self::Tajikistan),
834 => Ok(Self::TanzaniaUnitedRepublic),
764 => Ok(Self::Thailand),
626 => Ok(Self::TimorLeste),
768 => Ok(Self::Togo),
772 => Ok(Self::Tokelau),
776 => Ok(Self::Tonga),
780 => Ok(Self::TrinidadAndTobago),
788 => Ok(Self::Tunisia),
792 => Ok(Self::Turkey),
795 => Ok(Self::Turkmenistan),
796 => Ok(Self::TurksAndCaicosIslands),
798 => Ok(Self::Tuvalu),
800 => Ok(Self::Uganda),
804 => Ok(Self::Ukraine),
784 => Ok(Self::UnitedArabEmirates),
826 => Ok(Self::UnitedKingdomOfGreatBritainAndNorthernIreland),
840 => Ok(Self::UnitedStatesOfAmerica),
581 => Ok(Self::UnitedStatesMinorOutlyingIslands),
858 => Ok(Self::Uruguay),
860 => Ok(Self::Uzbekistan),
548 => Ok(Self::Vanuatu),
862 => Ok(Self::VenezuelaBolivarianRepublic),
704 => Ok(Self::Vietnam),
92 => Ok(Self::VirginIslandsBritish),
850 => Ok(Self::VirginIslandsUS),
876 => Ok(Self::WallisAndFutuna),
732 => Ok(Self::WesternSahara),
887 => Ok(Self::Yemen),
894 => Ok(Self::Zambia),
716 => Ok(Self::Zimbabwe),
_ => Err(NumericCountryCodeParseError),
}
}
pub const fn to_numeric(self) -> u32 {
match self {
Self::Afghanistan => 4,
Self::AlandIslands => 248,
Self::Albania => 8,
Self::Algeria => 12,
Self::AmericanSamoa => 16,
Self::Andorra => 20,
Self::Angola => 24,
Self::Anguilla => 660,
Self::Antarctica => 10,
Self::AntiguaAndBarbuda => 28,
Self::Argentina => 32,
Self::Armenia => 51,
Self::Aruba => 533,
Self::Australia => 36,
Self::Austria => 40,
Self::Azerbaijan => 31,
Self::Bahamas => 44,
Self::Bahrain => 48,
Self::Bangladesh => 50,
Self::Barbados => 52,
Self::Belarus => 112,
Self::Belgium => 56,
Self::Belize => 84,
Self::Benin => 204,
Self::Bermuda => 60,
Self::Bhutan => 64,
Self::BoliviaPlurinationalState => 68,
Self::BonaireSintEustatiusAndSaba => 535,
Self::BosniaAndHerzegovina => 70,
Self::Botswana => 72,
Self::BouvetIsland => 74,
Self::Brazil => 76,
Self::BritishIndianOceanTerritory => 86,
Self::BruneiDarussalam => 96,
Self::Bulgaria => 100,
Self::BurkinaFaso => 854,
Self::Burundi => 108,
Self::CaboVerde => 132,
Self::Cambodia => 116,
Self::Cameroon => 120,
Self::Canada => 124,
Self::CaymanIslands => 136,
Self::CentralAfricanRepublic => 140,
Self::Chad => 148,
Self::Chile => 152,
Self::China => 156,
Self::ChristmasIsland => 162,
Self::CocosKeelingIslands => 166,
Self::Colombia => 170,
Self::Comoros => 174,
Self::Congo => 178,
Self::CongoDemocraticRepublic => 180,
Self::CookIslands => 184,
Self::CostaRica => 188,
Self::CotedIvoire => 384,
Self::Croatia => 191,
Self::Cuba => 192,
Self::Curacao => 531,
Self::Cyprus => 196,
Self::Czechia => 203,
Self::Denmark => 208,
Self::Djibouti => 262,
Self::Dominica => 212,
Self::DominicanRepublic => 214,
Self::Ecuador => 218,
Self::Egypt => 818,
Self::ElSalvador => 222,
Self::EquatorialGuinea => 226,
Self::Eritrea => 232,
Self::Estonia => 233,
Self::Ethiopia => 231,
Self::FalklandIslandsMalvinas => 238,
Self::FaroeIslands => 234,
Self::Fiji => 242,
Self::Finland => 246,
Self::France => 250,
Self::FrenchGuiana => 254,
Self::FrenchPolynesia => 258,
Self::FrenchSouthernTerritories => 260,
Self::Gabon => 266,
Self::Gambia => 270,
Self::Georgia => 268,
Self::Germany => 276,
Self::Ghana => 288,
Self::Gibraltar => 292,
Self::Greece => 300,
Self::Greenland => 304,
Self::Grenada => 308,
Self::Guadeloupe => 312,
Self::Guam => 316,
Self::Guatemala => 320,
Self::Guernsey => 831,
Self::Guinea => 324,
Self::GuineaBissau => 624,
Self::Guyana => 328,
Self::Haiti => 332,
Self::HeardIslandAndMcDonaldIslands => 334,
Self::HolySee => 336,
Self::Honduras => 340,
Self::HongKong => 344,
Self::Hungary => 348,
Self::Iceland => 352,
Self::India => 356,
Self::Indonesia => 360,
Self::IranIslamicRepublic => 364,
Self::Iraq => 368,
Self::Ireland => 372,
Self::IsleOfMan => 833,
Self::Israel => 376,
Self::Italy => 380,
Self::Jamaica => 388,
Self::Japan => 392,
Self::Jersey => 832,
Self::Jordan => 400,
Self::Kazakhstan => 398,
Self::Kenya => 404,
Self::Kiribati => 296,
Self::KoreaDemocraticPeoplesRepublic => 408,
Self::KoreaRepublic => 410,
Self::Kuwait => 414,
Self::Kyrgyzstan => 417,
Self::LaoPeoplesDemocraticRepublic => 418,
Self::Latvia => 428,
Self::Lebanon => 422,
Self::Lesotho => 426,
Self::Liberia => 430,
Self::Libya => 434,
Self::Liechtenstein => 438,
Self::Lithuania => 440,
Self::Luxembourg => 442,
Self::Macao => 446,
Self::MacedoniaTheFormerYugoslavRepublic => 807,
Self::Madagascar => 450,
Self::Malawi => 454,
Self::Malaysia => 458,
Self::Maldives => 462,
Self::Mali => 466,
Self::Malta => 470,
Self::MarshallIslands => 584,
Self::Martinique => 474,
Self::Mauritania => 478,
Self::Mauritius => 480,
Self::Mayotte => 175,
Self::Mexico => 484,
Self::MicronesiaFederatedStates => 583,
Self::MoldovaRepublic => 498,
Self::Monaco => 492,
Self::Mongolia => 496,
Self::Montenegro => 499,
Self::Montserrat => 500,
Self::Morocco => 504,
Self::Mozambique => 508,
Self::Myanmar => 104,
Self::Namibia => 516,
Self::Nauru => 520,
Self::Nepal => 524,
Self::Netherlands => 528,
Self::NewCaledonia => 540,
Self::NewZealand => 554,
Self::Nicaragua => 558,
Self::Niger => 562,
Self::Nigeria => 566,
Self::Niue => 570,
Self::NorfolkIsland => 574,
Self::NorthernMarianaIslands => 580,
Self::Norway => 578,
Self::Oman => 512,
Self::Pakistan => 586,
Self::Palau => 585,
Self::PalestineState => 275,
Self::Panama => 591,
Self::PapuaNewGuinea => 598,
Self::Paraguay => 600,
Self::Peru => 604,
Self::Philippines => 608,
Self::Pitcairn => 612,
Self::Poland => 616,
Self::Portugal => 620,
Self::PuertoRico => 630,
Self::Qatar => 634,
Self::Reunion => 638,
Self::Romania => 642,
Self::RussianFederation => 643,
Self::Rwanda => 646,
Self::SaintBarthelemy => 652,
Self::SaintHelenaAscensionAndTristandaCunha => 654,
Self::SaintKittsAndNevis => 659,
Self::SaintLucia => 662,
Self::SaintMartinFrenchpart => 663,
Self::SaintPierreAndMiquelon => 666,
Self::SaintVincentAndTheGrenadines => 670,
Self::Samoa => 882,
Self::SanMarino => 674,
Self::SaoTomeAndPrincipe => 678,
Self::SaudiArabia => 682,
Self::Senegal => 686,
Self::Serbia => 688,
Self::Seychelles => 690,
Self::SierraLeone => 694,
Self::Singapore => 702,
Self::SintMaartenDutchpart => 534,
Self::Slovakia => 703,
Self::Slovenia => 705,
Self::SolomonIslands => 90,
Self::Somalia => 706,
Self::SouthAfrica => 710,
Self::SouthGeorgiaAndTheSouthSandwichIslands => 239,
Self::SouthSudan => 728,
Self::Spain => 724,
Self::SriLanka => 144,
Self::Sudan => 729,
Self::Suriname => 740,
Self::SvalbardAndJanMayen => 744,
Self::Swaziland => 748,
Self::Sweden => 752,
Self::Switzerland => 756,
Self::SyrianArabRepublic => 760,
Self::TaiwanProvinceOfChina => 158,
Self::Tajikistan => 762,
Self::TanzaniaUnitedRepublic => 834,
Self::Thailand => 764,
Self::TimorLeste => 626,
Self::Togo => 768,
Self::Tokelau => 772,
Self::Tonga => 776,
Self::TrinidadAndTobago => 780,
Self::Tunisia => 788,
Self::Turkey => 792,
Self::Turkmenistan => 795,
Self::TurksAndCaicosIslands => 796,
Self::Tuvalu => 798,
Self::Uganda => 800,
Self::Ukraine => 804,
Self::UnitedArabEmirates => 784,
Self::UnitedKingdomOfGreatBritainAndNorthernIreland => 826,
Self::UnitedStatesOfAmerica => 840,
Self::UnitedStatesMinorOutlyingIslands => 581,
Self::Uruguay => 858,
Self::Uzbekistan => 860,
Self::Vanuatu => 548,
Self::VenezuelaBolivarianRepublic => 862,
Self::Vietnam => 704,
Self::VirginIslandsBritish => 92,
Self::VirginIslandsUS => 850,
Self::WallisAndFutuna => 876,
Self::WesternSahara => 732,
Self::Yemen => 887,
Self::Zambia => 894,
Self::Zimbabwe => 716,
}
}
}
impl From<PaymentMethodType> for PaymentMethod {
fn from(value: PaymentMethodType) -> Self {
match value {
PaymentMethodType::Ach => Self::BankDebit,
PaymentMethodType::Affirm => Self::PayLater,
PaymentMethodType::AfterpayClearpay => Self::PayLater,
PaymentMethodType::AliPay => Self::Wallet,
PaymentMethodType::AliPayHk => Self::Wallet,
PaymentMethodType::Alma => Self::PayLater,
PaymentMethodType::AmazonPay => Self::Wallet,
PaymentMethodType::Paysera => Self::Wallet,
PaymentMethodType::Skrill => Self::Wallet,
PaymentMethodType::ApplePay => Self::Wallet,
PaymentMethodType::Bacs => Self::BankDebit,
PaymentMethodType::BancontactCard => Self::BankRedirect,
PaymentMethodType::BcaBankTransfer => Self::BankTransfer,
PaymentMethodType::Becs => Self::BankDebit,
PaymentMethodType::BniVa => Self::BankTransfer,
PaymentMethodType::Breadpay => Self::PayLater,
PaymentMethodType::BriVa => Self::BankTransfer,
PaymentMethodType::Benefit => Self::CardRedirect,
PaymentMethodType::Bizum => Self::BankRedirect,
PaymentMethodType::Blik => Self::BankRedirect,
PaymentMethodType::Bluecode => Self::Wallet,
PaymentMethodType::Alfamart => Self::Voucher,
PaymentMethodType::CardRedirect => Self::CardRedirect,
PaymentMethodType::CimbVa => Self::BankTransfer,
PaymentMethodType::ClassicReward => Self::Reward,
PaymentMethodType::Credit => Self::Card,
#[cfg(feature = "v2")]
PaymentMethodType::Card => Self::Card,
PaymentMethodType::CryptoCurrency => Self::Crypto,
PaymentMethodType::Dana => Self::Wallet,
PaymentMethodType::DanamonVa => Self::BankTransfer,
PaymentMethodType::Debit => Self::Card,
PaymentMethodType::Flexiti => Self::PayLater,
PaymentMethodType::Fps => Self::RealTimePayment,
PaymentMethodType::DuitNow => Self::RealTimePayment,
PaymentMethodType::Eft => Self::BankRedirect,
PaymentMethodType::Eps => Self::BankRedirect,
PaymentMethodType::Evoucher => Self::Reward,
PaymentMethodType::Giropay => Self::BankRedirect,
PaymentMethodType::GooglePay => Self::Wallet,
PaymentMethodType::GoPay => Self::Wallet,
PaymentMethodType::Gcash => Self::Wallet,
PaymentMethodType::Mifinity => Self::Wallet,
PaymentMethodType::Ideal => Self::BankRedirect,
PaymentMethodType::Qris => Self::RealTimePayment,
PaymentMethodType::Klarna => Self::PayLater,
PaymentMethodType::KakaoPay => Self::Wallet,
PaymentMethodType::Knet => Self::CardRedirect,
PaymentMethodType::LocalBankRedirect => Self::BankRedirect,
PaymentMethodType::MbWay => Self::Wallet,
PaymentMethodType::MobilePay => Self::Wallet,
PaymentMethodType::Momo => Self::Wallet,
PaymentMethodType::MomoAtm => Self::CardRedirect,
PaymentMethodType::Multibanco => Self::BankTransfer,
PaymentMethodType::MandiriVa => Self::BankTransfer,
PaymentMethodType::Interac => Self::BankRedirect,
PaymentMethodType::InstantBankTransfer => Self::BankTransfer,
PaymentMethodType::InstantBankTransferFinland => Self::BankTransfer,
PaymentMethodType::InstantBankTransferPoland => Self::BankTransfer,
PaymentMethodType::Indomaret => Self::Voucher,
PaymentMethodType::OnlineBankingCzechRepublic => Self::BankRedirect,
PaymentMethodType::OnlineBankingFinland => Self::BankRedirect,
PaymentMethodType::OnlineBankingFpx => Self::BankRedirect,
PaymentMethodType::OnlineBankingThailand => Self::BankRedirect,
PaymentMethodType::OnlineBankingPoland => Self::BankRedirect,
PaymentMethodType::OnlineBankingSlovakia => Self::BankRedirect,
PaymentMethodType::Paze => Self::Wallet,
PaymentMethodType::PermataBankTransfer => Self::BankTransfer,
PaymentMethodType::Pix => Self::BankTransfer,
PaymentMethodType::Pse => Self::BankTransfer,
PaymentMethodType::LocalBankTransfer => Self::BankTransfer,
PaymentMethodType::PayBright => Self::PayLater,
PaymentMethodType::Paypal => Self::Wallet,
PaymentMethodType::PaySafeCard => Self::GiftCard,
PaymentMethodType::Przelewy24 => Self::BankRedirect,
PaymentMethodType::PromptPay => Self::RealTimePayment,
PaymentMethodType::SamsungPay => Self::Wallet,
PaymentMethodType::Sepa => Self::BankDebit,
PaymentMethodType::SepaGuarenteedDebit => Self::BankDebit,
PaymentMethodType::SepaBankTransfer => Self::BankTransfer,
PaymentMethodType::Sofort => Self::BankRedirect,
PaymentMethodType::Swish => Self::BankRedirect,
PaymentMethodType::Trustly => Self::BankRedirect,
PaymentMethodType::Twint => Self::Wallet,
PaymentMethodType::UpiCollect => Self::Upi,
PaymentMethodType::UpiIntent => Self::Upi,
PaymentMethodType::UpiQr => Self::Upi,
PaymentMethodType::Vipps => Self::Wallet,
PaymentMethodType::Venmo => Self::Wallet,
PaymentMethodType::VietQr => Self::RealTimePayment,
PaymentMethodType::Walley => Self::PayLater,
PaymentMethodType::WeChatPay => Self::Wallet,
PaymentMethodType::TouchNGo => Self::Wallet,
PaymentMethodType::Atome => Self::PayLater,
PaymentMethodType::Payjustnow => Self::PayLater,
PaymentMethodType::Boleto => Self::Voucher,
PaymentMethodType::Efecty => Self::Voucher,
PaymentMethodType::PagoEfectivo => Self::Voucher,
PaymentMethodType::RedCompra => Self::Voucher,
PaymentMethodType::RedPagos => Self::Voucher,
PaymentMethodType::Cashapp => Self::Wallet,
PaymentMethodType::BhnCardNetwork => Self::GiftCard,
PaymentMethodType::Givex => Self::GiftCard,
PaymentMethodType::Oxxo => Self::Voucher,
PaymentMethodType::OpenBankingUk => Self::BankRedirect,
PaymentMethodType::SevenEleven => Self::Voucher,
PaymentMethodType::Lawson => Self::Voucher,
PaymentMethodType::MiniStop => Self::Voucher,
PaymentMethodType::FamilyMart => Self::Voucher,
PaymentMethodType::Seicomart => Self::Voucher,
PaymentMethodType::PayEasy => Self::Voucher,
PaymentMethodType::OpenBankingPIS => Self::OpenBanking,
PaymentMethodType::DirectCarrierBilling => Self::MobilePayment,
PaymentMethodType::RevolutPay => Self::Wallet,
PaymentMethodType::IndonesianBankTransfer => Self::BankTransfer,
PaymentMethodType::OpenBanking => Self::BankRedirect,
PaymentMethodType::NetworkToken => Self::NetworkToken,
}
}
}
#[derive(Debug)]
pub struct NumericCountryCodeParseError;
#[allow(dead_code)]
mod custom_serde {
use super::*;
pub mod alpha2_country_code {
use std::fmt;
use serde::de::Visitor;
use super::*;
// `serde::Serialize` implementation needs the function to accept `&Country`
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn serialize<S>(code: &Country, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
code.to_alpha2().serialize(serializer)
}
struct FieldVisitor;
impl Visitor<'_> for FieldVisitor {
type Value = CountryAlpha2;
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str("CountryAlpha2 as a string")
}
}
pub fn deserialize<'a, D>(deserializer: D) -> Result<Country, D::Error>
where
D: serde::Deserializer<'a>,
{
CountryAlpha2::deserialize(deserializer).map(Country::from_alpha2)
}
}
pub mod alpha3_country_code {
use std::fmt;
use serde::de::Visitor;
use super::*;
// `serde::Serialize` implementation needs the function to accept `&Country`
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn serialize<S>(code: &Country, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
code.to_alpha3().serialize(serializer)
}
struct FieldVisitor;
impl Visitor<'_> for FieldVisitor {
type Value = CountryAlpha3;
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str("CountryAlpha3 as a string")
}
}
pub fn deserialize<'a, D>(deserializer: D) -> Result<Country, D::Error>
where
D: serde::Deserializer<'a>,
{
CountryAlpha3::deserialize(deserializer).map(Country::from_alpha3)
}
}
pub mod numeric_country_code {
use std::fmt;
use serde::de::Visitor;
use super::*;
// `serde::Serialize` implementation needs the function to accept `&Country`
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn serialize<S>(code: &Country, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
code.to_numeric().serialize(serializer)
}
struct FieldVisitor;
impl Visitor<'_> for FieldVisitor {
type Value = u32;
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str("Numeric country code passed as an u32")
}
}
pub fn deserialize<'a, D>(deserializer: D) -> Result<Country, D::Error>
where
D: serde::Deserializer<'a>,
{
u32::deserialize(deserializer)
.and_then(|value| Country::from_numeric(value).map_err(serde::de::Error::custom))
}
}
}
impl From<Option<bool>> for super::External3dsAuthenticationRequest {
fn from(value: Option<bool>) -> Self {
match value {
Some(true) => Self::Enable,
_ => Self::Skip,
}
}
}
/// Get the boolean value of the `External3dsAuthenticationRequest`.
impl super::External3dsAuthenticationRequest {
pub fn as_bool(&self) -> bool {
match self {
Self::Enable => true,
Self::Skip => false,
}
}
}
impl super::EnablePaymentLinkRequest {
pub fn as_bool(&self) -> bool {
match self {
Self::Enable => true,
Self::Skip => false,
}
}
}
impl From<Option<bool>> for super::EnablePaymentLinkRequest {
fn from(value: Option<bool>) -> Self {
match value {
Some(true) => Self::Enable,
_ => Self::Skip,
}
}
}
impl From<Option<bool>> for super::MitExemptionRequest {
fn from(value: Option<bool>) -> Self {
match value {
Some(true) => Self::Apply,
_ => Self::Skip,
}
}
}
impl super::MitExemptionRequest {
pub fn as_bool(&self) -> bool {
match self {
Self::Apply => true,
Self::Skip => false,
}
}
}
impl From<Option<bool>> for super::PresenceOfCustomerDuringPayment {
fn from(value: Option<bool>) -> Self {
match value {
Some(false) => Self::Absent,
_ => Self::Present,
}
}
}
impl super::PresenceOfCustomerDuringPayment {
pub fn as_bool(&self) -> bool {
match self {
Self::Present => true,
Self::Absent => false,
}
}
}
impl From<AttemptStatus> for IntentStatus {
fn from(s: AttemptStatus) -> Self {
match s {
AttemptStatus::Charged | AttemptStatus::AutoRefunded => Self::Succeeded,
AttemptStatus::ConfirmationAwaited => Self::RequiresConfirmation,
AttemptStatus::PaymentMethodAwaited => Self::RequiresPaymentMethod,
AttemptStatus::Authorized => Self::RequiresCapture,
AttemptStatus::AuthenticationPending | AttemptStatus::DeviceDataCollectionPending => {
Self::RequiresCustomerAction
}
AttemptStatus::Unresolved => Self::RequiresMerchantAction,
AttemptStatus::IntegrityFailure => Self::Conflicted,
AttemptStatus::PartialCharged => Self::PartiallyCaptured,
AttemptStatus::PartialChargedAndChargeable => Self::PartiallyCapturedAndCapturable,
AttemptStatus::Started
| AttemptStatus::AuthenticationSuccessful
| AttemptStatus::Authorizing
| AttemptStatus::CodInitiated
| AttemptStatus::VoidInitiated
| AttemptStatus::CaptureInitiated
| AttemptStatus::Pending => Self::Processing,
AttemptStatus::AuthenticationFailed
| AttemptStatus::AuthorizationFailed
| AttemptStatus::VoidFailed
| AttemptStatus::RouterDeclined
| AttemptStatus::CaptureFailed
| AttemptStatus::Failure => Self::Failed,
AttemptStatus::Voided => Self::Cancelled,
AttemptStatus::VoidedPostCharge => Self::CancelledPostCapture,
AttemptStatus::Expired => Self::Expired,
AttemptStatus::PartiallyAuthorized => Self::PartiallyAuthorizedAndRequiresCapture,
}
}
}
impl From<IntentStatus> for Option<EventType> {
fn from(value: IntentStatus) -> Self {
match value {
IntentStatus::Succeeded => Some(EventType::PaymentSucceeded),
IntentStatus::Failed => Some(EventType::PaymentFailed),
IntentStatus::Processing | IntentStatus::PartiallyCapturedAndProcessing => {
Some(EventType::PaymentProcessing)
}
IntentStatus::RequiresMerchantAction
| IntentStatus::RequiresCustomerAction
| IntentStatus::Conflicted => Some(EventType::ActionRequired),
IntentStatus::Cancelled => Some(EventType::PaymentCancelled),
IntentStatus::CancelledPostCapture => Some(EventType::PaymentCancelledPostCapture),
IntentStatus::Expired => Some(EventType::PaymentExpired),
IntentStatus::PartiallyCaptured | IntentStatus::PartiallyCapturedAndCapturable => {
Some(EventType::PaymentCaptured)
}
IntentStatus::RequiresCapture => Some(EventType::PaymentAuthorized),
IntentStatus::RequiresPaymentMethod | IntentStatus::RequiresConfirmation => None,
IntentStatus::PartiallyAuthorizedAndRequiresCapture => {
Some(EventType::PaymentPartiallyAuthorized)
}
}
}
}
impl From<RefundStatus> for Option<EventType> {
fn from(value: RefundStatus) -> Self {
match value {
RefundStatus::Success => Some(EventType::RefundSucceeded),
RefundStatus::Failure => Some(EventType::RefundFailed),
RefundStatus::ManualReview
| RefundStatus::Pending
| RefundStatus::TransactionFailure => None,
}
}
}
#[cfg(feature = "payouts")]
impl From<PayoutStatus> for Option<EventType> {
fn from(value: PayoutStatus) -> Self {
match value {
PayoutStatus::Success => Some(EventType::PayoutSuccess),
PayoutStatus::Failed => Some(EventType::PayoutFailed),
PayoutStatus::Cancelled => Some(EventType::PayoutCancelled),
PayoutStatus::Initiated => Some(EventType::PayoutInitiated),
PayoutStatus::Expired => Some(EventType::PayoutExpired),
PayoutStatus::Reversed => Some(EventType::PayoutReversed),
PayoutStatus::Ineligible
| PayoutStatus::Pending
| PayoutStatus::RequiresCreation
| PayoutStatus::RequiresFulfillment
| PayoutStatus::RequiresPayoutMethodData
| PayoutStatus::RequiresVendorAccountCreation
| PayoutStatus::RequiresConfirmation => None,
}
}
}
impl From<DisputeStatus> for EventType {
fn from(value: DisputeStatus) -> Self {
match value {
DisputeStatus::DisputeOpened => Self::DisputeOpened,
DisputeStatus::DisputeExpired => Self::DisputeExpired,
DisputeStatus::DisputeAccepted => Self::DisputeAccepted,
DisputeStatus::DisputeCancelled => Self::DisputeCancelled,
DisputeStatus::DisputeChallenged => Self::DisputeChallenged,
DisputeStatus::DisputeWon => Self::DisputeWon,
DisputeStatus::DisputeLost => Self::DisputeLost,
}
}
}
impl From<MandateStatus> for Option<EventType> {
fn from(value: MandateStatus) -> Self {
match value {
MandateStatus::Active => Some(EventType::MandateActive),
MandateStatus::Revoked => Some(EventType::MandateRevoked),
MandateStatus::Inactive | MandateStatus::Pending => None,
}
}
}
impl From<SubscriptionStatus> for Option<EventType> {
fn from(value: SubscriptionStatus) -> Self {
match value {
SubscriptionStatus::Active => Some(EventType::InvoicePaid),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(serde::Serialize)]
struct Alpha2Request {
#[serde(with = "custom_serde::alpha2_country_code")]
pub country: Country,
}
#[derive(serde::Serialize)]
struct Alpha3Request {
#[serde(with = "custom_serde::alpha3_country_code")]
pub country: Country,
}
#[derive(serde::Serialize)]
struct NumericRequest {
#[serde(with = "custom_serde::numeric_country_code")]
pub country: Country,
}
#[derive(serde::Serialize, serde::Deserialize)]
struct HyperswitchRequestAlpha2 {
#[serde(with = "custom_serde::alpha2_country_code")]
pub country: Country,
}
#[derive(serde::Serialize, serde::Deserialize)]
struct HyperswitchRequestAlpha3 {
#[serde(with = "custom_serde::alpha3_country_code")]
pub country: Country,
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
struct HyperswitchRequestNumeric {
#[serde(with = "custom_serde::numeric_country_code")]
pub country: Country,
}
#[test]
fn test_serialize_alpha2() {
let x_request = Alpha2Request {
country: Country::India,
};
let serialized_country = serde_json::to_string(&x_request).unwrap();
assert_eq!(serialized_country, r#"{"country":"IN"}"#);
let x_request = Alpha2Request {
country: Country::MacedoniaTheFormerYugoslavRepublic,
};
let serialized_country = serde_json::to_string(&x_request).unwrap();
assert_eq!(serialized_country, r#"{"country":"MK"}"#);
let x_request = Alpha2Request {
country: Country::FrenchSouthernTerritories,
};
let serialized_country = serde_json::to_string(&x_request).unwrap();
assert_eq!(serialized_country, r#"{"country":"TF"}"#);
}
#[test]
fn test_serialize_alpha3() {
let y_request = Alpha3Request {
country: Country::India,
};
let serialized_country = serde_json::to_string(&y_request).unwrap();
assert_eq!(serialized_country, r#"{"country":"IND"}"#);
let y_request = Alpha3Request {
country: Country::HeardIslandAndMcDonaldIslands,
};
let serialized_country = serde_json::to_string(&y_request).unwrap();
assert_eq!(serialized_country, r#"{"country":"HMD"}"#);
let y_request = Alpha3Request {
country: Country::Argentina,
};
let serialized_country = serde_json::to_string(&y_request).unwrap();
assert_eq!(serialized_country, r#"{"country":"ARG"}"#);
}
#[test]
fn test_serialize_numeric() {
let y_request = NumericRequest {
country: Country::India,
};
let serialized_country = serde_json::to_string(&y_request).unwrap();
assert_eq!(serialized_country, r#"{"country":356}"#);
let y_request = NumericRequest {
country: Country::Bermuda,
};
let serialized_country = serde_json::to_string(&y_request).unwrap();
assert_eq!(serialized_country, r#"{"country":60}"#);
let y_request = NumericRequest {
country: Country::GuineaBissau,
};
let serialized_country = serde_json::to_string(&y_request).unwrap();
assert_eq!(serialized_country, r#"{"country":624}"#);
}
#[test]
fn test_deserialize_alpha2() {
let request_str = r#"{"country":"IN"}"#;
let request = serde_json::from_str::<HyperswitchRequestAlpha2>(request_str).unwrap();
assert_eq!(request.country, Country::India);
let request_str = r#"{"country":"GR"}"#;
let request = serde_json::from_str::<HyperswitchRequestAlpha2>(request_str).unwrap();
assert_eq!(request.country, Country::Greece);
let request_str = r#"{"country":"IQ"}"#;
let request = serde_json::from_str::<HyperswitchRequestAlpha2>(request_str).unwrap();
assert_eq!(request.country, Country::Iraq);
}
#[test]
fn test_deserialize_alpha3() {
let request_str = r#"{"country":"IND"}"#;
let request = serde_json::from_str::<HyperswitchRequestAlpha3>(request_str).unwrap();
assert_eq!(request.country, Country::India);
let request_str = r#"{"country":"LVA"}"#;
let request = serde_json::from_str::<HyperswitchRequestAlpha3>(request_str).unwrap();
assert_eq!(request.country, Country::Latvia);
let request_str = r#"{"country":"PNG"}"#;
let request = serde_json::from_str::<HyperswitchRequestAlpha3>(request_str).unwrap();
assert_eq!(request.country, Country::PapuaNewGuinea);
}
#[test]
fn test_deserialize_numeric() {
let request_str = r#"{"country":356}"#;
let request = serde_json::from_str::<HyperswitchRequestNumeric>(request_str).unwrap();
assert_eq!(request.country, Country::India);
let request_str = r#"{"country":239}"#;
let request = serde_json::from_str::<HyperswitchRequestNumeric>(request_str).unwrap();
assert_eq!(
request.country,
Country::SouthGeorgiaAndTheSouthSandwichIslands
);
let request_str = r#"{"country":826}"#;
let request = serde_json::from_str::<HyperswitchRequestNumeric>(request_str).unwrap();
assert_eq!(
request.country,
Country::UnitedKingdomOfGreatBritainAndNorthernIreland
);
}
#[test]
fn test_deserialize_and_serialize() {
// Deserialize the country as alpha2 code
// Serialize the country as alpha3 code
let request_str = r#"{"country":"IN"}"#;
let request = serde_json::from_str::<HyperswitchRequestAlpha2>(request_str).unwrap();
let alpha3_request = Alpha3Request {
country: request.country,
};
let response = serde_json::to_string::<Alpha3Request>(&alpha3_request).unwrap();
assert_eq!(response, r#"{"country":"IND"}"#)
}
#[test]
fn test_serialize_and_deserialize() {
let request_str = r#"{"country":"AX"}"#;
let request = serde_json::from_str::<HyperswitchRequestAlpha2>(request_str).unwrap();
let alpha3_request = Alpha3Request {
country: request.country,
};
let response = serde_json::to_string::<Alpha3Request>(&alpha3_request).unwrap();
assert_eq!(response, r#"{"country":"ALA"}"#);
let result = serde_json::from_str::<HyperswitchRequestAlpha3>(response.as_str()).unwrap();
assert_eq!(result.country, Country::AlandIslands);
}
#[test]
fn test_deserialize_invalid_country_code() {
let request_str = r#"{"country": 123456}"#;
let result: Result<HyperswitchRequestNumeric, _> =
serde_json::from_str::<HyperswitchRequestNumeric>(request_str);
assert!(result.is_err());
}
}
|
crates__common_types__src__payments.rs
|
//! Payment related types
use std::collections::HashMap;
use common_enums::enums;
use common_utils::{
date_time, errors, events, ext_traits::OptionExt, impl_to_sql_from_sql_json, pii,
types::MinorUnit,
};
use diesel::{
sql_types::{Jsonb, Text},
AsExpression, FromSqlRow,
};
use error_stack::{Report, Result, ResultExt};
use euclid::frontend::{
ast::Program,
dir::{DirKeyKind, EuclidDirFilter},
};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use smithy::SmithyModel;
use time::PrimitiveDateTime;
use utoipa::ToSchema;
use crate::domain::{AdyenSplitData, XenditSplitSubMerchantData};
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// Fee information for Split Payments to be charged on the payment being collected
pub enum SplitPaymentsRequest {
/// StripeSplitPayment
#[smithy(value_type = "StripeSplitPaymentRequest")]
StripeSplitPayment(StripeSplitPaymentRequest),
/// AdyenSplitPayment
#[smithy(value_type = "AdyenSplitData")]
AdyenSplitPayment(AdyenSplitData),
/// XenditSplitPayment
#[smithy(value_type = "XenditSplitRequest")]
XenditSplitPayment(XenditSplitRequest),
}
impl_to_sql_from_sql_json!(SplitPaymentsRequest);
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// Fee information for Split Payments to be charged on the payment being collected for Stripe
pub struct StripeSplitPaymentRequest {
/// Stripe's charge type
#[schema(value_type = PaymentChargeType, example = "direct")]
#[smithy(value_type = "PaymentChargeType")]
pub charge_type: enums::PaymentChargeType,
/// Platform fees to be collected on the payment
#[schema(value_type = i64, example = 6540)]
#[smithy(value_type = "Option<i64>")]
pub application_fees: Option<MinorUnit>,
/// Identifier for the reseller's account where the funds were transferred
#[smithy(value_type = "String")]
pub transfer_account_id: String,
}
impl_to_sql_from_sql_json!(StripeSplitPaymentRequest);
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
/// Hashmap to store mca_id's with product names
pub struct AuthenticationConnectorAccountMap(
HashMap<enums::AuthenticationProduct, common_utils::id_type::MerchantConnectorAccountId>,
);
impl_to_sql_from_sql_json!(AuthenticationConnectorAccountMap);
impl AuthenticationConnectorAccountMap {
/// fn to get click to pay connector_account_id
pub fn get_click_to_pay_connector_account_id(
&self,
) -> Result<common_utils::id_type::MerchantConnectorAccountId, errors::ValidationError> {
self.0
.get(&enums::AuthenticationProduct::ClickToPay)
.ok_or(errors::ValidationError::MissingRequiredField {
field_name: "authentication_product_id.click_to_pay".to_string(),
})
.map_err(Report::from)
.cloned()
}
}
/// A wrapper type for merchant country codes that provides validation and conversion functionality.
///
/// This type stores a country code as a string and provides methods to validate it
/// and convert it to a `Country` enum variant.
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Text)]
#[serde(deny_unknown_fields)]
pub struct MerchantCountryCode(String);
impl MerchantCountryCode {
/// Returns the country code as a string.
pub fn get_country_code(&self) -> String {
self.0.clone()
}
/// Validates the country code and returns a `Country` enum variant.
///
/// This method attempts to parse the country code as a u32 and convert it to a `Country` enum variant.
/// If the country code is invalid, it returns a `ValidationError` with the appropriate error message.
pub fn validate_and_get_country_from_merchant_country_code(
&self,
) -> errors::CustomResult<common_enums::Country, errors::ValidationError> {
let country_code = self.get_country_code();
let code = country_code
.parse::<u32>()
.map_err(Report::from)
.change_context(errors::ValidationError::IncorrectValueProvided {
field_name: "merchant_country_code",
})
.attach_printable_lazy(|| {
format!("Country code {country_code} is negative or too large")
})?;
common_enums::Country::from_numeric(code)
.map_err(|_| errors::ValidationError::IncorrectValueProvided {
field_name: "merchant_country_code",
})
.attach_printable_lazy(|| format!("Invalid country code {code}"))
}
/// Creates a new `MerchantCountryCode` instance from a string.
pub fn new(country_code: String) -> Self {
Self(country_code)
}
}
impl diesel::serialize::ToSql<Text, diesel::pg::Pg> for MerchantCountryCode {
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>,
) -> diesel::serialize::Result {
<String as diesel::serialize::ToSql<Text, diesel::pg::Pg>>::to_sql(&self.0, out)
}
}
impl diesel::deserialize::FromSql<Text, diesel::pg::Pg> for MerchantCountryCode {
fn from_sql(bytes: diesel::pg::PgValue<'_>) -> diesel::deserialize::Result<Self> {
let s = <String as diesel::deserialize::FromSql<Text, diesel::pg::Pg>>::from_sql(bytes)?;
Ok(Self(s))
}
}
#[derive(
Serialize, Default, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
/// ConditionalConfigs
pub struct ConditionalConfigs {
/// Override 3DS
pub override_3ds: Option<common_enums::AuthenticationType>,
}
impl EuclidDirFilter for ConditionalConfigs {
const ALLOWED: &'static [DirKeyKind] = &[
DirKeyKind::PaymentMethod,
DirKeyKind::CardType,
DirKeyKind::CardNetwork,
DirKeyKind::MetaData,
DirKeyKind::PaymentAmount,
DirKeyKind::PaymentCurrency,
DirKeyKind::CaptureMethod,
DirKeyKind::BillingCountry,
DirKeyKind::BusinessCountry,
DirKeyKind::NetworkTokenType,
];
}
impl_to_sql_from_sql_json!(ConditionalConfigs);
/// 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,
AsExpression,
ToSchema,
SmithyModel,
)]
#[serde(deny_unknown_fields)]
#[diesel(sql_type = Jsonb)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct CustomerAcceptance {
/// Type of acceptance provided by the
#[schema(example = "online")]
#[smithy(value_type = "AcceptanceType")]
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")]
#[smithy(value_type = "Option<PrimitiveDateTime>")]
pub accepted_at: Option<PrimitiveDateTime>,
/// Information required for online mandate generation
#[smithy(value_type = "Option<OnlineMandate>")]
pub online: Option<OnlineMandate>,
}
impl_to_sql_from_sql_json!(CustomerAcceptance);
impl CustomerAcceptance {
/// Get the IP address
pub fn get_ip_address(&self) -> Option<String> {
self.online
.as_ref()
.and_then(|data| data.ip_address.as_ref().map(|ip| ip.peek().to_owned()))
}
/// Get the User Agent
pub fn get_user_agent(&self) -> Option<String> {
self.online.as_ref().map(|data| data.user_agent.clone())
}
/// Get when the customer acceptance was provided
pub fn get_accepted_at(&self) -> PrimitiveDateTime {
self.accepted_at.unwrap_or_else(date_time::now)
}
}
impl masking::SerializableSecret for CustomerAcceptance {}
#[derive(
Default,
Debug,
serde::Deserialize,
serde::Serialize,
PartialEq,
Eq,
Clone,
Copy,
ToSchema,
SmithyModel,
)]
#[serde(rename_all = "lowercase")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// This is used to indicate if the mandate was accepted online or offline
pub enum AcceptanceType {
/// Online
Online,
/// Offline
#[default]
Offline,
}
#[derive(
Default,
Eq,
PartialEq,
Debug,
serde::Deserialize,
serde::Serialize,
AsExpression,
Clone,
ToSchema,
SmithyModel,
)]
#[serde(deny_unknown_fields)]
/// Details of online mandate
#[diesel(sql_type = Jsonb)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct OnlineMandate {
/// Ip address of the customer machine from which the mandate was created
#[schema(value_type = String, example = "123.32.25.123")]
#[smithy(value_type = "String")]
pub ip_address: Option<Secret<String, pii::IpAddress>>,
/// The user-agent of the customer's browser
#[smithy(value_type = "String")]
pub user_agent: String,
}
impl_to_sql_from_sql_json!(OnlineMandate);
#[derive(Serialize, Deserialize, Debug, Clone, FromSqlRow, AsExpression, ToSchema)]
#[diesel(sql_type = Jsonb)]
/// DecisionManagerRecord
pub struct DecisionManagerRecord {
/// Name of the Decision Manager
pub name: String,
/// Program to be executed
pub program: Program<ConditionalConfigs>,
/// Created at timestamp
pub created_at: i64,
}
impl events::ApiEventMetric for DecisionManagerRecord {
fn get_api_event_type(&self) -> Option<events::ApiEventsType> {
Some(events::ApiEventsType::Routing)
}
}
impl_to_sql_from_sql_json!(DecisionManagerRecord);
/// DecisionManagerResponse
pub type DecisionManagerResponse = DecisionManagerRecord;
/// Fee information to be charged on the payment being collected via Stripe
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct StripeChargeResponseData {
/// Identifier for charge created for the payment
#[smithy(value_type = "Option<String>")]
pub charge_id: Option<String>,
/// Type of charge (connector specific)
#[schema(value_type = PaymentChargeType, example = "direct")]
#[smithy(value_type = "PaymentChargeType")]
pub charge_type: enums::PaymentChargeType,
/// Platform fees collected on the payment
#[schema(value_type = i64, example = 6540)]
#[smithy(value_type = "Option<i64>")]
pub application_fees: Option<MinorUnit>,
/// Identifier for the reseller's account where the funds were transferred
#[smithy(value_type = "String")]
pub transfer_account_id: String,
}
impl_to_sql_from_sql_json!(StripeChargeResponseData);
/// Charge Information
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum ConnectorChargeResponseData {
/// StripeChargeResponseData
#[smithy(value_type = "StripeChargeResponseData")]
StripeSplitPayment(StripeChargeResponseData),
/// AdyenChargeResponseData
#[smithy(value_type = "AdyenSplitData")]
AdyenSplitPayment(AdyenSplitData),
/// XenditChargeResponseData
#[smithy(value_type = "XenditChargeResponseData")]
XenditSplitPayment(XenditChargeResponseData),
}
impl_to_sql_from_sql_json!(ConnectorChargeResponseData);
/// Fee information to be charged on the payment being collected via xendit
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct XenditSplitRoute {
/// Amount of payments to be split
#[smithy(value_type = "Option<i64>")]
pub flat_amount: Option<MinorUnit>,
/// Amount of payments to be split, using a percent rate as unit
#[smithy(value_type = "Option<i64>")]
pub percent_amount: Option<i64>,
/// Currency code
#[schema(value_type = Currency, example = "USD")]
#[smithy(value_type = "Currency")]
pub currency: enums::Currency,
/// ID of the destination account where the amount will be routed to
#[smithy(value_type = "String")]
pub destination_account_id: String,
/// Reference ID which acts as an identifier of the route itself
#[smithy(value_type = "String")]
pub reference_id: String,
}
impl_to_sql_from_sql_json!(XenditSplitRoute);
/// Fee information to be charged on the payment being collected via xendit
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct XenditMultipleSplitRequest {
/// Name to identify split rule. Not required to be unique. Typically based on transaction and/or sub-merchant types.
#[smithy(value_type = "String")]
pub name: String,
/// Description to identify fee rule
#[smithy(value_type = "String")]
pub description: String,
/// The sub-account user-id that you want to make this transaction for.
#[smithy(value_type = "Option<String>")]
pub for_user_id: Option<String>,
/// Array of objects that define how the platform wants to route the fees and to which accounts.
#[smithy(value_type = "Vec<XenditSplitRoute>")]
pub routes: Vec<XenditSplitRoute>,
}
impl_to_sql_from_sql_json!(XenditMultipleSplitRequest);
/// Xendit Charge Request
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum XenditSplitRequest {
/// Split Between Multiple Accounts
#[smithy(value_type = "XenditMultipleSplitRequest")]
MultipleSplits(XenditMultipleSplitRequest),
/// Collect Fee for Single Account
#[smithy(value_type = "XenditSplitSubMerchantData")]
SingleSplit(XenditSplitSubMerchantData),
}
impl_to_sql_from_sql_json!(XenditSplitRequest);
/// Charge Information
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum XenditChargeResponseData {
/// Split Between Multiple Accounts
#[smithy(value_type = "XenditMultipleSplitResponse")]
MultipleSplits(XenditMultipleSplitResponse),
/// Collect Fee for Single Account
#[smithy(value_type = "XenditSplitSubMerchantData")]
SingleSplit(XenditSplitSubMerchantData),
}
impl_to_sql_from_sql_json!(XenditChargeResponseData);
/// Fee information charged on the payment being collected via xendit
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct XenditMultipleSplitResponse {
/// Identifier for split rule created for the payment
#[smithy(value_type = "String")]
pub split_rule_id: String,
/// The sub-account user-id that you want to make this transaction for.
#[smithy(value_type = "Option<String>")]
pub for_user_id: Option<String>,
/// Name to identify split rule. Not required to be unique. Typically based on transaction and/or sub-merchant types.
#[smithy(value_type = "String")]
pub name: String,
/// Description to identify fee rule
#[smithy(value_type = "String")]
pub description: String,
/// Array of objects that define how the platform wants to route the fees and to which accounts.
#[smithy(value_type = "Vec<XenditSplitRoute>")]
pub routes: Vec<XenditSplitRoute>,
}
impl_to_sql_from_sql_json!(XenditMultipleSplitResponse);
#[derive(
Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[serde(rename_all = "snake_case")]
#[serde(untagged)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// This enum is used to represent the Gpay payment data, which can either be encrypted or decrypted.
pub enum GpayTokenizationData {
/// This variant contains the decrypted Gpay payment data as a structured object.
#[smithy(value_type = "GPayPredecryptData")]
Decrypted(GPayPredecryptData),
/// This variant contains the encrypted Gpay payment data as a string.
#[smithy(value_type = "GpayEcryptedTokenizationData")]
Encrypted(GpayEcryptedTokenizationData),
}
#[derive(
Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// This struct represents the encrypted Gpay payment data
pub struct GpayEcryptedTokenizationData {
/// The type of the token
#[serde(rename = "type")]
#[smithy(value_type = "String")]
pub token_type: String,
/// Token generated for the wallet
#[smithy(value_type = "String")]
pub token: String,
}
#[derive(
Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[serde(rename_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// This struct represents the decrypted Google Pay payment data
pub struct GPayPredecryptData {
/// The card's expiry month
#[schema(value_type = String)]
#[smithy(value_type = "String")]
pub card_exp_month: Secret<String>,
/// The card's expiry year
#[schema(value_type = String)]
#[smithy(value_type = "String")]
pub card_exp_year: Secret<String>,
/// The Primary Account Number (PAN) of the card
#[schema(value_type = String, example = "4242424242424242")]
#[smithy(value_type = "String")]
pub application_primary_account_number: cards::CardNumber,
/// Cryptogram generated by the Network
#[schema(value_type = String, example = "AgAAAAAAAIR8CQrXcIhbQAAAAAA")]
#[smithy(value_type = "Option<String>")]
pub cryptogram: Option<Secret<String>>,
/// Electronic Commerce Indicator
#[schema(value_type = String, example = "07")]
#[smithy(value_type = "Option<String>")]
pub eci_indicator: Option<String>,
}
impl GpayTokenizationData {
/// Get the encrypted Google Pay payment data, returning an error if it does not exist
pub fn get_encrypted_google_pay_payment_data_mandatory(
&self,
) -> Result<&GpayEcryptedTokenizationData, errors::ValidationError> {
match self {
Self::Encrypted(encrypted_data) => Ok(encrypted_data),
Self::Decrypted(_) => Err(errors::ValidationError::InvalidValue {
message: "Encrypted Google Pay payment data is mandatory".to_string(),
}
.into()),
}
}
/// Get the optional decrypted Google Pay payment data
pub fn get_decrypted_google_pay_payment_data_optional(&self) -> Option<&GPayPredecryptData> {
match self {
Self::Decrypted(token) => Some(token),
Self::Encrypted(_) => None,
}
}
/// Get the token from Google Pay tokenization data
/// Returns the token string if encrypted data exists, otherwise returns an error
pub fn get_encrypted_google_pay_token(&self) -> Result<String, errors::ValidationError> {
Ok(self
.get_encrypted_google_pay_payment_data_mandatory()?
.token
.clone())
}
/// Get the token type from Google Pay tokenization data
/// Returns the token_type string if encrypted data exists, otherwise returns an error
pub fn get_encrypted_token_type(&self) -> Result<String, errors::ValidationError> {
Ok(self
.get_encrypted_google_pay_payment_data_mandatory()?
.token_type
.clone())
}
}
impl GPayPredecryptData {
/// Get the four-digit expiration year from the Google Pay pre-decrypt data
pub fn get_four_digit_expiry_year(&self) -> Result<Secret<String>, errors::ValidationError> {
let mut year = self.card_exp_year.peek().clone();
// If it's a 2-digit year, convert to 4-digit
if year.len() == 2 {
year = format!("20{year}");
} else if year.len() != 4 {
return Err(errors::ValidationError::InvalidValue {
message: format!(
"Invalid expiry year length: {}. Must be 2 or 4 digits",
year.len()
),
}
.into());
}
Ok(Secret::new(year))
}
/// Get the 2-digit expiration year from the Google Pay pre-decrypt data
pub fn get_two_digit_expiry_year(&self) -> Result<Secret<String>, errors::ValidationError> {
let binding = self.card_exp_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ValidationError::InvalidValue {
message: "Invalid two-digit year".to_string(),
})?
.to_string(),
))
}
/// Get the expiry date in MMYY format from the Google Pay pre-decrypt data
pub fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ValidationError> {
let year = self.get_two_digit_expiry_year()?.expose();
let month = self.get_expiry_month()?.clone().expose();
Ok(Secret::new(format!("{month}{year}")))
}
/// Get the expiration month from the Google Pay pre-decrypt data
pub fn get_expiry_month(&self) -> Result<Secret<String>, errors::ValidationError> {
let month_str = self.card_exp_month.peek();
let month = month_str
.parse::<u8>()
.map_err(|_| errors::ValidationError::InvalidValue {
message: format!("Failed to parse expiry month: {month_str}"),
})?;
if !(1..=12).contains(&month) {
return Err(errors::ValidationError::InvalidValue {
message: format!("Invalid expiry month: {month}. Must be between 1 and 12"),
}
.into());
}
Ok(self.card_exp_month.clone())
}
}
#[derive(
Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[serde(rename_all = "snake_case")]
#[serde(untagged)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// This enum is used to represent the Apple Pay payment data, which can either be encrypted or decrypted.
pub enum ApplePayPaymentData {
/// This variant contains the decrypted Apple Pay payment data as a structured object.
#[smithy(value_type = "ApplePayPredecryptData")]
Decrypted(ApplePayPredecryptData),
/// This variant contains the encrypted Apple Pay payment data as a string.
#[smithy(value_type = "String")]
Encrypted(String),
}
#[derive(
Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[serde(rename_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// This struct represents the decrypted Apple Pay payment data
pub struct ApplePayPredecryptData {
/// The primary account number
#[schema(value_type = String, example = "4242424242424242")]
#[smithy(value_type = "String")]
pub application_primary_account_number: cards::CardNumber,
/// The application expiration date (PAN expiry month)
#[schema(value_type = String, example = "12")]
#[smithy(value_type = "String")]
pub application_expiration_month: Secret<String>,
/// The application expiration date (PAN expiry year)
#[schema(value_type = String, example = "24")]
#[smithy(value_type = "String")]
pub application_expiration_year: Secret<String>,
/// The payment data, which contains the cryptogram and ECI indicator
#[schema(value_type = ApplePayCryptogramData)]
#[smithy(value_type = "ApplePayCryptogramData")]
pub payment_data: ApplePayCryptogramData,
}
#[derive(
Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[serde(rename_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// This struct represents the cryptogram data for Apple Pay transactions
pub struct ApplePayCryptogramData {
/// The online payment cryptogram
#[schema(value_type = String, example = "A1B2C3D4E5F6G7H8")]
#[smithy(value_type = "String")]
pub online_payment_cryptogram: Secret<String>,
/// The ECI (Electronic Commerce Indicator) value
#[schema(value_type = String, example = "05")]
#[smithy(value_type = "Option<String>")]
pub eci_indicator: Option<String>,
}
impl ApplePayPaymentData {
/// Get the encrypted Apple Pay payment data if it exists
pub fn get_encrypted_apple_pay_payment_data_optional(&self) -> Option<&String> {
match self {
Self::Encrypted(encrypted_data) => Some(encrypted_data),
Self::Decrypted(_) => None,
}
}
/// Get the decrypted Apple Pay payment data if it exists
pub fn get_decrypted_apple_pay_payment_data_optional(&self) -> Option<&ApplePayPredecryptData> {
match self {
Self::Encrypted(_) => None,
Self::Decrypted(decrypted_data) => Some(decrypted_data),
}
}
/// Get the encrypted Apple Pay payment data, returning an error if it does not exist
pub fn get_encrypted_apple_pay_payment_data_mandatory(
&self,
) -> Result<&String, errors::ValidationError> {
self.get_encrypted_apple_pay_payment_data_optional()
.get_required_value("Encrypted Apple Pay payment data")
.attach_printable("Encrypted Apple Pay payment data is mandatory")
}
/// Get the decrypted Apple Pay payment data, returning an error if it does not exist
pub fn get_decrypted_apple_pay_payment_data_mandatory(
&self,
) -> Result<&ApplePayPredecryptData, errors::ValidationError> {
self.get_decrypted_apple_pay_payment_data_optional()
.get_required_value("Decrypted Apple Pay payment data")
.attach_printable("Decrypted Apple Pay payment data is mandatory")
}
}
impl ApplePayPredecryptData {
/// Get the four-digit expiration year from the Apple Pay pre-decrypt data
pub fn get_two_digit_expiry_year(&self) -> Result<Secret<String>, errors::ValidationError> {
let binding = self.application_expiration_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ValidationError::InvalidValue {
message: "Invalid two-digit year".to_string(),
})?
.to_string(),
))
}
/// Get the four-digit expiration year from the Apple Pay pre-decrypt data
pub fn get_four_digit_expiry_year(&self) -> Secret<String> {
let mut year = self.application_expiration_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
/// Get the expiration month from the Apple Pay pre-decrypt data
pub fn get_expiry_month(&self) -> Result<Secret<String>, errors::ValidationError> {
let month_str = self.application_expiration_month.peek();
let month = month_str
.parse::<u8>()
.map_err(|_| errors::ValidationError::InvalidValue {
message: format!("Failed to parse expiry month: {month_str}"),
})?;
if !(1..=12).contains(&month) {
return Err(errors::ValidationError::InvalidValue {
message: format!("Invalid expiry month: {month}. Must be between 1 and 12"),
}
.into());
}
Ok(self.application_expiration_month.clone())
}
/// Get the two-digit expiration month from the Apple Pay pre-decrypt data
/// Returns the month with zero-padding if it's a single digit (e.g., "1" -> "01")
pub fn get_two_digit_expiry_month(&self) -> Result<Secret<String>, errors::ValidationError> {
let month_str = self.application_expiration_month.peek();
let month = month_str
.parse::<u8>()
.map_err(|_| errors::ValidationError::InvalidValue {
message: format!("Failed to parse expiry month: {month_str}"),
})?;
if !(1..=12).contains(&month) {
return Err(errors::ValidationError::InvalidValue {
message: format!("Invalid expiry month: {month}. Must be between 1 and 12"),
}
.into());
}
Ok(Secret::new(format!("{:02}", month)))
}
/// Get the expiry date in MMYY format from the Apple Pay pre-decrypt data
pub fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ValidationError> {
let year = self.get_two_digit_expiry_year()?.expose();
let month = self.get_expiry_month()?.expose();
Ok(Secret::new(format!("{month}{year}")))
}
/// Get the expiry date in YYMM format from the Apple Pay pre-decrypt data
pub fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ValidationError> {
let year = self.get_two_digit_expiry_year()?.expose();
let month = self.get_expiry_month()?.expose();
Ok(Secret::new(format!("{year}{month}")))
}
}
/// type of action that needs to taken after consuming recovery payload
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RecoveryAction {
/// Stops the process tracker and update the payment intent.
CancelInvoice,
/// Records the external transaction against payment intent.
ScheduleFailedPayment,
/// Records the external payment and stops the internal process tracker.
SuccessPaymentExternal,
/// Pending payments from billing processor.
PendingPayment,
/// No action required.
NoAction,
/// Invalid event has been received.
InvalidAction,
}
/// Billing Descriptor information to be sent to the payment gateway
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, AsExpression, FromSqlRow, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct BillingDescriptor {
/// name to be put in billing description
#[schema(value_type = Option<String>, example = "The Online Retailer")]
pub name: Option<Secret<String>>,
/// city to be put in billing description
#[schema(value_type = Option<String>, example = "San Francisco")]
pub city: Option<Secret<String>>,
/// phone to be put in billing description
#[schema(value_type = Option<String>, example = "9123456789")]
pub phone: Option<Secret<String>>,
/// a short description for the payment
pub statement_descriptor: Option<String>,
/// Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor.
pub statement_descriptor_suffix: Option<String>,
/// A reference to be shown on billing description
pub reference: Option<String>,
}
impl_to_sql_from_sql_json!(BillingDescriptor);
/// Information identifying partner / external platform details
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, AsExpression, FromSqlRow, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct PartnerApplicationDetails {
/// Name of the partner/external platform
#[schema(value_type = Option<String>)]
pub name: Option<String>,
/// Version of the partner/external platform
#[schema(value_type = Option<String>, example = "1.0.0")]
pub version: Option<String>,
/// Integrator
#[schema(value_type = Option<String>)]
pub integrator: Option<String>,
}
impl_to_sql_from_sql_json!(PartnerApplicationDetails);
/// Information identifying merchant details
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, AsExpression, FromSqlRow, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct MerchantApplicationDetails {
/// Name of the the merchant application
#[schema(value_type = Option<String>)]
pub name: Option<String>,
/// Version of the merchant application
#[schema(value_type = Option<String>)]
pub version: Option<String>,
}
impl_to_sql_from_sql_json!(MerchantApplicationDetails);
/// Information identifying partner and merchant application initiating the request
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, AsExpression, FromSqlRow, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct PartnerMerchantIdentifierDetails {
/// Information identifying partner/external platform details
#[schema(value_type = Option<PartnerApplicationDetails>)]
pub partner_details: Option<PartnerApplicationDetails>,
/// Information identifying merchant details
#[schema(value_type = Option<MerchantApplicationDetails>)]
pub merchant_details: Option<MerchantApplicationDetails>,
}
impl_to_sql_from_sql_json!(PartnerMerchantIdentifierDetails);
/// Additional metadata for payment intent state containing refunded and disputed amounts
#[derive(
Default,
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
AsExpression,
FromSqlRow,
utoipa::ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct PaymentIntentStateMetadata {
/// Shows up the total refunded amount for a payment
pub total_refunded_amount: Option<MinorUnit>,
/// Shows up the total disputed amount across all disputes for a particular payment
pub total_disputed_amount: Option<MinorUnit>,
}
impl PaymentIntentStateMetadata {
/// Builder method to set total_refunded_amount
pub fn with_total_refunded_amount(mut self, amount: MinorUnit) -> Self {
self.total_refunded_amount = Some(amount);
self
}
/// Builder method to set total_disputed_amount
pub fn with_total_disputed_amount(mut self, amount: MinorUnit) -> Self {
self.total_disputed_amount = Some(amount);
self
}
/// Get the blocked amount which is the sum of total disputed and total refunded amounts
pub fn get_blocked_amount(self) -> MinorUnit {
let blocked_amount = self
.total_disputed_amount
.unwrap_or(MinorUnit::zero())
.get_amount_as_i64()
+ self
.total_refunded_amount
.unwrap_or(MinorUnit::zero())
.get_amount_as_i64();
MinorUnit::new(blocked_amount)
}
}
common_utils::impl_to_sql_from_sql_json!(PaymentIntentStateMetadata);
/// List of custom T&C messages grouped by payment method
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, utoipa::ToSchema)]
pub struct PaymentMethodsConfig(
#[schema(example = json!([
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"message": {
"value": "I authorize this payment",
"display_mode": "default_sdk_message"
}
}
]
}
]))]
pub Vec<PaymentMethodConfig>,
);
/// Custom T&C messages for a specific payment method
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, utoipa::ToSchema)]
pub struct PaymentMethodConfig {
/// Payment Method
#[schema(value_type = PaymentMethod, example = "card")]
pub payment_method: common_enums::PaymentMethod,
/// Payment Method Types
#[schema(example = json!([
{
"payment_method_type": "credit",
"message": {
"value": "Sample message",
"display_mode": "custom"
}
}
]))]
#[schema(value_type = Vec<CustomTerms>)]
pub payment_method_types: Vec<CustomTerms>,
}
/// Custom T&C message for a specific payment method type
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, utoipa::ToSchema)]
pub struct CustomTerms {
/// Payment Method Type
#[schema(value_type = PaymentMethodType, example = "sepa")]
pub payment_method_type: common_enums::PaymentMethodType,
/// The message to be shown
#[schema(value_type = CustomMessage)]
pub message: CustomMessage,
}
/// Custom T&C message content and display mode
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, utoipa::ToSchema)]
pub struct CustomMessage {
/// The text to be shown per payment method type
#[schema(value_type = String, example = "I authorize Novalnet AG to debit my account.")]
pub value: String,
/// The display mode for terms and conditions
#[schema(value_type = SdkDisplayMode , example = "custom")]
#[serde(default)]
pub display_mode: SdkDisplayMode,
}
/// Display mode options for controlling how messages are shown.
#[derive(Default, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum SdkDisplayMode {
/// Display the default terms and conditions in sdk
#[default]
DefaultSdkMessage,
/// Display the custom configured by the merchant
CustomMessage,
/// No terms and conditions to be shown
Hidden,
}
impl PaymentMethodsConfig {
/// Validation function for custom terms and conditions
pub fn validate(&self) -> Result<(), errors::ValidationError> {
for pm_config in &self.0 {
let parent_pm = pm_config.payment_method;
for pm_type_config in &pm_config.payment_method_types {
let pm_type = pm_type_config.payment_method_type;
// Check if the payment_method_type belongs to the parent payment_method
if common_enums::PaymentMethod::from(pm_type) != parent_pm {
return Err(errors::ValidationError::InvalidValue {
message: "Payment Method Type '{pm_type}' does not belong to Payment Method '{parent_pm}'".to_string(),
}
.into());
}
}
}
Ok(())
}
}
/// Interac Customer Information Details
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct InteracCustomerInfoDetails {
/// Customer Name
#[schema(value_type = Option<String>)]
pub customer_name: Option<Secret<String>>,
/// Customer Email
#[schema(value_type = Option<String>)]
pub customer_email: Option<pii::Email>,
/// Customer Phone Number
#[schema(value_type = Option<String>)]
pub customer_phone_number: Option<Secret<String>>,
/// Customer Bank Id
#[schema(value_type = Option<String>)]
pub customer_bank_id: Option<Secret<String>>,
/// Customer Bank Name
#[schema(value_type = Option<String>)]
pub customer_bank_name: Option<Secret<String>>,
}
/// Network Transaction ID and Decrypted Wallet Token Details
#[derive(
Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct NetworkTransactionIdAndDecryptedWalletTokenDetails {
/// The Decrypted Token
#[schema(value_type = String, example = "4604000460040787")]
#[smithy(value_type = "String")]
pub decrypted_token: cards::NetworkToken,
/// The token's expiry month
#[schema(value_type = String, example = "05")]
#[smithy(value_type = "String")]
pub token_exp_month: Secret<String>,
/// The token's expiry year
#[schema(value_type = String, example = "24")]
#[smithy(value_type = "String")]
pub token_exp_year: Secret<String>,
/// The card holder's name
#[schema(value_type = String, example = "John Test")]
#[smithy(value_type = "Option<String>")]
pub card_holder_name: Option<Secret<String>>,
/// The network transaction ID provided by the card network during a Customer Initiated Transaction (CIT)
/// when `setup_future_usage` is set to `off_session`.
#[schema(value_type = String)]
#[smithy(value_type = "String")]
pub network_transaction_id: Secret<String>,
/// ECI indicator of the card
pub eci: Option<String>,
/// Source of the token
#[schema(value_type = Option<TokenSource>, example = "googlepay")]
pub token_source: Option<TokenSource>,
}
#[derive(
Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq, SmithyModel,
)]
#[schema(example = "google_pay, apple_pay")]
#[serde(rename_all = "snake_case")]
/// Source of the token
pub enum TokenSource {
/// Google Pay
GooglePay,
/// Apple Pay
ApplePay,
}
|
crates__common_types__src__primitive_wrappers.rs
|
pub use bool_wrappers::*;
pub use safe_string::*;
pub use u16_wrappers::*;
pub use u32_wrappers::*;
mod bool_wrappers {
use std::ops::Deref;
use serde::{Deserialize, Serialize};
/// Bool that represents if Extended Authorization is Applied or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct ExtendedAuthorizationAppliedBool(bool);
impl Deref for ExtendedAuthorizationAppliedBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<bool> for ExtendedAuthorizationAppliedBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for ExtendedAuthorizationAppliedBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for ExtendedAuthorizationAppliedBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Extended Authorization is Requested or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct RequestExtendedAuthorizationBool(bool);
impl Deref for RequestExtendedAuthorizationBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<bool> for RequestExtendedAuthorizationBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl RequestExtendedAuthorizationBool {
/// returns the inner bool value
pub fn is_true(&self) -> bool {
self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for RequestExtendedAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for RequestExtendedAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Enable Partial Authorization is Requested or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct EnablePartialAuthorizationBool(bool);
impl Deref for EnablePartialAuthorizationBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<bool> for EnablePartialAuthorizationBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl EnablePartialAuthorizationBool {
/// returns the inner bool value
pub fn is_true(&self) -> bool {
self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for EnablePartialAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for EnablePartialAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Extended Authorization is always Requested or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct AlwaysRequestExtendedAuthorization(bool);
impl Deref for AlwaysRequestExtendedAuthorization {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB>
for AlwaysRequestExtendedAuthorization
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for AlwaysRequestExtendedAuthorization
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Cvv should be collected during payment or not. Default is true
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct ShouldCollectCvvDuringPayment(bool);
impl Deref for ShouldCollectCvvDuringPayment {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for ShouldCollectCvvDuringPayment
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for ShouldCollectCvvDuringPayment
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
impl Default for ShouldCollectCvvDuringPayment {
/// Default for `ShouldCollectCvvDuringPayment` is `true`
fn default() -> Self {
Self(true)
}
}
/// Bool that represents if overcapture should always be requested
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct AlwaysEnableOvercaptureBool(bool);
impl AlwaysEnableOvercaptureBool {
/// returns the inner bool value
pub fn is_true(&self) -> bool {
self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for AlwaysEnableOvercaptureBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for AlwaysEnableOvercaptureBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
impl Default for AlwaysEnableOvercaptureBool {
/// Default for `AlwaysEnableOvercaptureBool` is `false`
fn default() -> Self {
Self(false)
}
}
/// Bool that represents if overcapture is requested for this payment
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct EnableOvercaptureBool(bool);
impl From<bool> for EnableOvercaptureBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl From<AlwaysEnableOvercaptureBool> for EnableOvercaptureBool {
fn from(item: AlwaysEnableOvercaptureBool) -> Self {
Self(item.is_true())
}
}
impl Deref for EnableOvercaptureBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for EnableOvercaptureBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for EnableOvercaptureBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
impl Default for EnableOvercaptureBool {
/// Default for `EnableOvercaptureBool` is `false`
fn default() -> Self {
Self(false)
}
}
/// Bool that represents if overcapture is applied for a payment by the connector
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct OvercaptureEnabledBool(bool);
impl OvercaptureEnabledBool {
/// Creates a new instance of `OvercaptureEnabledBool`
pub fn new(value: bool) -> Self {
Self(value)
}
}
impl Default for OvercaptureEnabledBool {
/// Default for `OvercaptureEnabledBool` is `false`
fn default() -> Self {
Self(false)
}
}
impl Deref for OvercaptureEnabledBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for OvercaptureEnabledBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for OvercaptureEnabledBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
}
mod u32_wrappers {
use std::ops::Deref;
use serde::{de::Error, Deserialize, Serialize};
use crate::consts::{
DEFAULT_DISPUTE_POLLING_INTERVAL_IN_HOURS, MAX_DISPUTE_POLLING_INTERVAL_IN_HOURS,
};
/// Time interval in hours for polling disputes
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, diesel::expression::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Integer)]
pub struct DisputePollingIntervalInHours(i32);
impl Deref for DisputePollingIntervalInHours {
type Target = i32;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'de> Deserialize<'de> for DisputePollingIntervalInHours {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let val = i32::deserialize(deserializer)?;
if val < 0 {
Err(D::Error::custom(
"DisputePollingIntervalInHours cannot be negative",
))
} else if val > MAX_DISPUTE_POLLING_INTERVAL_IN_HOURS {
Err(D::Error::custom(
"DisputePollingIntervalInHours exceeds the maximum allowed value of 24",
))
} else {
Ok(Self(val))
}
}
}
impl diesel::deserialize::FromSql<diesel::sql_types::Integer, diesel::pg::Pg>
for DisputePollingIntervalInHours
{
fn from_sql(value: diesel::pg::PgValue<'_>) -> diesel::deserialize::Result<Self> {
i32::from_sql(value).map(Self)
}
}
impl diesel::serialize::ToSql<diesel::sql_types::Integer, diesel::pg::Pg>
for DisputePollingIntervalInHours
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>,
) -> diesel::serialize::Result {
<i32 as diesel::serialize::ToSql<diesel::sql_types::Integer, diesel::pg::Pg>>::to_sql(
&self.0, out,
)
}
}
impl Default for DisputePollingIntervalInHours {
/// Default for `DisputePollingIntervalInHours` is `24`
fn default() -> Self {
Self(DEFAULT_DISPUTE_POLLING_INTERVAL_IN_HOURS)
}
}
}
mod u16_wrappers {
use std::ops::Deref;
use serde::{de::Error, Deserialize, Serialize};
use crate::consts::{
CUSTOMER_LIST_DEFAULT_LIMIT, CUSTOMER_LIST_LOWER_LIMIT, CUSTOMER_LIST_UPPER_LIMIT,
};
/// Customer list limit wrapper with automatic validation
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
pub struct CustomerListLimit(u16);
impl Deref for CustomerListLimit {
type Target = u16;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'de> Deserialize<'de> for CustomerListLimit {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let val = u16::deserialize(deserializer)?;
Self::new(val).map_err(D::Error::custom)
}
}
impl Default for CustomerListLimit {
/// Default for `CustomerListLimit` is `20`
fn default() -> Self {
Self(CUSTOMER_LIST_DEFAULT_LIMIT)
}
}
impl CustomerListLimit {
/// Creates a new CustomerListLimit with validation
pub fn new(value: u16) -> Result<Self, String> {
if value < CUSTOMER_LIST_LOWER_LIMIT {
Err(format!(
"CustomerListLimit cannot be less than {}",
CUSTOMER_LIST_LOWER_LIMIT
))
} else if value > CUSTOMER_LIST_UPPER_LIMIT {
Err(format!(
"CustomerListLimit exceeds the maximum allowed value of {}",
CUSTOMER_LIST_UPPER_LIMIT
))
} else {
Ok(Self(value))
}
}
}
}
/// Safe string wrapper that validates input against XSS attacks
mod safe_string {
use std::ops::Deref;
use common_utils::validation::contains_potential_xss_or_sqli;
use masking::SerializableSecret;
use serde::{de::Error, Deserialize, Serialize};
/// String wrapper that prevents XSS and SQLi attacks
#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub struct SafeString(String);
impl SafeString {
/// Creates a new SafeString after XSS and SQL injection validation
pub fn new(value: String) -> Result<Self, String> {
if contains_potential_xss_or_sqli(&value) {
return Err("Input contains potentially malicious content".into());
}
Ok(Self(value))
}
/// Creates a SafeString from a string slice
pub fn from_string_slice(value: &str) -> Result<Self, String> {
Self::new(value.to_string())
}
/// Returns the inner string as a string slice
pub fn as_str(&self) -> &str {
&self.0
}
/// Consumes self and returns the inner String
pub fn into_inner(self) -> String {
self.0
}
/// Returns true if the string is empty
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Returns the length of the string
pub fn len(&self) -> usize {
self.0.len()
}
}
impl Deref for SafeString {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.0
}
}
// Custom serialization and deserialization
impl Serialize for SafeString {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.0.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for SafeString {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Self::new(value).map_err(D::Error::custom)
}
}
// Implement SerializableSecret for SafeString to work with Secret<SafeString>
impl SerializableSecret for SafeString {}
// Diesel implementations for database operations
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Text, DB> for SafeString
where
DB: diesel::backend::Backend,
String: diesel::serialize::ToSql<diesel::sql_types::Text, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Text, DB> for SafeString
where
DB: diesel::backend::Backend,
String: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
String::from_sql(value).map(Self)
}
}
}
|
crates__common_utils__src__crypto.rs
|
//! Utilities for cryptographic algorithms
use std::ops::Deref;
use base64::Engine;
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret};
use ring::{
aead::{self, BoundKey, OpeningKey, SealingKey, UnboundKey},
hmac, rand as ring_rand,
signature::{RsaKeyPair, RSA_PSS_SHA256},
};
#[cfg(feature = "logs")]
use router_env::logger;
use rsa::{
pkcs1::DecodeRsaPrivateKey,
pkcs8::{DecodePrivateKey, DecodePublicKey},
signature::Verifier,
traits::PublicKeyParts,
};
use crate::{
consts::{BASE64_ENGINE, BASE64_ENGINE_URL_SAFE_NO_PAD},
errors::{self, CustomResult},
pii::{self, EncryptionStrategy},
};
#[derive(Clone, Debug)]
struct NonceSequence(u128);
impl NonceSequence {
/// Byte index at which sequence number starts in a 16-byte (128-bit) sequence.
/// This byte index considers the big endian order used while encoding and decoding the nonce
/// to/from a 128-bit unsigned integer.
const SEQUENCE_NUMBER_START_INDEX: usize = 4;
/// Generate a random nonce sequence.
fn new() -> Result<Self, ring::error::Unspecified> {
use ring::rand::{SecureRandom, SystemRandom};
let rng = SystemRandom::new();
// 96-bit sequence number, stored in a 128-bit unsigned integer in big-endian order
let mut sequence_number = [0_u8; 128 / 8];
rng.fill(&mut sequence_number[Self::SEQUENCE_NUMBER_START_INDEX..])?;
let sequence_number = u128::from_be_bytes(sequence_number);
Ok(Self(sequence_number))
}
/// Returns the current nonce value as bytes.
fn current(&self) -> [u8; aead::NONCE_LEN] {
let mut nonce = [0_u8; aead::NONCE_LEN];
nonce.copy_from_slice(&self.0.to_be_bytes()[Self::SEQUENCE_NUMBER_START_INDEX..]);
nonce
}
/// Constructs a nonce sequence from bytes
fn from_bytes(bytes: [u8; aead::NONCE_LEN]) -> Self {
let mut sequence_number = [0_u8; 128 / 8];
sequence_number[Self::SEQUENCE_NUMBER_START_INDEX..].copy_from_slice(&bytes);
let sequence_number = u128::from_be_bytes(sequence_number);
Self(sequence_number)
}
}
impl aead::NonceSequence for NonceSequence {
fn advance(&mut self) -> Result<aead::Nonce, ring::error::Unspecified> {
let mut nonce = [0_u8; aead::NONCE_LEN];
nonce.copy_from_slice(&self.0.to_be_bytes()[Self::SEQUENCE_NUMBER_START_INDEX..]);
// Increment sequence number
self.0 = self.0.wrapping_add(1);
// Return previous sequence number as bytes
Ok(aead::Nonce::assume_unique_for_key(nonce))
}
}
/// Trait for cryptographically signing messages
pub trait SignMessage {
/// Takes in a secret and a message and returns the calculated signature as bytes
fn sign_message(
&self,
_secret: &[u8],
_msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError>;
}
/// Trait for cryptographically verifying a message against a signature
pub trait VerifySignature {
/// Takes in a secret, the signature and the message and verifies the message
/// against the signature
fn verify_signature(
&self,
_secret: &[u8],
_signature: &[u8],
_msg: &[u8],
) -> CustomResult<bool, errors::CryptoError>;
}
/// Trait for cryptographically encoding a message
pub trait EncodeMessage {
/// Takes in a secret and the message and encodes it, returning bytes
fn encode_message(
&self,
_secret: &[u8],
_msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError>;
}
/// Trait for cryptographically decoding a message
pub trait DecodeMessage {
/// Takes in a secret, an encoded messages and attempts to decode it, returning bytes
fn decode_message(
&self,
_secret: &[u8],
_msg: Secret<Vec<u8>, EncryptionStrategy>,
) -> CustomResult<Vec<u8>, errors::CryptoError>;
}
/// Represents no cryptographic algorithm.
/// Implements all crypto traits and acts like a Nop
#[derive(Debug)]
pub struct NoAlgorithm;
impl SignMessage for NoAlgorithm {
fn sign_message(
&self,
_secret: &[u8],
_msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
Ok(Vec::new())
}
}
impl VerifySignature for NoAlgorithm {
fn verify_signature(
&self,
_secret: &[u8],
_signature: &[u8],
_msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
Ok(true)
}
}
impl EncodeMessage for NoAlgorithm {
fn encode_message(
&self,
_secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
Ok(msg.to_vec())
}
}
impl DecodeMessage for NoAlgorithm {
fn decode_message(
&self,
_secret: &[u8],
msg: Secret<Vec<u8>, EncryptionStrategy>,
) -> CustomResult<Vec<u8>, errors::CryptoError> {
Ok(msg.expose())
}
}
/// Represents the HMAC-SHA-1 algorithm
#[derive(Debug)]
pub struct HmacSha1;
impl SignMessage for HmacSha1 {
fn sign_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, secret);
Ok(hmac::sign(&key, msg).as_ref().to_vec())
}
}
impl VerifySignature for HmacSha1 {
fn verify_signature(
&self,
secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, secret);
Ok(hmac::verify(&key, msg, signature).is_ok())
}
}
/// Represents the HMAC-SHA-256 algorithm
#[derive(Debug)]
pub struct HmacSha256;
impl SignMessage for HmacSha256 {
fn sign_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA256, secret);
Ok(hmac::sign(&key, msg).as_ref().to_vec())
}
}
impl VerifySignature for HmacSha256 {
fn verify_signature(
&self,
secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA256, secret);
Ok(hmac::verify(&key, msg, signature).is_ok())
}
}
/// Represents the HMAC-SHA-512 algorithm
#[derive(Debug)]
pub struct HmacSha512;
impl SignMessage for HmacSha512 {
fn sign_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA512, secret);
Ok(hmac::sign(&key, msg).as_ref().to_vec())
}
}
impl VerifySignature for HmacSha512 {
fn verify_signature(
&self,
secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA512, secret);
Ok(hmac::verify(&key, msg, signature).is_ok())
}
}
/// Blake3
#[derive(Debug)]
pub struct Blake3(String);
impl Blake3 {
/// Create a new instance of Blake3 with a key
pub fn new(key: impl Into<String>) -> Self {
Self(key.into())
}
}
impl SignMessage for Blake3 {
fn sign_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let key = blake3::derive_key(&self.0, secret);
let output = blake3::keyed_hash(&key, msg).as_bytes().to_vec();
Ok(output)
}
}
impl VerifySignature for Blake3 {
fn verify_signature(
&self,
secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let key = blake3::derive_key(&self.0, secret);
let output = blake3::keyed_hash(&key, msg);
Ok(output.as_bytes() == signature)
}
}
/// Represents the GCM-AES-256 algorithm
#[derive(Debug)]
pub struct GcmAes256;
impl EncodeMessage for GcmAes256 {
fn encode_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let nonce_sequence =
NonceSequence::new().change_context(errors::CryptoError::EncodingFailed)?;
let current_nonce = nonce_sequence.current();
let key = UnboundKey::new(&aead::AES_256_GCM, secret)
.change_context(errors::CryptoError::EncodingFailed)?;
let mut key = SealingKey::new(key, nonce_sequence);
let mut in_out = msg.to_vec();
key.seal_in_place_append_tag(aead::Aad::empty(), &mut in_out)
.change_context(errors::CryptoError::EncodingFailed)?;
in_out.splice(0..0, current_nonce);
Ok(in_out)
}
}
impl DecodeMessage for GcmAes256 {
fn decode_message(
&self,
secret: &[u8],
msg: Secret<Vec<u8>, EncryptionStrategy>,
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let msg = msg.expose();
let key = UnboundKey::new(&aead::AES_256_GCM, secret)
.change_context(errors::CryptoError::DecodingFailed)?;
let nonce_sequence = NonceSequence::from_bytes(
<[u8; aead::NONCE_LEN]>::try_from(
msg.get(..aead::NONCE_LEN)
.ok_or(errors::CryptoError::DecodingFailed)
.attach_printable("Failed to read the nonce form the encrypted ciphertext")?,
)
.change_context(errors::CryptoError::DecodingFailed)?,
);
let mut key = OpeningKey::new(key, nonce_sequence);
let mut binding = msg;
let output = binding.as_mut_slice();
let result = key
.open_within(aead::Aad::empty(), output, aead::NONCE_LEN..)
.change_context(errors::CryptoError::DecodingFailed)?;
Ok(result.to_vec())
}
}
/// Represents the ED25519 signature verification algorithm
#[derive(Debug)]
pub struct Ed25519;
impl Ed25519 {
/// ED25519 algorithm constants
const ED25519_PUBLIC_KEY_LEN: usize = 32;
const ED25519_SIGNATURE_LEN: usize = 64;
/// Validates ED25519 inputs (public key and signature lengths)
fn validate_inputs(
public_key: &[u8],
signature: &[u8],
) -> CustomResult<(), errors::CryptoError> {
// Validate public key length
if public_key.len() != Self::ED25519_PUBLIC_KEY_LEN {
return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!(
"Invalid ED25519 public key length: expected {} bytes, got {}",
Self::ED25519_PUBLIC_KEY_LEN,
public_key.len()
));
}
// Validate signature length
if signature.len() != Self::ED25519_SIGNATURE_LEN {
return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!(
"Invalid ED25519 signature length: expected {} bytes, got {}",
Self::ED25519_SIGNATURE_LEN,
signature.len()
));
}
Ok(())
}
}
impl VerifySignature for Ed25519 {
fn verify_signature(
&self,
public_key: &[u8],
signature: &[u8], // ED25519 signature bytes (must be 64 bytes)
msg: &[u8], // Message that was signed
) -> CustomResult<bool, errors::CryptoError> {
// Validate inputs first
Self::validate_inputs(public_key, signature)?;
// Create unparsed public key
let ring_public_key =
ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, public_key);
// Perform verification
match ring_public_key.verify(msg, signature) {
Ok(()) => Ok(true),
Err(_err) => {
#[cfg(feature = "logs")]
logger::error!("ED25519 signature verification failed: {:?}", _err);
Err(errors::CryptoError::SignatureVerificationFailed)
.attach_printable("ED25519 signature verification failed")
}
}
}
}
impl SignMessage for Ed25519 {
fn sign_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
if secret.len() != 32 {
return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!(
"Invalid ED25519 private key length: expected 32 bytes, got {}",
secret.len()
));
}
let key_pair = ring::signature::Ed25519KeyPair::from_seed_unchecked(secret)
.change_context(errors::CryptoError::MessageSigningFailed)
.attach_printable("Failed to create ED25519 key pair from seed")?;
let signature = key_pair.sign(msg);
Ok(signature.as_ref().to_vec())
}
}
/// Secure Hash Algorithm 512
#[derive(Debug)]
pub struct Sha512;
/// Secure Hash Algorithm 256
#[derive(Debug)]
pub struct Sha256;
/// Trait for generating a digest for SHA
pub trait GenerateDigest {
/// takes a message and creates a digest for it
fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError>;
}
impl GenerateDigest for Sha512 {
fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> {
let digest = ring::digest::digest(&ring::digest::SHA512, message);
Ok(digest.as_ref().to_vec())
}
}
impl VerifySignature for Sha512 {
fn verify_signature(
&self,
_secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let msg_str = std::str::from_utf8(msg)
.change_context(errors::CryptoError::EncodingFailed)?
.to_owned();
let hashed_digest = hex::encode(
Self.generate_digest(msg_str.as_bytes())
.change_context(errors::CryptoError::SignatureVerificationFailed)?,
);
let hashed_digest_into_bytes = hashed_digest.into_bytes();
Ok(hashed_digest_into_bytes == signature)
}
}
/// MD5 hash function
#[derive(Debug)]
pub struct Md5;
impl GenerateDigest for Md5 {
fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> {
let digest = md5::compute(message);
Ok(digest.as_ref().to_vec())
}
}
impl VerifySignature for Md5 {
fn verify_signature(
&self,
_secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let hashed_digest = Self
.generate_digest(msg)
.change_context(errors::CryptoError::SignatureVerificationFailed)?;
Ok(hashed_digest == signature)
}
}
impl GenerateDigest for Sha256 {
fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> {
let digest = ring::digest::digest(&ring::digest::SHA256, message);
Ok(digest.as_ref().to_vec())
}
}
impl VerifySignature for Sha256 {
fn verify_signature(
&self,
_secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let hashed_digest = Self
.generate_digest(msg)
.change_context(errors::CryptoError::SignatureVerificationFailed)?;
let hashed_digest_into_bytes = hashed_digest.as_slice();
Ok(hashed_digest_into_bytes == signature)
}
}
/// Secure Hash Algorithm 256 with RSA public-key cryptosystem
#[derive(Debug)]
pub struct RsaSha256;
impl VerifySignature for RsaSha256 {
fn verify_signature(
&self,
secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
// create verifying key
let decoded_public_key = BASE64_ENGINE
.decode(secret)
.change_context(errors::CryptoError::SignatureVerificationFailed)
.attach_printable("base64 decoding failed")?;
let string_public_key = String::from_utf8(decoded_public_key)
.change_context(errors::CryptoError::SignatureVerificationFailed)
.attach_printable("utf8 to string parsing failed")?;
let rsa_public_key = rsa::RsaPublicKey::from_public_key_pem(&string_public_key)
.change_context(errors::CryptoError::SignatureVerificationFailed)
.attach_printable("rsa public key transformation failed")?;
let verifying_key = rsa::pkcs1v15::VerifyingKey::<rsa::sha2::Sha256>::new(rsa_public_key);
// transfrom the signature
let decoded_signature = BASE64_ENGINE
.decode(signature)
.change_context(errors::CryptoError::SignatureVerificationFailed)
.attach_printable("base64 decoding failed")?;
let rsa_signature = rsa::pkcs1v15::Signature::try_from(&decoded_signature[..])
.change_context(errors::CryptoError::SignatureVerificationFailed)
.attach_printable("rsa signature transformation failed")?;
// signature verification
verifying_key
.verify(msg, &rsa_signature)
.map(|_| true)
.change_context(errors::CryptoError::SignatureVerificationFailed)
.attach_printable("signature verification step failed")
}
}
/// TripleDesEde3 hash function
#[derive(Debug)]
#[cfg(feature = "crypto_openssl")]
pub struct TripleDesEde3CBC {
padding: common_enums::CryptoPadding,
iv: Vec<u8>,
}
#[cfg(feature = "crypto_openssl")]
impl TripleDesEde3CBC {
const TRIPLE_DES_KEY_LENGTH: usize = 24;
/// Initialization Vector (IV) length for TripleDesEde3
pub const TRIPLE_DES_IV_LENGTH: usize = 8;
/// Constructor function to be used by the encryptor and decryptor to generate the data type
pub fn new(
padding: Option<common_enums::CryptoPadding>,
iv: Vec<u8>,
) -> Result<Self, errors::CryptoError> {
if iv.len() != Self::TRIPLE_DES_IV_LENGTH {
Err(errors::CryptoError::InvalidIvLength)?
};
let padding = padding.unwrap_or(common_enums::CryptoPadding::PKCS7);
Ok(Self { iv, padding })
}
}
#[cfg(feature = "crypto_openssl")]
impl EncodeMessage for TripleDesEde3CBC {
fn encode_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
if secret.len() != Self::TRIPLE_DES_KEY_LENGTH {
Err(errors::CryptoError::InvalidKeyLength)?
}
let mut buffer = msg.to_vec();
if let common_enums::CryptoPadding::ZeroPadding = self.padding {
let pad_len = Self::TRIPLE_DES_IV_LENGTH - (buffer.len() % Self::TRIPLE_DES_IV_LENGTH);
if pad_len != Self::TRIPLE_DES_IV_LENGTH {
buffer.extend(vec![0u8; pad_len]);
}
};
let cipher = openssl::symm::Cipher::des_ede3_cbc();
openssl::symm::encrypt(cipher, secret, Some(&self.iv), &buffer)
.change_context(errors::CryptoError::EncodingFailed)
}
}
/// Generate a random string using a cryptographically secure pseudo-random number generator
/// (CSPRNG). Typically used for generating (readable) keys and passwords.
#[inline]
pub fn generate_cryptographically_secure_random_string(length: usize) -> String {
use rand::distributions::DistString;
rand::distributions::Alphanumeric.sample_string(&mut rand::rngs::OsRng, length)
}
/// Generate an array of random bytes using a cryptographically secure pseudo-random number
/// generator (CSPRNG). Typically used for generating keys.
#[inline]
pub fn generate_cryptographically_secure_random_bytes<const N: usize>() -> [u8; N] {
use rand::RngCore;
let mut bytes = [0; N];
rand::rngs::OsRng.fill_bytes(&mut bytes);
bytes
}
/// A wrapper type to store the encrypted data for sensitive pii domain data types
#[derive(Debug, Clone)]
pub struct Encryptable<T: Clone> {
inner: T,
encrypted: Secret<Vec<u8>, EncryptionStrategy>,
}
impl<T: Clone, S: masking::Strategy<T>> Encryptable<Secret<T, S>> {
/// constructor function to be used by the encryptor and decryptor to generate the data type
pub fn new(
masked_data: Secret<T, S>,
encrypted_data: Secret<Vec<u8>, EncryptionStrategy>,
) -> Self {
Self {
inner: masked_data,
encrypted: encrypted_data,
}
}
}
impl<T: Clone> Encryptable<T> {
/// Get the inner data while consuming self
#[inline]
pub fn into_inner(self) -> T {
self.inner
}
/// Get the reference to inner value
#[inline]
pub fn get_inner(&self) -> &T {
&self.inner
}
/// Get the inner encrypted data while consuming self
#[inline]
pub fn into_encrypted(self) -> Secret<Vec<u8>, EncryptionStrategy> {
self.encrypted
}
/// Deserialize inner value and return new Encryptable object
pub fn deserialize_inner_value<U, F>(
self,
f: F,
) -> CustomResult<Encryptable<U>, errors::ParsingError>
where
F: FnOnce(T) -> CustomResult<U, errors::ParsingError>,
U: Clone,
{
let inner = self.inner;
let encrypted = self.encrypted;
let inner = f(inner)?;
Ok(Encryptable { inner, encrypted })
}
/// consume self and modify the inner value
pub fn map<U: Clone>(self, f: impl FnOnce(T) -> U) -> Encryptable<U> {
let encrypted_data = self.encrypted;
let masked_data = f(self.inner);
Encryptable {
inner: masked_data,
encrypted: encrypted_data,
}
}
}
impl<T: Clone> Deref for Encryptable<Secret<T>> {
type Target = Secret<T>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T: Clone> masking::Serialize for Encryptable<T>
where
T: masking::Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.inner.serialize(serializer)
}
}
impl<T: Clone> PartialEq for Encryptable<T>
where
T: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.inner.eq(&other.inner)
}
}
/// Type alias for `Option<Encryptable<Secret<String>>>`
pub type OptionalEncryptableSecretString = Option<Encryptable<Secret<String>>>;
/// Type alias for `Option<Encryptable<Secret<String>>>` used for `name` field
pub type OptionalEncryptableName = Option<Encryptable<Secret<String>>>;
/// Type alias for `Option<Encryptable<Secret<String>>>` used for `email` field
pub type OptionalEncryptableEmail = Option<Encryptable<Secret<String, pii::EmailStrategy>>>;
/// Type alias for `Option<Encryptable<Secret<String>>>` used for `phone` field
pub type OptionalEncryptablePhone = Option<Encryptable<Secret<String>>>;
/// Type alias for `Option<Encryptable<Secret<serde_json::Value>>>`
pub type OptionalEncryptableValue = Option<Encryptable<Secret<serde_json::Value>>>;
/// Type alias for `Option<Secret<serde_json::Value>>`
pub type OptionalSecretValue = Option<Secret<serde_json::Value>>;
/// Type alias for `Encryptable<Secret<String>>` used for `name` field
pub type EncryptableName = Encryptable<Secret<String>>;
/// Type alias for `Encryptable<Secret<String>>` used for `email` field
pub type EncryptableEmail = Encryptable<Secret<String, pii::EmailStrategy>>;
/// Extract RSA public key components (n, e) from a private key PEM for JWKS
/// Returns base64url-encoded modulus and exponent
pub fn extract_rsa_public_key_components(
private_key_pem: &Secret<String>,
) -> CustomResult<(String, String), errors::CryptoError> {
let pem_str = private_key_pem.peek();
let parsed_pem = pem::parse(pem_str).change_context(errors::CryptoError::EncodingFailed)?;
let private_key = match parsed_pem.tag() {
"PRIVATE KEY" => rsa::RsaPrivateKey::from_pkcs8_der(parsed_pem.contents())
.change_context(errors::CryptoError::InvalidKeyLength),
"RSA PRIVATE KEY" => rsa::RsaPrivateKey::from_pkcs1_der(parsed_pem.contents())
.change_context(errors::CryptoError::InvalidKeyLength),
tag => Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!(
"Unexpected PEM tag: {tag}. Expected 'PRIVATE KEY' or 'RSA PRIVATE KEY'"
)),
}
.attach_printable("Failed to extract RSA public key components from private key")?;
let public_key = private_key.to_public_key();
let n_bytes = public_key.n().to_bytes_be();
let e_bytes = public_key.e().to_bytes_be();
let n_b64 = BASE64_ENGINE_URL_SAFE_NO_PAD.encode(n_bytes);
let e_b64 = BASE64_ENGINE_URL_SAFE_NO_PAD.encode(e_bytes);
Ok((n_b64, e_b64))
}
/// Represents the RSA-PSS-SHA256 signing algorithm
#[derive(Debug)]
pub struct RsaPssSha256;
impl SignMessage for RsaPssSha256 {
fn sign_message(
&self,
private_key_pem_bytes: &[u8],
msg_to_sign: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let parsed_pem = pem::parse(private_key_pem_bytes)
.change_context(errors::CryptoError::EncodingFailed)
.attach_printable("Failed to parse PEM string")?;
let key_pair = match parsed_pem.tag() {
"PRIVATE KEY" => RsaKeyPair::from_pkcs8(parsed_pem.contents())
.change_context(errors::CryptoError::InvalidKeyLength)
.attach_printable("Failed to parse PKCS#8 DER with ring"),
"RSA PRIVATE KEY" => RsaKeyPair::from_der(parsed_pem.contents())
.change_context(errors::CryptoError::InvalidKeyLength)
.attach_printable("Failed to parse PKCS#1 DER (using from_der) with ring"),
tag => Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!(
"Unexpected PEM tag: {tag}. Expected 'PRIVATE KEY' or 'RSA PRIVATE KEY'",
)),
}?;
let rng = ring_rand::SystemRandom::new();
let signature_len = key_pair.public().modulus_len();
let mut signature_bytes = vec![0; signature_len];
key_pair
.sign(&RSA_PSS_SHA256, &rng, msg_to_sign, &mut signature_bytes)
.change_context(errors::CryptoError::EncodingFailed)
.attach_printable("Failed to sign data with ring")?;
Ok(signature_bytes)
}
}
#[cfg(test)]
mod crypto_tests {
use super::{DecodeMessage, EncodeMessage, SignMessage, VerifySignature};
use crate::crypto::GenerateDigest;
#[test]
fn test_hmac_sha256_sign_message() {
let message = r#"{"type":"payment_intent"}"#.as_bytes();
let secret = "hmac_secret_1234".as_bytes();
let right_signature =
hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823e")
.expect("Right signature decoding");
let signature = super::HmacSha256
.sign_message(secret, message)
.expect("Signature");
assert_eq!(signature, right_signature);
}
#[test]
fn test_hmac_sha256_verify_signature() {
let right_signature =
hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823e")
.expect("Right signature decoding");
let wrong_signature =
hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823f")
.expect("Wrong signature decoding");
let secret = "hmac_secret_1234".as_bytes();
let data = r#"{"type":"payment_intent"}"#.as_bytes();
let right_verified = super::HmacSha256
.verify_signature(secret, &right_signature, data)
.expect("Right signature verification result");
assert!(right_verified);
let wrong_verified = super::HmacSha256
.verify_signature(secret, &wrong_signature, data)
.expect("Wrong signature verification result");
assert!(!wrong_verified);
}
#[test]
fn test_sha256_verify_signature() {
let right_signature =
hex::decode("123250a72f4e961f31661dbcee0fec0f4714715dc5ae1b573f908a0a5381ddba")
.expect("Right signature decoding");
let wrong_signature =
hex::decode("123250a72f4e961f31661dbcee0fec0f4714715dc5ae1b573f908a0a5381ddbb")
.expect("Wrong signature decoding");
let secret = "".as_bytes();
let data = r#"AJHFH9349JASFJHADJ9834115USD2020-11-13.13:22:34711000000021406655APPROVED12345product_id"#.as_bytes();
let right_verified = super::Sha256
.verify_signature(secret, &right_signature, data)
.expect("Right signature verification result");
assert!(right_verified);
let wrong_verified = super::Sha256
.verify_signature(secret, &wrong_signature, data)
.expect("Wrong signature verification result");
assert!(!wrong_verified);
}
#[test]
fn test_hmac_sha512_sign_message() {
let message = r#"{"type":"payment_intent"}"#.as_bytes();
let secret = "hmac_secret_1234".as_bytes();
let right_signature = hex::decode("38b0bc1ea66b14793e39cd58e93d37b799a507442d0dd8d37443fa95dec58e57da6db4742636fea31201c48e57a66e73a308a2e5a5c6bb831e4e39fe2227c00f")
.expect("signature decoding");
let signature = super::HmacSha512
.sign_message(secret, message)
.expect("Signature");
assert_eq!(signature, right_signature);
}
#[test]
fn test_hmac_sha512_verify_signature() {
let right_signature = hex::decode("38b0bc1ea66b14793e39cd58e93d37b799a507442d0dd8d37443fa95dec58e57da6db4742636fea31201c48e57a66e73a308a2e5a5c6bb831e4e39fe2227c00f")
.expect("signature decoding");
let wrong_signature =
hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823f")
.expect("Wrong signature decoding");
let secret = "hmac_secret_1234".as_bytes();
let data = r#"{"type":"payment_intent"}"#.as_bytes();
let right_verified = super::HmacSha512
.verify_signature(secret, &right_signature, data)
.expect("Right signature verification result");
assert!(right_verified);
let wrong_verified = super::HmacSha256
.verify_signature(secret, &wrong_signature, data)
.expect("Wrong signature verification result");
assert!(!wrong_verified);
}
#[test]
fn test_gcm_aes_256_encode_message() {
let message = r#"{"type":"PAYMENT"}"#.as_bytes();
let secret =
hex::decode("000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f")
.expect("Secret decoding");
let algorithm = super::GcmAes256;
let encoded_message = algorithm
.encode_message(&secret, message)
.expect("Encoded message and tag");
assert_eq!(
algorithm
.decode_message(&secret, encoded_message.into())
.expect("Decode Failed"),
message
);
}
#[test]
fn test_gcm_aes_256_decode_message() {
// Inputs taken from AES GCM test vectors provided by NIST
// https://github.com/briansmith/ring/blob/95948b3977013aed16db92ae32e6b8384496a740/tests/aead_aes_256_gcm_tests.txt#L447-L452
let right_secret =
hex::decode("feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308")
.expect("Secret decoding");
let wrong_secret =
hex::decode("feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308309")
.expect("Secret decoding");
let message =
// The three parts of the message are the nonce, ciphertext and tag from the test vector
hex::decode(
"cafebabefacedbaddecaf888\
522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662898015ad\
b094dac5d93471bdec1a502270e3cc6c"
).expect("Message decoding");
let algorithm = super::GcmAes256;
let decoded = algorithm
.decode_message(&right_secret, message.clone().into())
.expect("Decoded message");
assert_eq!(
decoded,
hex::decode("d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255")
.expect("Decoded plaintext message")
);
let err_decoded = algorithm.decode_message(&wrong_secret, message.into());
assert!(err_decoded.is_err());
}
#[test]
fn test_md5_digest() {
let message = "abcdefghijklmnopqrstuvwxyz".as_bytes();
assert_eq!(
format!(
"{}",
hex::encode(super::Md5.generate_digest(message).expect("Digest"))
),
"c3fcd3d76192e4007dfb496cca67e13b"
);
}
#[test]
fn test_md5_verify_signature() {
let right_signature =
hex::decode("c3fcd3d76192e4007dfb496cca67e13b").expect("signature decoding");
let wrong_signature =
hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823f")
.expect("Wrong signature decoding");
let secret = "".as_bytes();
let data = "abcdefghijklmnopqrstuvwxyz".as_bytes();
let right_verified = super::Md5
.verify_signature(secret, &right_signature, data)
.expect("Right signature verification result");
assert!(right_verified);
let wrong_verified = super::Md5
.verify_signature(secret, &wrong_signature, data)
.expect("Wrong signature verification result");
assert!(!wrong_verified);
}
use ring::signature::{UnparsedPublicKey, RSA_PSS_2048_8192_SHA256};
#[test]
fn test_rsa_pss_sha256_verify_signature() {
let signer = crate::crypto::RsaPssSha256;
let message = b"abcdefghijklmnopqrstuvwxyz";
let private_key_pem_bytes =
std::fs::read("../../private_key.pem").expect("Failed to read private key");
let parsed_pem = pem::parse(&private_key_pem_bytes).expect("Failed to parse PEM");
let private_key_der = parsed_pem.contents();
let signature = signer
.sign_message(&private_key_pem_bytes, message)
.expect("Signing failed");
let key_pair = crate::crypto::RsaKeyPair::from_pkcs8(private_key_der)
.expect("Failed to parse DER key");
let public_key_der = key_pair.public().as_ref().to_vec();
let public_key = UnparsedPublicKey::new(&RSA_PSS_2048_8192_SHA256, &public_key_der);
assert!(
public_key.verify(message, &signature).is_ok(),
"Right signature should verify"
);
let mut wrong_signature = signature.clone();
if let Some(byte) = wrong_signature.first_mut() {
*byte ^= 0xFF;
}
assert!(
public_key.verify(message, &wrong_signature).is_err(),
"Wrong signature should not verify"
);
}
#[test]
fn test_rsasha256_verify_signature() {
use base64::Engine;
use rand::rngs::OsRng;
use rsa::{
pkcs8::EncodePublicKey,
signature::{RandomizedSigner, SignatureEncoding},
};
use crate::consts::BASE64_ENGINE;
let mut rng = OsRng;
let bits = 2048;
let private_key = rsa::RsaPrivateKey::new(&mut rng, bits).expect("keygen failed");
let signing_key = rsa::pkcs1v15::SigningKey::<rsa::sha2::Sha256>::new(private_key.clone());
let message = "{ This is a test message :) }".as_bytes();
let signature = signing_key.sign_with_rng(&mut rng, message);
let encoded_signature = BASE64_ENGINE.encode(signature.to_bytes());
let rsa_public_key = private_key.to_public_key();
let pem_format_public_key = rsa_public_key
.to_public_key_pem(rsa::pkcs8::LineEnding::LF)
.expect("transformation failed");
let encoded_pub_key = BASE64_ENGINE.encode(&pem_format_public_key[..]);
let right_verified = super::RsaSha256
.verify_signature(
encoded_pub_key.as_bytes(),
encoded_signature.as_bytes(),
message,
)
.expect("Right signature verification result");
assert!(right_verified);
}
}
|
crates__common_utils__src__ext_traits.rs
|
//! This module holds traits for extending functionalities for existing datatypes
//! & inbuilt datatypes.
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret, Strategy};
use quick_xml::de;
#[cfg(all(feature = "logs", feature = "async_ext"))]
use router_env::logger;
use serde::{Deserialize, Serialize};
use crate::{
crypto,
errors::{self, CustomResult},
fp_utils::when,
};
/// Encode interface
/// An interface for performing type conversions and serialization
pub trait Encode<'e>
where
Self: 'e + std::fmt::Debug,
{
// If needed get type information/custom error implementation.
///
/// Converting `Self` into an intermediate representation `<P>`
/// and then performing encoding operation using the `Serialize` trait from `serde`
/// Specifically to convert into json, by using `serde_json`
fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize;
/// Converting `Self` into an intermediate representation `<P>`
/// and then performing encoding operation using the `Serialize` trait from `serde`
/// Specifically, to convert into urlencoded, by using `serde_urlencoded`
fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize;
/// Functionality, for specifically encoding `Self` into `String`
/// after serialization by using `serde::Serialize`
fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize;
/// Functionality, for specifically encoding `Self` into `String`
/// after serialization by using `serde::Serialize`
/// specifically, to convert into JSON `String`.
fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize;
/// Functionality, for specifically encoding `Self` into `String`
/// after serialization by using `serde::Serialize`
/// specifically, to convert into XML `String`.
fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize;
/// Functionality, for specifically encoding `Self` into `serde_json::Value`
/// after serialization by using `serde::Serialize`
fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError>
where
Self: Serialize;
/// Functionality, for specifically encoding `Self` into `Vec<u8>`
/// after serialization by using `serde::Serialize`
fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError>
where
Self: Serialize;
}
impl<'e, A> Encode<'e> for A
where
Self: 'e + std::fmt::Debug,
{
fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize,
{
serde_json::to_string(
&P::try_from(self).change_context(errors::ParsingError::UnknownError)?,
)
.change_context(errors::ParsingError::EncodeError("string"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize,
{
serde_urlencoded::to_string(
&P::try_from(self).change_context(errors::ParsingError::UnknownError)?,
)
.change_context(errors::ParsingError::EncodeError("url-encoded"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
// Check without two functions can we combine this
fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize,
{
serde_urlencoded::to_string(self)
.change_context(errors::ParsingError::EncodeError("url-encoded"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize,
{
serde_json::to_string(self)
.change_context(errors::ParsingError::EncodeError("json"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize,
{
quick_xml::se::to_string(self)
.change_context(errors::ParsingError::EncodeError("xml"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError>
where
Self: Serialize,
{
serde_json::to_value(self)
.change_context(errors::ParsingError::EncodeError("json-value"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a value"))
}
fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError>
where
Self: Serialize,
{
serde_json::to_vec(self)
.change_context(errors::ParsingError::EncodeError("byte-vec"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a value"))
}
}
/// Extending functionalities of `bytes::Bytes`
pub trait BytesExt {
/// Convert `bytes::Bytes` into type `<T>` using `serde::Deserialize`
fn parse_struct<'de, T>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>;
}
impl BytesExt for bytes::Bytes {
fn parse_struct<'de, T>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>,
{
use bytes::Buf;
serde_json::from_slice::<T>(self.chunk())
.change_context(errors::ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| {
let variable_type = std::any::type_name::<T>();
let value = serde_json::from_slice::<serde_json::Value>(self)
.unwrap_or_else(|_| serde_json::Value::String(String::new()));
format!(
"Unable to parse {variable_type} from bytes {:?}",
Secret::<_, masking::JsonMaskStrategy>::new(value)
)
})
}
}
/// Extending functionalities of `[u8]` for performing parsing
pub trait ByteSliceExt {
/// Convert `[u8]` into type `<T>` by using `serde::Deserialize`
fn parse_struct<'de, T>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>;
}
impl ByteSliceExt for [u8] {
#[track_caller]
fn parse_struct<'de, T>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>,
{
serde_json::from_slice(self)
.change_context(errors::ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| {
let value = serde_json::from_slice::<serde_json::Value>(self)
.unwrap_or_else(|_| serde_json::Value::String(String::new()));
format!(
"Unable to parse {type_name} from &[u8] {:?}",
Secret::<_, masking::JsonMaskStrategy>::new(value)
)
})
}
}
/// Extending functionalities of `serde_json::Value` for performing parsing
pub trait ValueExt {
/// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize`
fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: serde::de::DeserializeOwned;
}
impl ValueExt for serde_json::Value {
fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: serde::de::DeserializeOwned,
{
serde_json::from_value::<T>(self.clone())
.change_context(errors::ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| {
format!(
"Unable to parse {type_name} from serde_json::Value: {:?}",
// Required to prevent logging sensitive data in case of deserialization failure
Secret::<_, masking::JsonMaskStrategy>::new(self)
)
})
}
}
impl<MaskingStrategy> ValueExt for Secret<serde_json::Value, MaskingStrategy>
where
MaskingStrategy: Strategy<serde_json::Value>,
{
fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: serde::de::DeserializeOwned,
{
self.expose().parse_value(type_name)
}
}
impl<E: ValueExt + Clone> ValueExt for crypto::Encryptable<E> {
fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: serde::de::DeserializeOwned,
{
self.into_inner().parse_value(type_name)
}
}
/// Extending functionalities of `String` for performing parsing
pub trait StringExt<T> {
/// Convert `String` into type `<T>` (which being an `enum`)
fn parse_enum(self, enum_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: std::str::FromStr,
// Requirement for converting the `Err` variant of `FromStr` to `Report<Err>`
<T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static;
/// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize`
fn parse_struct<'de>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>;
}
impl<T> StringExt<T> for String {
fn parse_enum(self, enum_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: std::str::FromStr,
<T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static,
{
T::from_str(&self)
.change_context(errors::ParsingError::EnumParseFailure(enum_name))
.attach_printable_lazy(|| format!("Invalid enum variant {self:?} for enum {enum_name}"))
}
fn parse_struct<'de>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>,
{
serde_json::from_str::<T>(self)
.change_context(errors::ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| {
format!(
"Unable to parse {type_name} from string {:?}",
Secret::<_, masking::JsonMaskStrategy>::new(serde_json::Value::String(
self.clone()
))
)
})
}
}
/// Extending functionalities of Wrapper types for idiomatic
#[cfg(feature = "async_ext")]
#[cfg_attr(feature = "async_ext", async_trait::async_trait)]
pub trait AsyncExt<A> {
/// Output type of the map function
type WrappedSelf<T>;
/// Extending map by allowing functions which are async
async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = B> + Send;
/// Extending the `and_then` by allowing functions which are async
async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send;
/// Extending `unwrap_or_else` to allow async fallback
async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = A> + Send;
/// Extending `or_else` to allow async fallback that returns Self::WrappedSelf<A>
async fn async_or_else<F, Fut>(self, func: F) -> Self::WrappedSelf<A>
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<A>> + Send;
}
#[cfg(feature = "async_ext")]
#[cfg_attr(feature = "async_ext", async_trait::async_trait)]
impl<A: Send, E: Send + std::fmt::Debug> AsyncExt<A> for Result<A, E> {
type WrappedSelf<T> = Result<T, E>;
async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send,
{
match self {
Ok(a) => func(a).await,
Err(err) => Err(err),
}
}
async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = B> + Send,
{
match self {
Ok(a) => Ok(func(a).await),
Err(err) => Err(err),
}
}
async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = A> + Send,
{
match self {
Ok(a) => a,
Err(_err) => {
#[cfg(feature = "logs")]
logger::error!("Error: {:?}", _err);
func().await
}
}
}
async fn async_or_else<F, Fut>(self, func: F) -> Self::WrappedSelf<A>
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<A>> + Send,
{
match self {
Ok(a) => Ok(a),
Err(_err) => {
#[cfg(feature = "logs")]
logger::error!("Error: {:?}", _err);
func().await
}
}
}
}
#[cfg(feature = "async_ext")]
#[cfg_attr(feature = "async_ext", async_trait::async_trait)]
impl<A: Send> AsyncExt<A> for Option<A> {
type WrappedSelf<T> = Option<T>;
async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send,
{
match self {
Some(a) => func(a).await,
None => None,
}
}
async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = B> + Send,
{
match self {
Some(a) => Some(func(a).await),
None => None,
}
}
async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = A> + Send,
{
match self {
Some(a) => a,
None => func().await,
}
}
async fn async_or_else<F, Fut>(self, func: F) -> Self::WrappedSelf<A>
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<A>> + Send,
{
match self {
Some(a) => Some(a),
None => func().await,
}
}
}
/// Extension trait for validating application configuration. This trait provides utilities to
/// check whether the value is either the default value or is empty.
pub trait ConfigExt {
/// Returns whether the value of `self` is the default value for `Self`.
fn is_default(&self) -> bool
where
Self: Default + PartialEq<Self>,
{
*self == Self::default()
}
/// Returns whether the value of `self` is empty after trimming whitespace on both left and
/// right ends.
fn is_empty_after_trim(&self) -> bool;
/// Returns whether the value of `self` is the default value for `Self` or empty after trimming
/// whitespace on both left and right ends.
fn is_default_or_empty(&self) -> bool
where
Self: Default + PartialEq<Self>,
{
self.is_default() || self.is_empty_after_trim()
}
}
impl ConfigExt for u32 {
fn is_empty_after_trim(&self) -> bool {
false
}
}
impl ConfigExt for String {
fn is_empty_after_trim(&self) -> bool {
self.trim().is_empty()
}
}
impl<T, U> ConfigExt for Secret<T, U>
where
T: ConfigExt + Default + PartialEq<T>,
U: Strategy<T>,
{
fn is_default(&self) -> bool
where
T: Default + PartialEq<T>,
{
*self.peek() == T::default()
}
fn is_empty_after_trim(&self) -> bool {
self.peek().is_empty_after_trim()
}
fn is_default_or_empty(&self) -> bool
where
T: Default + PartialEq<T>,
{
self.peek().is_default() || self.peek().is_empty_after_trim()
}
}
/// Extension trait for deserializing XML strings using `quick-xml` crate
pub trait XmlExt {
/// Deserialize an XML string into the specified type `<T>`.
fn parse_xml<T>(self) -> Result<T, de::DeError>
where
T: serde::de::DeserializeOwned;
}
impl XmlExt for &str {
fn parse_xml<T>(self) -> Result<T, de::DeError>
where
T: serde::de::DeserializeOwned,
{
de::from_str(self)
}
}
/// Extension trait for Option to validate missing fields
pub trait OptionExt<T> {
/// check if the current option is Some
fn check_value_present(
&self,
field_name: &'static str,
) -> CustomResult<(), errors::ValidationError>;
/// Throw missing required field error when the value is None
fn get_required_value(
self,
field_name: &'static str,
) -> CustomResult<T, errors::ValidationError>;
/// Try parsing the option as Enum
fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError>
where
T: AsRef<str>,
E: std::str::FromStr,
// Requirement for converting the `Err` variant of `FromStr` to `Report<Err>`
<E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static;
/// Try parsing the option as Type
fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError>
where
T: ValueExt,
U: serde::de::DeserializeOwned;
/// update option value
fn update_value(&mut self, value: Option<T>);
}
impl<T> OptionExt<T> for Option<T>
where
T: std::fmt::Debug,
{
#[track_caller]
fn check_value_present(
&self,
field_name: &'static str,
) -> CustomResult<(), errors::ValidationError> {
when(self.is_none(), || {
Err(errors::ValidationError::MissingRequiredField {
field_name: field_name.to_string(),
})
.attach_printable(format!("Missing required field {field_name} in {self:?}"))
})
}
// This will allow the error message that was generated in this function to point to the call site
#[track_caller]
fn get_required_value(
self,
field_name: &'static str,
) -> CustomResult<T, errors::ValidationError> {
match self {
Some(v) => Ok(v),
None => Err(errors::ValidationError::MissingRequiredField {
field_name: field_name.to_string(),
})
.attach_printable(format!("Missing required field {field_name} in {self:?}")),
}
}
#[track_caller]
fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError>
where
T: AsRef<str>,
E: std::str::FromStr,
<E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static,
{
let value = self
.get_required_value(enum_name)
.change_context(errors::ParsingError::UnknownError)?;
E::from_str(value.as_ref())
.change_context(errors::ParsingError::UnknownError)
.attach_printable_lazy(|| format!("Invalid {{ {enum_name}: {value:?} }} "))
}
#[track_caller]
fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError>
where
T: ValueExt,
U: serde::de::DeserializeOwned,
{
let value = self
.get_required_value(type_name)
.change_context(errors::ParsingError::UnknownError)?;
value.parse_value(type_name)
}
fn update_value(&mut self, value: Self) {
if let Some(a) = value {
*self = Some(a)
}
}
}
|
crates__common_utils__src__macros.rs
|
//! Utility macros
#[allow(missing_docs)]
#[macro_export]
macro_rules! newtype_impl {
($is_pub:vis, $name:ident, $ty_path:path) => {
impl core::ops::Deref for $name {
type Target = $ty_path;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for $name {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<$ty_path> for $name {
fn from(ty: $ty_path) -> Self {
Self(ty)
}
}
impl $name {
pub fn into_inner(self) -> $ty_path {
self.0
}
}
};
}
#[allow(missing_docs)]
#[macro_export]
macro_rules! newtype {
($is_pub:vis $name:ident = $ty_path:path) => {
$is_pub struct $name(pub $ty_path);
$crate::newtype_impl!($is_pub, $name, $ty_path);
};
($is_pub:vis $name:ident = $ty_path:path, derives = ($($trt:path),*)) => {
#[derive($($trt),*)]
$is_pub struct $name(pub $ty_path);
$crate::newtype_impl!($is_pub, $name, $ty_path);
};
}
/// Use this to ensure that the corresponding
/// openapi route has been implemented in the openapi crate
#[macro_export]
macro_rules! openapi_route {
($route_name: ident) => {{
#[cfg(feature = "openapi")]
use openapi::routes::$route_name as _;
$route_name
}};
}
#[allow(missing_docs)]
#[macro_export]
macro_rules! fallback_reverse_lookup_not_found {
($a:expr,$b:expr) => {
match $a {
Ok(res) => res,
Err(err) => {
router_env::logger::error!(reverse_lookup_fallback = ?err);
match err.current_context() {
errors::StorageError::ValueNotFound(_) => return $b,
errors::StorageError::DatabaseError(data_err) => {
match data_err.current_context() {
diesel_models::errors::DatabaseError::NotFound => return $b,
_ => return Err(err)
}
}
_=> return Err(err)
}
}
};
};
}
/// Collects names of all optional fields that are `None`.
/// This is typically useful for constructing error messages including a list of all missing fields.
#[macro_export]
macro_rules! collect_missing_value_keys {
[$(($key:literal, $option:expr)),+] => {
{
let mut keys: Vec<&'static str> = Vec::new();
$(
if $option.is_none() {
keys.push($key);
}
)*
keys
}
};
}
/// Implements the `ToSql` and `FromSql` traits on a type to allow it to be serialized/deserialized
/// to/from JSON data in the database.
#[macro_export]
macro_rules! impl_to_sql_from_sql_json {
($type:ty, $diesel_type:ty) => {
#[allow(unused_qualifications)]
impl diesel::serialize::ToSql<$diesel_type, diesel::pg::Pg> for $type {
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>,
) -> diesel::serialize::Result {
let value = serde_json::to_value(self)?;
// the function `reborrow` only works in case of `Pg` backend. But, in case of other backends
// please refer to the diesel migration blog:
// https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations
<serde_json::Value as diesel::serialize::ToSql<
$diesel_type,
diesel::pg::Pg,
>>::to_sql(&value, &mut out.reborrow())
}
}
#[allow(unused_qualifications)]
impl diesel::deserialize::FromSql<$diesel_type, diesel::pg::Pg> for $type {
fn from_sql(
bytes: <diesel::pg::Pg as diesel::backend::Backend>::RawValue<'_>,
) -> diesel::deserialize::Result<Self> {
let value = <serde_json::Value as diesel::deserialize::FromSql<
$diesel_type,
diesel::pg::Pg,
>>::from_sql(bytes)?;
Ok(serde_json::from_value(value)?)
}
}
};
($type: ty) => {
$crate::impl_to_sql_from_sql_json!($type, diesel::sql_types::Json);
$crate::impl_to_sql_from_sql_json!($type, diesel::sql_types::Jsonb);
};
}
mod id_type {
/// Defines an ID type.
#[macro_export]
macro_rules! id_type {
($type:ident, $doc:literal, $diesel_type:ty, $max_length:expr, $min_length:expr) => {
#[doc = $doc]
#[derive(
Clone,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
diesel::expression::AsExpression,
utoipa::ToSchema,
)]
#[diesel(sql_type = $diesel_type)]
#[schema(value_type = String)]
pub struct $type($crate::id_type::LengthId<$max_length, $min_length>);
};
($type:ident, $doc:literal) => {
$crate::id_type!(
$type,
$doc,
diesel::sql_types::Text,
{ $crate::consts::MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH },
{ $crate::consts::MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH }
);
};
}
/// Defines a Global Id type
#[cfg(feature = "v2")]
#[macro_export]
macro_rules! global_id_type {
($type:ident, $doc:literal) => {
#[doc = $doc]
#[derive(
Debug,
Clone,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Text)]
pub struct $type($crate::id_type::global_id::GlobalId);
};
}
/// Implements common methods on the specified ID type.
#[macro_export]
macro_rules! impl_id_type_methods {
($type:ty, $field_name:literal) => {
impl $type {
/// Get the string representation of the ID type.
pub fn get_string_repr(&self) -> &str {
&self.0 .0 .0
}
}
impl $crate::id_type::TargetingKey for $type {
fn targeting_key_value(&self) -> &str {
self.get_string_repr()
}
}
};
}
/// Implements the `Debug` trait on the specified ID type.
#[macro_export]
macro_rules! impl_debug_id_type {
($type:ty) => {
impl core::fmt::Debug for $type {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_tuple(stringify!($type))
.field(&self.0 .0 .0)
.finish()
}
}
};
}
/// Implements the `TryFrom<Cow<'static, str>>` trait on the specified ID type.
#[macro_export]
macro_rules! impl_try_from_cow_str_id_type {
($type:ty, $field_name:literal) => {
impl TryFrom<std::borrow::Cow<'static, str>> for $type {
type Error = error_stack::Report<$crate::errors::ValidationError>;
fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> {
use error_stack::ResultExt;
let merchant_ref_id = $crate::id_type::LengthId::from(value).change_context(
$crate::errors::ValidationError::IncorrectValueProvided {
field_name: $field_name,
},
)?;
Ok(Self(merchant_ref_id))
}
}
};
}
/// Implements the `Default` trait on the specified ID type.
#[macro_export]
macro_rules! impl_default_id_type {
($type:ty, $prefix:literal) => {
impl Default for $type {
fn default() -> Self {
Self($crate::generate_ref_id_with_default_length($prefix))
}
}
};
}
/// Implements the `GenerateId` trait on the specified ID type.
#[macro_export]
macro_rules! impl_generate_id_id_type {
($type:ty, $prefix:literal) => {
impl $crate::id_type::GenerateId for $type {
fn generate() -> Self {
Self($crate::generate_ref_id_with_default_length($prefix))
}
}
};
}
/// Implements the `SerializableSecret` trait on the specified ID type.
#[macro_export]
macro_rules! impl_serializable_secret_id_type {
($type:ty) => {
impl masking::SerializableSecret for $type {}
};
}
/// Implements the `ToSql` and `FromSql` traits on the specified ID type.
#[macro_export]
macro_rules! impl_to_sql_from_sql_id_type {
($type:ty, $diesel_type:ty, $max_length:expr, $min_length:expr) => {
impl<DB> diesel::serialize::ToSql<$diesel_type, DB> for $type
where
DB: diesel::backend::Backend,
$crate::id_type::LengthId<$max_length, $min_length>:
diesel::serialize::ToSql<$diesel_type, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<$diesel_type, DB> for $type
where
DB: diesel::backend::Backend,
$crate::id_type::LengthId<$max_length, $min_length>:
diesel::deserialize::FromSql<$diesel_type, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
$crate::id_type::LengthId::<$max_length, $min_length>::from_sql(value).map(Self)
}
}
};
($type:ty) => {
$crate::impl_to_sql_from_sql_id_type!(
$type,
diesel::sql_types::Text,
{ $crate::consts::MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH },
{ $crate::consts::MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH }
);
};
}
#[cfg(feature = "v2")]
/// Implements the `ToSql` and `FromSql` traits on the specified Global ID type.
#[macro_export]
macro_rules! impl_to_sql_from_sql_global_id_type {
($type:ty, $diesel_type:ty) => {
impl<DB> diesel::serialize::ToSql<$diesel_type, DB> for $type
where
DB: diesel::backend::Backend,
$crate::id_type::global_id::GlobalId: diesel::serialize::ToSql<$diesel_type, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<$diesel_type, DB> for $type
where
DB: diesel::backend::Backend,
$crate::id_type::global_id::GlobalId:
diesel::deserialize::FromSql<$diesel_type, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
$crate::id_type::global_id::GlobalId::from_sql(value).map(Self)
}
}
};
($type:ty) => {
$crate::impl_to_sql_from_sql_global_id_type!($type, diesel::sql_types::Text);
};
}
/// Implements the `Queryable` trait on the specified ID type.
#[macro_export]
macro_rules! impl_queryable_id_type {
($type:ty, $diesel_type:ty) => {
impl<DB> diesel::Queryable<$diesel_type, DB> for $type
where
DB: diesel::backend::Backend,
Self: diesel::deserialize::FromSql<$diesel_type, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
Ok(row)
}
}
};
($type:ty) => {
$crate::impl_queryable_id_type!($type, diesel::sql_types::Text);
};
}
}
/// Create new generic list wrapper
#[macro_export]
macro_rules! create_list_wrapper {
(
$wrapper_name:ident,
$type_name: ty,
impl_functions: {
$($function_def: tt)*
}
) => {
#[derive(Clone, Debug)]
pub struct $wrapper_name(Vec<$type_name>);
impl $wrapper_name {
pub fn new(list: Vec<$type_name>) -> Self {
Self(list)
}
pub fn with_capacity(size: usize) -> Self {
Self(Vec::with_capacity(size))
}
$($function_def)*
}
impl std::ops::Deref for $wrapper_name {
type Target = Vec<$type_name>;
fn deref(&self) -> &<Self as std::ops::Deref>::Target {
&self.0
}
}
impl std::ops::DerefMut for $wrapper_name {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl IntoIterator for $wrapper_name {
type Item = $type_name;
type IntoIter = std::vec::IntoIter<$type_name>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl<'a> IntoIterator for &'a $wrapper_name {
type Item = &'a $type_name;
type IntoIter = std::slice::Iter<'a, $type_name>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl FromIterator<$type_name> for $wrapper_name {
fn from_iter<T: IntoIterator<Item = $type_name>>(iter: T) -> Self {
Self(iter.into_iter().collect())
}
}
};
}
/// Get the type name for a type
#[macro_export]
macro_rules! type_name {
($type:ty) => {
std::any::type_name::<$type>()
.rsplit("::")
.nth(1)
.unwrap_or_default();
};
}
/// **Note** Creates an enum wrapper that implements `FromStr`, `Display`, `Serialize`, and `Deserialize`
/// based on a specific string representation format: `"VariantName<delimiter>FieldValue"`.
/// It handles parsing errors by returning a dedicated `Invalid` variant.
/// *Note*: The macro adds `Invalid,` automatically.
///
/// # Use Case
///
/// This macro is designed for scenarios where you need an enum, with each variant
/// holding a single piece of associated data, to be easily convertible to and from
/// a simple string format. This is useful for cases where enum is serialized to key value pairs
///
/// It avoids more complex serialization structures (like JSON objects `{"VariantName": value}`)
/// in favor of a plain string representation.
///
/// # Input Enum Format and Constraints
///
/// To use this macro, the enum definition must adhere to the following structure:
///
/// 1. **Public Enum:** The enum must be declared as `pub enum EnumName { ... }`.
/// 2. **Struct Variants Only:** All variants must be struct variants (using `{}`).
/// 3. **Exactly One Field:** Each struct variant must contain *exactly one* named field.
/// * **Valid:** `VariantA { value: i32 }`
/// * **Invalid:** `VariantA(i32)` (tuple variant)
/// * **Invalid:** `VariantA` or `VariantA {}` (no field)
/// * **Invalid:** `VariantA { value: i32, other: bool }` (multiple fields)
/// 4. **Tag Delimiter:** The macro invocation must specify a `tag_delimiter` literal,
/// which is the character used to separate the variant name from the field data in
/// the string representation (e.g., `tag_delimiter = ":",`).
/// 5. **Field Type Requirements:** The type of the single field in each variant (`$field_ty`)
/// must implement:
/// * `core::str::FromStr`: To parse the field's data from the string part.
/// The `Err` type should ideally be convertible to a meaningful error, though the
/// macro currently uses a generic error message upon failure.
/// * `core::fmt::Display`: To convert the field's data into the string part.
/// * `serde::Serialize` and `serde::Deserialize<'de>`: Although the macro implements
/// custom `Serialize`/`Deserialize` for the *enum* using the string format, the field
/// type itself must satisfy these bounds if required elsewhere or by generic contexts.
/// The macro's implementations rely solely on `Display` and `FromStr` for the conversion.
/// 6. **Error Type:** This macro uses `core::convert::Infallible` as it never fails but gives
/// `Self::Invalid` variant.
///
/// # Serialization and Deserialization (`serde`)
///
/// When `serde` features are enabled and the necessary traits are derived or implemented,
/// this macro implements `Serialize` and `Deserialize` for the enum:
///
/// **Serialization:** An enum value like `MyEnum::VariantA { value: 123 }` (with `tag_delimiter = ":",`)
/// will be serialized into the string `"VariantA:123"`. If serializing to JSON, this results
/// in a JSON string: `"\"VariantA:123\""`.
/// **Deserialization:** The macro expects a string matching the format `"VariantName<delimiter>FieldValue"`.
/// It uses the enum's `FromStr` implementation internally. When deserializing from JSON, it
/// expects a JSON string containing the correctly formatted value (e.g., `"\"VariantA:123\""`).
///
/// # `Display` and `FromStr`
///
/// **`Display`:** Formats valid variants to `"VariantName<delimiter>FieldValue"` and catch-all cases to `"Invalid"`.
/// **`FromStr`:** Parses `"VariantName<delimiter>FieldValue"` to the variant, or returns `Self::Invalid`
/// if the input string is malformed or `"Invalid"`.
///
/// # Example
///
/// ```rust
/// use std::str::FromStr;
///
/// crate::impl_enum_str!(
/// tag_delimiter = ":",
/// #[derive(Debug, PartialEq, Clone)] // Add other derives as needed
/// pub enum Setting {
/// Timeout { duration_ms: u32 },
/// Username { name: String },
/// }
/// );
/// // Note: The macro adds `Invalid,` automatically.
///
/// fn main() {
/// // Display
/// let setting1 = Setting::Timeout { duration_ms: 5000 };
/// assert_eq!(setting1.to_string(), "Timeout:5000");
/// assert_eq!(Setting::Invalid.to_string(), "Invalid");
///
/// // FromStr (returns Self, not Result)
/// let parsed_setting: Setting = "Username:admin".parse().expect("Valid parse"); // parse() itself doesn't panic
/// assert_eq!(parsed_setting, Setting::Username { name: "admin".to_string() });
///
/// let invalid_format: Setting = "Timeout".parse().expect("Parse always returns Self");
/// assert_eq!(invalid_format, Setting::Invalid); // Malformed input yields Invalid
///
/// let bad_data: Setting = "Timeout:fast".parse().expect("Parse always returns Self");
/// assert_eq!(bad_data, Setting::Invalid); // Bad field data yields Invalid
///
/// let unknown_tag: Setting = "Unknown:abc".parse().expect("Parse always returns Self");
/// assert_eq!(unknown_tag, Setting::Invalid); // Unknown tag yields Invalid
///
/// let explicit_invalid: Setting = "Invalid".parse().expect("Parse always returns Self");
/// assert_eq!(explicit_invalid, Setting::Invalid); // "Invalid" string yields Invalid
///
/// // Serde (requires derive Serialize/Deserialize on Setting)
/// // let json_output = serde_json::to_string(&setting1).unwrap();
/// // assert_eq!(json_output, "\"Timeout:5000\"");
/// // let invalid_json_output = serde_json::to_string(&Setting::Invalid).unwrap();
/// // assert_eq!(invalid_json_output, "\"Invalid\"");
///
/// // let deserialized: Setting = serde_json::from_str("\"Username:guest\"").unwrap();
/// // assert_eq!(deserialized, Setting::Username { name: "guest".to_string() });
/// // let deserialized_invalid: Setting = serde_json::from_str("\"Invalid\"").unwrap();
/// // assert_eq!(deserialized_invalid, Setting::Invalid);
/// // let deserialized_malformed: Setting = serde_json::from_str("\"TimeoutFast\"").unwrap();
/// // assert_eq!(deserialized_malformed, Setting::Invalid); // Malformed -> Invalid
/// }
///
/// # // Mock macro definition for doctest purposes
/// # #[macro_export] macro_rules! impl_enum_str { ($($tt:tt)*) => { $($tt)* } }
/// ```
#[macro_export]
macro_rules! impl_enum_str {
(
tag_delimiter = $tag_delim:literal,
$(#[$enum_attr:meta])*
pub enum $enum_name:ident {
$(
$(#[$variant_attr:meta])*
$variant:ident {
$(#[$field_attr:meta])*
$field:ident : $field_ty:ty $(,)?
}
),* $(,)?
}
) => {
$(#[$enum_attr])*
pub enum $enum_name {
$(
$(#[$variant_attr])*
$variant {
$(#[$field_attr])*
$field : $field_ty
},
)*
/// Represents a parsing failure.
Invalid, // Automatically add the Invalid variant
}
// Implement FromStr - now returns Self, not Result
impl core::str::FromStr for $enum_name {
// No associated error type needed
type Err = core::convert::Infallible; // FromStr requires an Err type, use Infallible
fn from_str(s: &str) -> Result<Self, Self::Err> {
// Check for explicit "Invalid" string first
if s == "Invalid" {
#[cfg(feature = "logs")]
router_env::logger::warn!(
"Failed to parse {} enum from 'Invalid': explicit Invalid variant encountered",
stringify!($enum_name)
);
return Ok(Self::Invalid);
}
let Some((tag, associated_data)) = s.split_once($tag_delim) else {
// Missing delimiter -> Invalid
#[cfg(feature = "logs")]
router_env::logger::warn!(
"Failed to parse {} enum from '{}': missing delimiter",
stringify!($enum_name),
s
);
return Ok(Self::Invalid);
};
let result = match tag {
$(
stringify!($variant) => {
// Try to parse the field data
match associated_data.parse::<$field_ty>() {
Ok(parsed_field) => {
// Success -> construct the variant
Self::$variant { $field: parsed_field }
},
Err(_) => {
// Field parse failure -> Invalid
#[cfg(feature = "logs")]
router_env::logger::warn!(
"Failed to parse {} enum from '{}': field parse failure for variant '{}'",
stringify!($enum_name),
s,
stringify!($variant)
);
Self::Invalid
}
}
}
),*
// Unknown tag -> Invalid
_ => {
#[cfg(feature = "logs")]
router_env::logger::warn!(
"Failed to parse {} enum from '{}': unknown variant tag '{}'",
stringify!($enum_name),
s,
tag
);
Self::Invalid
},
};
Ok(result) // Always Ok because failure modes return Self::Invalid
}
}
// Implement Serialize
impl ::serde::Serialize for $enum_name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: ::serde::Serializer,
{
match self {
$(
Self::$variant { $field } => {
let s = format!("{}{}{}", stringify!($variant), $tag_delim, $field);
serializer.serialize_str(&s)
}
)*
// Handle Invalid variant
Self::Invalid => serializer.serialize_str("Invalid"),
}
}
}
// Implement Deserialize
impl<'de> ::serde::Deserialize<'de> for $enum_name {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: ::serde::Deserializer<'de>,
{
struct EnumVisitor;
impl<'de> ::serde::de::Visitor<'de> for EnumVisitor {
type Value = $enum_name;
fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.write_str(concat!("a string like VariantName", $tag_delim, "field_data or 'Invalid'"))
}
// Leverage the FromStr implementation which now returns Self::Invalid on failure
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: ::serde::de::Error,
{
// parse() now returns Result<Self, Infallible>
// We unwrap() the Ok because it's infallible.
Ok(value.parse::<$enum_name>().unwrap())
}
fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
where
E: ::serde::de::Error,
{
Ok(value.parse::<$enum_name>().unwrap())
}
}
deserializer.deserialize_str(EnumVisitor)
}
}
// Implement Display
impl core::fmt::Display for $enum_name {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
$(
Self::$variant { $field } => {
write!(f, "{}{}{}", stringify!($variant), $tag_delim, $field)
}
)*
// Handle Invalid variant
Self::Invalid => write!(f, "Invalid"),
}
}
}
// Implement HasInvalidVariant trait
impl $crate::types::HasInvalidVariant for $enum_name {
fn is_invalid(&self) -> bool {
matches!(self, Self::Invalid)
}
}
};
}
// --- Tests ---
#[cfg(test)]
mod tests {
use serde_json::{json, Value as JsonValue};
impl_enum_str!(
tag_delimiter = ":",
#[derive(Debug, PartialEq, Clone)]
pub enum TestEnum {
VariantA { value: i32 },
VariantB { text: String },
VariantC { id: u64 },
VariantJson { data: JsonValue },
} // Note: Invalid variant is added automatically by the macro
);
#[test]
fn test_enum_from_str_ok() {
// Success cases just parse directly
let parsed_a: TestEnum = "VariantA:42".parse().unwrap(); // Unwrapping Infallible is fine
assert_eq!(parsed_a, TestEnum::VariantA { value: 42 });
let parsed_b: TestEnum = "VariantB:hello world".parse().unwrap();
assert_eq!(
parsed_b,
TestEnum::VariantB {
text: "hello world".to_string()
}
);
let parsed_c: TestEnum = "VariantC:123456789012345".parse().unwrap();
assert_eq!(
parsed_c,
TestEnum::VariantC {
id: 123456789012345
}
);
let parsed_json: TestEnum = r#"VariantJson:{"ok":true}"#.parse().unwrap();
assert_eq!(
parsed_json,
TestEnum::VariantJson {
data: json!({"ok": true})
}
);
}
#[test]
fn test_enum_from_str_failures_yield_invalid() {
// Missing delimiter
let parsed: TestEnum = "VariantA".parse().unwrap();
assert_eq!(parsed, TestEnum::Invalid);
// Unknown tag
let parsed: TestEnum = "UnknownVariant:123".parse().unwrap();
assert_eq!(parsed, TestEnum::Invalid);
// Bad field data for i32
let parsed: TestEnum = "VariantA:not_a_number".parse().unwrap();
assert_eq!(parsed, TestEnum::Invalid);
// Bad field data for JsonValue
let parsed: TestEnum = r#"VariantJson:{"bad_json"#.parse().unwrap();
assert_eq!(parsed, TestEnum::Invalid);
// Empty field data for non-string (e.g., i32)
let parsed: TestEnum = "VariantA:".parse().unwrap();
assert_eq!(parsed, TestEnum::Invalid);
// Empty field data for string IS valid for String type
let parsed_str: TestEnum = "VariantB:".parse().unwrap();
assert_eq!(
parsed_str,
TestEnum::VariantB {
text: "".to_string()
}
);
// Parsing the literal "Invalid" string
let parsed_invalid_str: TestEnum = "Invalid".parse().unwrap();
assert_eq!(parsed_invalid_str, TestEnum::Invalid);
}
#[test]
fn test_enum_display_and_serialize() {
// Display valid
let value_a = TestEnum::VariantA { value: 99 };
assert_eq!(value_a.to_string(), "VariantA:99");
// Serialize valid
let json_a = serde_json::to_string(&value_a).expect("Serialize A failed");
assert_eq!(json_a, "\"VariantA:99\""); // Serializes to JSON string
// Display Invalid
let value_invalid = TestEnum::Invalid;
assert_eq!(value_invalid.to_string(), "Invalid");
// Serialize Invalid
let json_invalid = serde_json::to_string(&value_invalid).expect("Serialize Invalid failed");
assert_eq!(json_invalid, "\"Invalid\""); // Serializes to JSON string "Invalid"
}
#[test]
fn test_enum_deserialize() {
// Deserialize valid
let input_a = "\"VariantA:123\"";
let deserialized_a: TestEnum = serde_json::from_str(input_a).expect("Deserialize A failed");
assert_eq!(deserialized_a, TestEnum::VariantA { value: 123 });
// Deserialize explicit "Invalid"
let input_invalid = "\"Invalid\"";
let deserialized_invalid: TestEnum =
serde_json::from_str(input_invalid).expect("Deserialize Invalid failed");
assert_eq!(deserialized_invalid, TestEnum::Invalid);
// Deserialize malformed string (according to macro rules) -> Invalid
let input_malformed = "\"VariantA_no_delimiter\"";
let deserialized_malformed: TestEnum =
serde_json::from_str(input_malformed).expect("Deserialize malformed should succeed");
assert_eq!(deserialized_malformed, TestEnum::Invalid);
// Deserialize string with bad field data -> Invalid
let input_bad_data = "\"VariantA:not_a_number\"";
let deserialized_bad_data: TestEnum =
serde_json::from_str(input_bad_data).expect("Deserialize bad data should succeed");
assert_eq!(deserialized_bad_data, TestEnum::Invalid);
}
}
|
crates__common_utils__src__pii.rs
|
//! Personal Identifiable Information protection.
use std::{convert::AsRef, fmt, ops, str::FromStr};
use diesel::{
backend::Backend,
deserialize,
deserialize::FromSql,
prelude::*,
serialize::{Output, ToSql},
sql_types, AsExpression,
};
use error_stack::ResultExt;
use masking::{ExposeInterface, Secret, Strategy, WithType};
#[cfg(feature = "logs")]
use router_env::logger;
use serde::Deserialize;
use crate::{
crypto::Encryptable,
errors::{self, ValidationError},
validation::{validate_email, validate_phone_number},
};
/// A string constant representing a redacted or masked value.
pub const REDACTED: &str = "Redacted";
/// Type alias for serde_json value which has Secret Information
pub type SecretSerdeValue = Secret<serde_json::Value>;
/// Strategy for masking a PhoneNumber
#[derive(Debug)]
pub enum PhoneNumberStrategy {}
/// Phone Number
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(try_from = "String")]
pub struct PhoneNumber(Secret<String, PhoneNumberStrategy>);
impl<T> Strategy<T> for PhoneNumberStrategy
where
T: AsRef<str> + fmt::Debug,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_str: &str = val.as_ref();
if let Some(val_str) = val_str.get(val_str.len() - 4..) {
// masks everything but the last 4 digits
write!(f, "{}{}", "*".repeat(val_str.len() - 4), val_str)
} else {
#[cfg(feature = "logs")]
logger::error!("Invalid phone number: {val_str}");
WithType::fmt(val, f)
}
}
}
impl FromStr for PhoneNumber {
type Err = error_stack::Report<ValidationError>;
fn from_str(phone_number: &str) -> Result<Self, Self::Err> {
validate_phone_number(phone_number)?;
let secret = Secret::<String, PhoneNumberStrategy>::new(phone_number.to_string());
Ok(Self(secret))
}
}
impl TryFrom<String> for PhoneNumber {
type Error = error_stack::Report<errors::ParsingError>;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::from_str(&value).change_context(errors::ParsingError::PhoneNumberParsingError)
}
}
impl ops::Deref for PhoneNumber {
type Target = Secret<String, PhoneNumberStrategy>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ops::DerefMut for PhoneNumber {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<DB> Queryable<sql_types::Text, DB> for PhoneNumber
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for PhoneNumber
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(bytes)?;
Ok(Self::from_str(val.as_str())?)
}
}
impl<DB> ToSql<sql_types::Text, DB> for PhoneNumber
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
/*
/// Phone number
#[derive(Debug)]
pub struct PhoneNumber;
impl<T> Strategy<T> for PhoneNumber
where
T: AsRef<str>,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_str: &str = val.as_ref();
if val_str.len() < 10 || val_str.len() > 12 {
return WithType::fmt(val, f);
}
write!(
f,
"{}{}{}",
&val_str[..2],
"*".repeat(val_str.len() - 5),
&val_str[(val_str.len() - 3)..]
)
}
}
*/
/// Strategy for Encryption
#[derive(Debug)]
pub enum EncryptionStrategy {}
impl<T> Strategy<T> for EncryptionStrategy
where
T: AsRef<[u8]>,
{
fn fmt(value: &T, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
fmt,
"*** Encrypted data of length {} bytes ***",
value.as_ref().len()
)
}
}
/// Client secret
#[derive(Debug)]
pub enum ClientSecret {}
impl<T> Strategy<T> for ClientSecret
where
T: AsRef<str>,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_str: &str = val.as_ref();
let client_secret_segments: Vec<&str> = val_str.split('_').collect();
if client_secret_segments.len() != 4
|| !client_secret_segments.contains(&"pay")
|| !client_secret_segments.contains(&"secret")
{
return WithType::fmt(val, f);
}
if let Some((client_secret_segments_0, client_secret_segments_1)) = client_secret_segments
.first()
.zip(client_secret_segments.get(1))
{
write!(
f,
"{}_{}_{}",
client_secret_segments_0,
client_secret_segments_1,
"*".repeat(
val_str.len()
- (client_secret_segments_0.len() + client_secret_segments_1.len() + 2)
)
)
} else {
#[cfg(feature = "logs")]
logger::error!("Invalid client secret: {val_str}");
WithType::fmt(val, f)
}
}
}
/// Strategy for masking Email
#[derive(Debug, Copy, Clone, Deserialize)]
pub enum EmailStrategy {}
impl<T> Strategy<T> for EmailStrategy
where
T: AsRef<str> + fmt::Debug,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_str: &str = val.as_ref();
match val_str.split_once('@') {
Some((a, b)) => write!(f, "{}@{}", "*".repeat(a.len()), b),
None => WithType::fmt(val, f),
}
}
}
/// Email address
#[derive(
serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, Default, AsExpression,
)]
#[diesel(sql_type = sql_types::Text)]
#[serde(try_from = "String")]
pub struct Email(Secret<String, EmailStrategy>);
impl From<Encryptable<Secret<String, EmailStrategy>>> for Email {
fn from(item: Encryptable<Secret<String, EmailStrategy>>) -> Self {
Self(item.into_inner())
}
}
impl ExposeInterface<Secret<String, EmailStrategy>> for Email {
fn expose(self) -> Secret<String, EmailStrategy> {
self.0
}
}
impl TryFrom<String> for Email {
type Error = error_stack::Report<errors::ParsingError>;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::from_str(&value).change_context(errors::ParsingError::EmailParsingError)
}
}
impl ops::Deref for Email {
type Target = Secret<String, EmailStrategy>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ops::DerefMut for Email {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<DB> Queryable<sql_types::Text, DB> for Email
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for Email
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(bytes)?;
Ok(Self::from_str(val.as_str())?)
}
}
impl<DB> ToSql<sql_types::Text, DB> for Email
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl FromStr for Email {
type Err = error_stack::Report<ValidationError>;
fn from_str(email: &str) -> Result<Self, Self::Err> {
if email.eq(REDACTED) {
return Ok(Self(Secret::new(email.to_string())));
}
match validate_email(email) {
Ok(_) => {
let secret = Secret::<String, EmailStrategy>::new(email.to_string());
Ok(Self(secret))
}
Err(_) => Err(ValidationError::InvalidValue {
message: "Invalid email address format".into(),
}
.into()),
}
}
}
/// IP address
#[derive(Debug)]
pub enum IpAddress {}
impl<T> Strategy<T> for IpAddress
where
T: AsRef<str>,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_str: &str = val.as_ref();
let segments: Vec<&str> = val_str.split('.').collect();
if segments.len() != 4 {
return WithType::fmt(val, f);
}
for seg in segments.iter() {
if seg.is_empty() || seg.len() > 3 {
return WithType::fmt(val, f);
}
}
if let Some(segments) = segments.first() {
write!(f, "{segments}.**.**.**")
} else {
#[cfg(feature = "logs")]
logger::error!("Invalid IP address: {val_str}");
WithType::fmt(val, f)
}
}
}
/// Strategy for masking UPI VPA's
#[derive(Debug)]
pub enum UpiVpaMaskingStrategy {}
impl<T> Strategy<T> for UpiVpaMaskingStrategy
where
T: AsRef<str> + fmt::Debug,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let vpa_str: &str = val.as_ref();
if let Some((user_identifier, bank_or_psp)) = vpa_str.split_once('@') {
let masked_user_identifier = "*".repeat(user_identifier.len());
write!(f, "{masked_user_identifier}@{bank_or_psp}")
} else {
WithType::fmt(val, f)
}
}
}
#[cfg(test)]
mod pii_masking_strategy_tests {
use std::str::FromStr;
use masking::{ExposeInterface, Secret};
use super::{ClientSecret, Email, IpAddress, UpiVpaMaskingStrategy};
use crate::pii::{EmailStrategy, REDACTED};
/*
#[test]
fn test_valid_phone_number_masking() {
let secret: Secret<String, PhoneNumber> = Secret::new("9123456789".to_string());
assert_eq!("99*****299", format!("{}", secret));
}
#[test]
fn test_invalid_phone_number_masking() {
let secret: Secret<String, PhoneNumber> = Secret::new("99229922".to_string());
assert_eq!("*** alloc::string::String ***", format!("{}", secret));
let secret: Secret<String, PhoneNumber> = Secret::new("9922992299229922".to_string());
assert_eq!("*** alloc::string::String ***", format!("{}", secret));
}
*/
#[test]
fn test_valid_email_masking() {
let secret: Secret<String, EmailStrategy> = Secret::new("example@test.com".to_string());
assert_eq!("*******@test.com", format!("{secret:?}"));
let secret: Secret<String, EmailStrategy> = Secret::new("username@gmail.com".to_string());
assert_eq!("********@gmail.com", format!("{secret:?}"));
}
#[test]
fn test_invalid_email_masking() {
let secret: Secret<String, EmailStrategy> = Secret::new("myemailgmail.com".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
let secret: Secret<String, EmailStrategy> = Secret::new("myemail$gmail.com".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
}
#[test]
fn test_valid_newtype_email() {
let email_check = Email::from_str("example@abc.com");
assert!(email_check.is_ok());
}
#[test]
fn test_invalid_newtype_email() {
let email_check = Email::from_str("example@abc@com");
assert!(email_check.is_err());
}
#[test]
fn test_redacted_email() {
let email_result = Email::from_str(REDACTED);
assert!(email_result.is_ok());
if let Ok(email) = email_result {
let secret_value = email.0.expose();
assert_eq!(secret_value.as_str(), REDACTED);
}
}
#[test]
fn test_valid_ip_addr_masking() {
let secret: Secret<String, IpAddress> = Secret::new("123.23.1.78".to_string());
assert_eq!("123.**.**.**", format!("{secret:?}"));
}
#[test]
fn test_invalid_ip_addr_masking() {
let secret: Secret<String, IpAddress> = Secret::new("123.4.56".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
let secret: Secret<String, IpAddress> = Secret::new("123.4567.12.4".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
let secret: Secret<String, IpAddress> = Secret::new("123..4.56".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
}
#[test]
fn test_valid_client_secret_masking() {
let secret: Secret<String, ClientSecret> =
Secret::new("pay_uszFB2QGe9MmLY65ojhT_secret_tLjTz9tAQxUVEFqfmOIP".to_string());
assert_eq!(
"pay_uszFB2QGe9MmLY65ojhT_***************************",
format!("{secret:?}")
);
}
#[test]
fn test_invalid_client_secret_masking() {
let secret: Secret<String, IpAddress> =
Secret::new("pay_uszFB2QGe9MmLY65ojhT_secret".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
}
#[test]
fn test_valid_phone_number_default_masking() {
let secret: Secret<String> = Secret::new("+40712345678".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
}
#[test]
fn test_valid_upi_vpa_masking() {
let secret: Secret<String, UpiVpaMaskingStrategy> = Secret::new("my_name@upi".to_string());
assert_eq!("*******@upi", format!("{secret:?}"));
}
#[test]
fn test_invalid_upi_vpa_masking() {
let secret: Secret<String, UpiVpaMaskingStrategy> = Secret::new("my_name_upi".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
}
}
|
crates__common_utils__src__types.rs
|
//! Types that can be used in other crates
pub mod keymanager;
/// Enum for Authentication Level
pub mod authentication;
/// User related types
pub mod user;
/// types that are wrappers around primitive types
pub mod primitive_wrappers;
use std::{
borrow::Cow,
fmt::Display,
iter::Sum,
num::NonZeroI64,
ops::{Add, Mul, Sub},
primitive::i64,
str::FromStr,
};
use common_enums::enums;
use diesel::{
backend::Backend,
deserialize,
deserialize::FromSql,
serialize::{Output, ToSql},
sql_types,
sql_types::Jsonb,
AsExpression, FromSqlRow, Queryable,
};
use error_stack::{report, ResultExt};
pub use primitive_wrappers::bool_wrappers::{
AlwaysRequestExtendedAuthorization, ExtendedAuthorizationAppliedBool,
RequestExtendedAuthorizationBool,
};
use rust_decimal::{
prelude::{FromPrimitive, ToPrimitive},
Decimal,
};
use semver::Version;
use serde::{de::Visitor, Deserialize, Deserializer, Serialize};
use thiserror::Error;
use time::PrimitiveDateTime;
use utoipa::ToSchema;
use crate::{
consts::{
self, MAX_DESCRIPTION_LENGTH, MAX_STATEMENT_DESCRIPTOR_LENGTH, PUBLISHABLE_KEY_LENGTH,
},
errors::{CustomResult, ParsingError, PercentageError, ValidationError},
fp_utils::when,
id_type, impl_enum_str,
};
/// Represents Percentage Value between 0 and 100 both inclusive
#[derive(Clone, Default, Debug, PartialEq, Serialize)]
pub struct Percentage<const PRECISION: u8> {
// this value will range from 0 to 100, decimal length defined by precision macro
/// Percentage value ranging between 0 and 100
percentage: f32,
}
fn get_invalid_percentage_error_message(precision: u8) -> String {
format!(
"value should be a float between 0 to 100 and precise to only upto {precision} decimal digits",
)
}
impl<const PRECISION: u8> Percentage<PRECISION> {
/// construct percentage using a string representation of float value
pub fn from_string(value: String) -> CustomResult<Self, PercentageError> {
if Self::is_valid_string_value(&value)? {
Ok(Self {
percentage: value
.parse::<f32>()
.change_context(PercentageError::InvalidPercentageValue)?,
})
} else {
Err(report!(PercentageError::InvalidPercentageValue))
.attach_printable(get_invalid_percentage_error_message(PRECISION))
}
}
/// function to get percentage value
pub fn get_percentage(&self) -> f32 {
self.percentage
}
/// apply the percentage to amount and ceil the result
#[allow(clippy::as_conversions)]
pub fn apply_and_ceil_result(
&self,
amount: MinorUnit,
) -> CustomResult<MinorUnit, PercentageError> {
let max_amount = i64::MAX / 10000;
let amount = amount.0;
if amount > max_amount {
// value gets rounded off after i64::MAX/10000
Err(report!(PercentageError::UnableToApplyPercentage {
percentage: self.percentage,
amount: MinorUnit::new(amount),
}))
.attach_printable(format!(
"Cannot calculate percentage for amount greater than {max_amount}",
))
} else {
let percentage_f64 = f64::from(self.percentage);
let result = (amount as f64 * (percentage_f64 / 100.0)).ceil() as i64;
Ok(MinorUnit::new(result))
}
}
fn is_valid_string_value(value: &str) -> CustomResult<bool, PercentageError> {
let float_value = Self::is_valid_float_string(value)?;
Ok(Self::is_valid_range(float_value) && Self::is_valid_precision_length(value))
}
fn is_valid_float_string(value: &str) -> CustomResult<f32, PercentageError> {
value
.parse::<f32>()
.change_context(PercentageError::InvalidPercentageValue)
}
fn is_valid_range(value: f32) -> bool {
(0.0..=100.0).contains(&value)
}
fn is_valid_precision_length(value: &str) -> bool {
if value.contains('.') {
// if string has '.' then take the decimal part and verify precision length
match value.split('.').next_back() {
Some(decimal_part) => {
decimal_part.trim_end_matches('0').len() <= <u8 as Into<usize>>::into(PRECISION)
}
// will never be None
None => false,
}
} else {
// if there is no '.' then it is a whole number with no decimal part. So return true
true
}
}
}
// custom serde deserialization function
struct PercentageVisitor<const PRECISION: u8> {}
impl<'de, const PRECISION: u8> Visitor<'de> for PercentageVisitor<PRECISION> {
type Value = Percentage<PRECISION>;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("Percentage object")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: serde::de::MapAccess<'de>,
{
let mut percentage_value = None;
while let Some(key) = map.next_key::<String>()? {
if key.eq("percentage") {
if percentage_value.is_some() {
return Err(serde::de::Error::duplicate_field("percentage"));
}
percentage_value = Some(map.next_value::<serde_json::Value>()?);
} else {
// Ignore unknown fields
let _: serde::de::IgnoredAny = map.next_value()?;
}
}
if let Some(value) = percentage_value {
let string_value = value.to_string();
Ok(Percentage::from_string(string_value.clone()).map_err(|_| {
serde::de::Error::invalid_value(
serde::de::Unexpected::Other(&format!("percentage value {string_value}")),
&&*get_invalid_percentage_error_message(PRECISION),
)
})?)
} else {
Err(serde::de::Error::missing_field("percentage"))
}
}
}
impl<'de, const PRECISION: u8> Deserialize<'de> for Percentage<PRECISION> {
fn deserialize<D>(data: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
data.deserialize_map(PercentageVisitor::<PRECISION> {})
}
}
/// represents surcharge type and value
#[derive(Clone, Debug, PartialEq, Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case", tag = "type", content = "value")]
pub enum Surcharge {
/// Fixed Surcharge value
Fixed(MinorUnit),
/// Surcharge percentage
Rate(Percentage<{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH }>),
}
/// This struct lets us represent a semantic version type
#[derive(Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, Ord, PartialOrd)]
#[diesel(sql_type = Jsonb)]
#[derive(Serialize, serde::Deserialize)]
pub struct SemanticVersion(#[serde(with = "Version")] Version);
impl SemanticVersion {
/// returns major version number
pub fn get_major(&self) -> u64 {
self.0.major
}
/// returns minor version number
pub fn get_minor(&self) -> u64 {
self.0.minor
}
/// Constructs new SemanticVersion instance
pub fn new(major: u64, minor: u64, patch: u64) -> Self {
Self(Version::new(major, minor, patch))
}
}
impl Display for SemanticVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl FromStr for SemanticVersion {
type Err = error_stack::Report<ParsingError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(Version::from_str(s).change_context(
ParsingError::StructParseFailure("SemanticVersion"),
)?))
}
}
crate::impl_to_sql_from_sql_json!(SemanticVersion);
/// Amount convertor trait for connector
pub trait AmountConvertor: Send {
/// Output type for the connector
type Output;
/// helps in conversion of connector required amount type
fn convert(
&self,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>>;
/// helps in converting back connector required amount type to core minor unit
fn convert_back(
&self,
amount: Self::Output,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>>;
}
/// Connector required amount type
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct StringMinorUnitForConnector;
impl AmountConvertor for StringMinorUnitForConnector {
type Output = StringMinorUnit;
fn convert(
&self,
amount: MinorUnit,
_currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_string()
}
fn convert_back(
&self,
amount: Self::Output,
_currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_i64()
}
}
/// Core required conversion type
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct StringMajorUnitForCore;
impl AmountConvertor for StringMajorUnitForCore {
type Output = StringMajorUnit;
fn convert(
&self,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
amount.to_major_unit_as_string(currency)
}
fn convert_back(
&self,
amount: StringMajorUnit,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_i64(currency)
}
}
/// Connector required amount type
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct StringMajorUnitForConnector;
impl AmountConvertor for StringMajorUnitForConnector {
type Output = StringMajorUnit;
fn convert(
&self,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
amount.to_major_unit_as_string(currency)
}
fn convert_back(
&self,
amount: StringMajorUnit,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_i64(currency)
}
}
/// Connector required amount type
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct FloatMajorUnitForConnector;
impl AmountConvertor for FloatMajorUnitForConnector {
type Output = FloatMajorUnit;
fn convert(
&self,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
amount.to_major_unit_as_f64(currency)
}
fn convert_back(
&self,
amount: FloatMajorUnit,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_i64(currency)
}
}
/// Connector required amount type
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct MinorUnitForConnector;
impl AmountConvertor for MinorUnitForConnector {
type Output = MinorUnit;
fn convert(
&self,
amount: MinorUnit,
_currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
Ok(amount)
}
fn convert_back(
&self,
amount: MinorUnit,
_currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
Ok(amount)
}
}
/// This Unit struct represents MinorUnit in which core amount works
#[derive(
Default,
Debug,
serde::Deserialize,
AsExpression,
serde::Serialize,
Clone,
Copy,
PartialEq,
Eq,
Hash,
ToSchema,
PartialOrd,
Ord,
)]
#[diesel(sql_type = sql_types::BigInt)]
pub struct MinorUnit(i64);
impl MinorUnit {
/// gets amount as i64 value will be removed in future
pub fn get_amount_as_i64(self) -> i64 {
self.0
}
/// forms a new minor default unit i.e zero
pub fn zero() -> Self {
Self(0)
}
/// forms a new minor unit from amount
pub fn new(value: i64) -> Self {
Self(value)
}
/// checks if the amount is greater than the given value
pub fn is_greater_than(&self, value: i64) -> bool {
self.get_amount_as_i64() > value
}
/// Convert the amount to its major denomination based on Currency and return String
/// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies.
/// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/
fn to_major_unit_as_string(
self,
currency: enums::Currency,
) -> Result<StringMajorUnit, error_stack::Report<ParsingError>> {
let amount_f64 = self.to_major_unit_as_f64(currency)?;
let amount_string = if currency.is_zero_decimal_currency() {
amount_f64.0.to_string()
} else if currency.is_three_decimal_currency() {
format!("{:.3}", amount_f64.0)
} else {
format!("{:.2}", amount_f64.0)
};
Ok(StringMajorUnit::new(amount_string))
}
/// Convert the amount to its major denomination based on Currency and return f64
fn to_major_unit_as_f64(
self,
currency: enums::Currency,
) -> Result<FloatMajorUnit, error_stack::Report<ParsingError>> {
let amount_decimal =
Decimal::from_i64(self.0).ok_or(ParsingError::I64ToDecimalConversionFailure)?;
let amount = if currency.is_zero_decimal_currency() {
amount_decimal
} else if currency.is_three_decimal_currency() {
amount_decimal / Decimal::from(1000)
} else {
amount_decimal / Decimal::from(100)
};
let amount_f64 = amount
.to_f64()
.ok_or(ParsingError::FloatToDecimalConversionFailure)?;
Ok(FloatMajorUnit::new(amount_f64))
}
///Convert minor unit to string minor unit
fn to_minor_unit_as_string(self) -> Result<StringMinorUnit, error_stack::Report<ParsingError>> {
Ok(StringMinorUnit::new(self.0.to_string()))
}
}
impl From<NonZeroI64> for MinorUnit {
fn from(val: NonZeroI64) -> Self {
Self::new(val.get())
}
}
impl Display for MinorUnit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl<DB> FromSql<sql_types::BigInt, DB> for MinorUnit
where
DB: Backend,
i64: FromSql<sql_types::BigInt, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = i64::from_sql(value)?;
Ok(Self(val))
}
}
impl<DB> ToSql<sql_types::BigInt, DB> for MinorUnit
where
DB: Backend,
i64: ToSql<sql_types::BigInt, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> Queryable<sql_types::BigInt, DB> for MinorUnit
where
DB: Backend,
Self: FromSql<sql_types::BigInt, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl Add for MinorUnit {
type Output = Self;
fn add(self, a2: Self) -> Self {
Self(self.0 + a2.0)
}
}
impl Sub for MinorUnit {
type Output = Self;
fn sub(self, a2: Self) -> Self {
Self(self.0 - a2.0)
}
}
impl Mul<u16> for MinorUnit {
type Output = Self;
fn mul(self, a2: u16) -> Self::Output {
Self(self.0 * i64::from(a2))
}
}
impl Sum for MinorUnit {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(Self(0), |a, b| a + b)
}
}
/// Connector specific types to send
#[derive(
Default,
Debug,
serde::Deserialize,
AsExpression,
serde::Serialize,
Clone,
PartialEq,
Eq,
Hash,
ToSchema,
PartialOrd,
)]
#[diesel(sql_type = sql_types::Text)]
pub struct StringMinorUnit(String);
impl StringMinorUnit {
/// forms a new minor unit in string from amount
fn new(value: String) -> Self {
Self(value)
}
/// converts to minor unit i64 from minor unit string value
fn to_minor_unit_as_i64(&self) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
let amount_string = &self.0;
let amount_decimal = Decimal::from_str(amount_string).map_err(|e| {
ParsingError::StringToDecimalConversionFailure {
error: e.to_string(),
}
})?;
let amount_i64 = amount_decimal
.to_i64()
.ok_or(ParsingError::DecimalToI64ConversionFailure)?;
Ok(MinorUnit::new(amount_i64))
}
}
impl Display for StringMinorUnit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl<DB> FromSql<sql_types::Text, DB> for StringMinorUnit
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(value)?;
Ok(Self(val))
}
}
impl<DB> ToSql<sql_types::Text, DB> for StringMinorUnit
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> Queryable<sql_types::Text, DB> for StringMinorUnit
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
/// Connector specific types to send
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct FloatMajorUnit(f64);
impl FloatMajorUnit {
/// forms a new major unit from amount
fn new(value: f64) -> Self {
Self(value)
}
/// forms a new major unit with zero amount
pub fn zero() -> Self {
Self(0.0)
}
/// converts to minor unit as i64 from FloatMajorUnit
fn to_minor_unit_as_i64(
self,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
let amount_decimal =
Decimal::from_f64(self.0).ok_or(ParsingError::FloatToDecimalConversionFailure)?;
let amount = if currency.is_zero_decimal_currency() {
amount_decimal
} else if currency.is_three_decimal_currency() {
amount_decimal * Decimal::from(1000)
} else {
amount_decimal * Decimal::from(100)
};
let amount_i64 = amount
.to_i64()
.ok_or(ParsingError::DecimalToI64ConversionFailure)?;
Ok(MinorUnit::new(amount_i64))
}
}
/// Connector specific types to send
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq)]
pub struct StringMajorUnit(String);
impl StringMajorUnit {
/// forms a new major unit from amount
fn new(value: String) -> Self {
Self(value)
}
/// Converts to minor unit as i64 from StringMajorUnit
fn to_minor_unit_as_i64(
&self,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
let amount_decimal = Decimal::from_str(&self.0).map_err(|e| {
ParsingError::StringToDecimalConversionFailure {
error: e.to_string(),
}
})?;
let amount = if currency.is_zero_decimal_currency() {
amount_decimal
} else if currency.is_three_decimal_currency() {
amount_decimal * Decimal::from(1000)
} else {
amount_decimal * Decimal::from(100)
};
let amount_i64 = amount
.to_i64()
.ok_or(ParsingError::DecimalToI64ConversionFailure)?;
Ok(MinorUnit::new(amount_i64))
}
/// forms a new StringMajorUnit default unit i.e zero
pub fn zero() -> Self {
Self("0".to_string())
}
/// Get string amount from struct to be removed in future
pub fn get_amount_as_string(&self) -> String {
self.0.clone()
}
/// forms a new default 2-decimal major unit
pub fn zero_decimal() -> Self {
Self("0.00".to_string())
}
}
#[derive(
Debug,
serde::Deserialize,
AsExpression,
serde::Serialize,
Clone,
PartialEq,
Eq,
Hash,
ToSchema,
PartialOrd,
)]
#[diesel(sql_type = sql_types::Text)]
/// This domain type can be used for any url
pub struct Url(url::Url);
impl Url {
/// Get string representation of the url
pub fn get_string_repr(&self) -> &str {
self.0.as_str()
}
/// wrap the url::Url in Url type
pub fn wrap(url: url::Url) -> Self {
Self(url)
}
/// Get the inner url
pub fn into_inner(self) -> url::Url {
self.0
}
/// Add query params to the url
pub fn add_query_params(mut self, (key, value): (&str, &str)) -> Self {
let url = self
.0
.query_pairs_mut()
.append_pair(key, value)
.finish()
.clone();
Self(url)
}
}
impl<DB> ToSql<sql_types::Text, DB> for Url
where
DB: Backend,
str: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
let url_string = self.0.as_str();
url_string.to_sql(out)
}
}
impl<DB> FromSql<sql_types::Text, DB> for Url
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(value)?;
let url = url::Url::parse(&val)?;
Ok(Self(url))
}
}
/// A type representing a range of time for filtering, including a mandatory start time and an optional end time.
#[derive(
Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema,
)]
pub struct TimeRange {
/// The start time to filter payments list or to get list of filters. To get list of filters start time is needed to be passed
#[serde(with = "crate::custom_serde::iso8601")]
#[serde(alias = "startTime")]
pub start_time: PrimitiveDateTime,
/// The end time to filter payments list or to get list of filters. If not passed the default time is now
#[serde(default, with = "crate::custom_serde::iso8601::option")]
#[serde(alias = "endTime")]
pub end_time: Option<PrimitiveDateTime>,
}
#[cfg(test)]
mod amount_conversion_tests {
use super::*;
const TWO_DECIMAL_CURRENCY: enums::Currency = enums::Currency::USD;
const THREE_DECIMAL_CURRENCY: enums::Currency = enums::Currency::BHD;
const ZERO_DECIMAL_CURRENCY: enums::Currency = enums::Currency::JPY;
#[test]
fn amount_conversion_to_float_major_unit() {
let request_amount = MinorUnit::new(999999999);
let required_conversion = FloatMajorUnitForConnector;
// Two decimal currency conversions
let converted_amount = required_conversion
.convert(request_amount, TWO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_amount.0, 9999999.99);
let converted_back_amount = required_conversion
.convert_back(converted_amount, TWO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
// Three decimal currency conversions
let converted_amount = required_conversion
.convert(request_amount, THREE_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_amount.0, 999999.999);
let converted_back_amount = required_conversion
.convert_back(converted_amount, THREE_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
// Zero decimal currency conversions
let converted_amount = required_conversion
.convert(request_amount, ZERO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_amount.0, 999999999.0);
let converted_back_amount = required_conversion
.convert_back(converted_amount, ZERO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
}
#[test]
fn amount_conversion_to_string_major_unit() {
let request_amount = MinorUnit::new(999999999);
let required_conversion = StringMajorUnitForConnector;
// Two decimal currency conversions
let converted_amount_two_decimal_currency = required_conversion
.convert(request_amount, TWO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(
converted_amount_two_decimal_currency.0,
"9999999.99".to_string()
);
let converted_back_amount = required_conversion
.convert_back(converted_amount_two_decimal_currency, TWO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
// Three decimal currency conversions
let converted_amount_three_decimal_currency = required_conversion
.convert(request_amount, THREE_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(
converted_amount_three_decimal_currency.0,
"999999.999".to_string()
);
let converted_back_amount = required_conversion
.convert_back(
converted_amount_three_decimal_currency,
THREE_DECIMAL_CURRENCY,
)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
// Zero decimal currency conversions
let converted_amount = required_conversion
.convert(request_amount, ZERO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_amount.0, "999999999".to_string());
let converted_back_amount = required_conversion
.convert_back(converted_amount, ZERO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
}
#[test]
fn amount_conversion_to_string_minor_unit() {
let request_amount = MinorUnit::new(999999999);
let currency = TWO_DECIMAL_CURRENCY;
let required_conversion = StringMinorUnitForConnector;
let converted_amount = required_conversion
.convert(request_amount, currency)
.unwrap();
assert_eq!(converted_amount.0, "999999999".to_string());
let converted_back_amount = required_conversion
.convert_back(converted_amount, currency)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
}
}
// Charges structs
#[derive(
Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
/// Charge specific fields for controlling the revert of funds from either platform or connected account. Check sub-fields for more details.
pub struct ChargeRefunds {
/// Identifier for charge created for the payment
pub charge_id: String,
/// Toggle for reverting the application fee that was collected for the payment.
/// If set to false, the funds are pulled from the destination account.
pub revert_platform_fee: Option<bool>,
/// Toggle for reverting the transfer that was made during the charge.
/// If set to false, the funds are pulled from the main platform's account.
pub revert_transfer: Option<bool>,
}
crate::impl_to_sql_from_sql_json!(ChargeRefunds);
/// A common type of domain type that can be used for fields that contain a string with restriction of length
#[derive(Debug, Clone, Serialize, Hash, PartialEq, Eq, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub(crate) struct LengthString<const MAX_LENGTH: u16, const MIN_LENGTH: u16>(String);
/// Error generated from violation of constraints for MerchantReferenceId
#[derive(Debug, Error, PartialEq, Eq)]
pub(crate) enum LengthStringError {
#[error("the maximum allowed length for this field is {0}")]
/// Maximum length of string violated
MaxLengthViolated(u16),
#[error("the minimum required length for this field is {0}")]
/// Minimum length of string violated
MinLengthViolated(u16),
}
impl<const MAX_LENGTH: u16, const MIN_LENGTH: u16> LengthString<MAX_LENGTH, MIN_LENGTH> {
/// Generates new [MerchantReferenceId] from the given input string
pub fn from(input_string: Cow<'static, str>) -> Result<Self, LengthStringError> {
let trimmed_input_string = input_string.trim().to_string();
let length_of_input_string = u16::try_from(trimmed_input_string.len())
.map_err(|_| LengthStringError::MaxLengthViolated(MAX_LENGTH))?;
when(length_of_input_string > MAX_LENGTH, || {
Err(LengthStringError::MaxLengthViolated(MAX_LENGTH))
})?;
when(length_of_input_string < MIN_LENGTH, || {
Err(LengthStringError::MinLengthViolated(MIN_LENGTH))
})?;
Ok(Self(trimmed_input_string))
}
pub(crate) fn new_unchecked(input_string: String) -> Self {
Self(input_string)
}
}
impl<'de, const MAX_LENGTH: u16, const MIN_LENGTH: u16> Deserialize<'de>
for LengthString<MAX_LENGTH, MIN_LENGTH>
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let deserialized_string = String::deserialize(deserializer)?;
Self::from(deserialized_string.into()).map_err(serde::de::Error::custom)
}
}
impl<DB, const MAX_LENGTH: u16, const MIN_LENGTH: u16> FromSql<sql_types::Text, DB>
for LengthString<MAX_LENGTH, MIN_LENGTH>
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(bytes)?;
Ok(Self(val))
}
}
impl<DB, const MAX_LENGTH: u16, const MIN_LENGTH: u16> ToSql<sql_types::Text, DB>
for LengthString<MAX_LENGTH, MIN_LENGTH>
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB, const MAX_LENGTH: u16, const MIN_LENGTH: u16> Queryable<sql_types::Text, DB>
for LengthString<MAX_LENGTH, MIN_LENGTH>
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
/// Domain type for description
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub struct Description(LengthString<MAX_DESCRIPTION_LENGTH, 1>);
impl Description {
/// Create a new Description Domain type without any length check from a static str
pub fn from_str_unchecked(input_str: &'static str) -> Self {
Self(LengthString::new_unchecked(input_str.to_owned()))
}
// TODO: Remove this function in future once description in router data is updated to domain type
/// Get the string representation of the description
pub fn get_string_repr(&self) -> &str {
&self.0 .0
}
}
/// Domain type for Statement Descriptor
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub struct StatementDescriptor(LengthString<MAX_STATEMENT_DESCRIPTOR_LENGTH, 1>);
impl<DB> Queryable<sql_types::Text, DB> for Description
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for Description
where
DB: Backend,
LengthString<MAX_DESCRIPTION_LENGTH, 1>: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = LengthString::<MAX_DESCRIPTION_LENGTH, 1>::from_sql(bytes)?;
Ok(Self(val))
}
}
impl<DB> ToSql<sql_types::Text, DB> for Description
where
DB: Backend,
LengthString<MAX_DESCRIPTION_LENGTH, 1>: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> Queryable<sql_types::Text, DB> for StatementDescriptor
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for StatementDescriptor
where
DB: Backend,
LengthString<MAX_STATEMENT_DESCRIPTOR_LENGTH, 1>: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = LengthString::<MAX_STATEMENT_DESCRIPTOR_LENGTH, 1>::from_sql(bytes)?;
Ok(Self(val))
}
}
impl<DB> ToSql<sql_types::Text, DB> for StatementDescriptor
where
DB: Backend,
LengthString<MAX_STATEMENT_DESCRIPTOR_LENGTH, 1>: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
/// Domain type for unified code
#[derive(
Debug, Clone, PartialEq, Eq, Queryable, serde::Deserialize, serde::Serialize, AsExpression,
)]
#[diesel(sql_type = sql_types::Text)]
pub struct UnifiedCode(pub String);
impl TryFrom<String> for UnifiedCode {
type Error = error_stack::Report<ValidationError>;
fn try_from(src: String) -> Result<Self, Self::Error> {
if src.len() > 255 {
Err(report!(ValidationError::InvalidValue {
message: "unified_code's length should not exceed 255 characters".to_string()
}))
} else {
Ok(Self(src))
}
}
}
impl<DB> Queryable<sql_types::Text, DB> for UnifiedCode
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for UnifiedCode
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(bytes)?;
Ok(Self::try_from(val)?)
}
}
impl<DB> ToSql<sql_types::Text, DB> for UnifiedCode
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
/// Domain type for unified messages
#[derive(
Debug, Clone, PartialEq, Eq, Queryable, serde::Deserialize, serde::Serialize, AsExpression,
)]
#[diesel(sql_type = sql_types::Text)]
pub struct UnifiedMessage(pub String);
impl TryFrom<String> for UnifiedMessage {
type Error = error_stack::Report<ValidationError>;
fn try_from(src: String) -> Result<Self, Self::Error> {
if src.len() > 1024 {
Err(report!(ValidationError::InvalidValue {
message: "unified_message's length should not exceed 1024 characters".to_string()
}))
} else {
Ok(Self(src))
}
}
}
impl<DB> Queryable<sql_types::Text, DB> for UnifiedMessage
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for UnifiedMessage
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(bytes)?;
Ok(Self::try_from(val)?)
}
}
impl<DB> ToSql<sql_types::Text, DB> for UnifiedMessage
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
#[cfg(feature = "v2")]
/// Browser information to be used for 3DS 2.0
// If any of the field is PII, then we can make them as secret
#[derive(
ToSchema,
Debug,
Clone,
serde::Deserialize,
serde::Serialize,
Eq,
PartialEq,
diesel::AsExpression,
)]
#[diesel(sql_type = Jsonb)]
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>,
/// Accept-language of the browser
pub accept_language: Option<String>,
/// Identifier of the source that initiated the request.
pub referer: Option<String>,
}
#[cfg(feature = "v2")]
crate::impl_to_sql_from_sql_json!(BrowserInformation);
/// Domain type for connector_transaction_id
/// Maximum length for connector's transaction_id can be 128 characters in HS DB.
/// In case connector's use an identifier whose length exceeds 128 characters,
/// the hash value of such identifiers will be stored as connector_transaction_id.
/// The actual connector's identifier will be stored in a separate column -
/// processor_transaction_data or something with a similar name.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub enum ConnectorTransactionId {
/// Actual transaction identifier
TxnId(String),
/// Hashed value of the transaction identifier
HashedData(String),
}
impl ConnectorTransactionId {
/// Implementation for retrieving the inner identifier
pub fn get_id(&self) -> &String {
match self {
Self::TxnId(id) | Self::HashedData(id) => id,
}
}
/// Implementation for forming ConnectorTransactionId and an optional string to be used for connector_transaction_id and processor_transaction_data
pub fn form_id_and_data(src: String) -> (Self, Option<String>) {
let txn_id = Self::from(src.clone());
match txn_id {
Self::TxnId(_) => (txn_id, None),
Self::HashedData(_) => (txn_id, Some(src)),
}
}
/// Implementation for extracting hashed data
pub fn extract_hashed_data(&self) -> Option<String> {
match self {
Self::TxnId(_) => None,
Self::HashedData(src) => Some(src.clone()),
}
}
/// Implementation for retrieving
pub fn get_txn_id<'a>(
&'a self,
txn_data: Option<&'a String>,
) -> Result<&'a String, error_stack::Report<ValidationError>> {
match (self, txn_data) {
(Self::TxnId(id), _) => Ok(id),
(Self::HashedData(_), Some(id)) => Ok(id),
(Self::HashedData(id), None) => Err(report!(ValidationError::InvalidValue {
message: "processor_transaction_data is empty for HashedData variant".to_string(),
})
.attach_printable(format!(
"processor_transaction_data is empty for connector_transaction_id {id}",
))),
}
}
}
impl From<String> for ConnectorTransactionId {
fn from(src: String) -> Self {
// ID already hashed
if src.starts_with("hs_hash_") {
Self::HashedData(src)
// Hash connector's transaction ID
} else if src.len() > 128 {
let mut hasher = blake3::Hasher::new();
let mut output = [0u8; consts::CONNECTOR_TRANSACTION_ID_HASH_BYTES];
hasher.update(src.as_bytes());
hasher.finalize_xof().fill(&mut output);
let hash = hex::encode(output);
Self::HashedData(format!("hs_hash_{hash}"))
// Default
} else {
Self::TxnId(src)
}
}
}
impl<DB> Queryable<sql_types::Text, DB> for ConnectorTransactionId
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for ConnectorTransactionId
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(bytes)?;
Ok(Self::from(val))
}
}
impl<DB> ToSql<sql_types::Text, DB> for ConnectorTransactionId
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
match self {
Self::HashedData(id) | Self::TxnId(id) => id.to_sql(out),
}
}
}
/// Trait for fetching actual or hashed transaction IDs
pub trait ConnectorTransactionIdTrait {
/// Returns an optional connector transaction ID
fn get_optional_connector_transaction_id(&self) -> Option<&String> {
None
}
/// Returns a connector transaction ID
fn get_connector_transaction_id(&self) -> &String {
self.get_optional_connector_transaction_id()
.unwrap_or_else(|| {
static EMPTY_STRING: String = String::new();
&EMPTY_STRING
})
}
/// Returns an optional connector refund ID
fn get_optional_connector_refund_id(&self) -> Option<&String> {
self.get_optional_connector_transaction_id()
}
}
/// Domain type for PublishableKey
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub struct PublishableKey(LengthString<PUBLISHABLE_KEY_LENGTH, PUBLISHABLE_KEY_LENGTH>);
impl PublishableKey {
/// Create a new PublishableKey Domain type without any length check from a static str
pub fn generate(env_prefix: &'static str) -> Self {
let publishable_key_string = format!("pk_{env_prefix}_{}", uuid::Uuid::now_v7().simple());
Self(LengthString::new_unchecked(publishable_key_string))
}
/// Get the string representation of the PublishableKey
pub fn get_string_repr(&self) -> &str {
&self.0 .0
}
}
impl<DB> Queryable<sql_types::Text, DB> for PublishableKey
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for PublishableKey
where
DB: Backend,
LengthString<PUBLISHABLE_KEY_LENGTH, PUBLISHABLE_KEY_LENGTH>: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = LengthString::<PUBLISHABLE_KEY_LENGTH, PUBLISHABLE_KEY_LENGTH>::from_sql(bytes)?;
Ok(Self(val))
}
}
impl<DB> ToSql<sql_types::Text, DB> for PublishableKey
where
DB: Backend,
LengthString<PUBLISHABLE_KEY_LENGTH, PUBLISHABLE_KEY_LENGTH>: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl_enum_str!(
tag_delimiter = ":",
/// CreatedBy conveys the information about the creator (identifier) as well as the origin or
/// trigger (Api, Jwt) of the record.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum CreatedBy {
/// Api variant
Api {
/// merchant id of creator.
merchant_id: String,
},
/// Jwt variant
Jwt {
/// user id of creator.
user_id: String,
},
/// EmbeddedToken variant
EmbeddedToken {
/// merchant id of creator.
merchant_id: String,
},
}
);
/// Trait for enums created with `impl_enum_str!` macro that have an `Invalid` variant.
/// This trait allows generic functions to check if a parsed enum value is invalid.
pub trait HasInvalidVariant {
/// Returns true if this instance is the `Invalid` variant
fn is_invalid(&self) -> bool;
}
#[allow(missing_docs)]
pub trait TenantConfig: Send + Sync {
fn get_tenant_id(&self) -> &id_type::TenantId;
fn get_schema(&self) -> &str;
fn get_accounts_schema(&self) -> &str;
fn get_redis_key_prefix(&self) -> &str;
fn get_clickhouse_database(&self) -> &str;
}
|
crates__common_utils__src__types__keymanager.rs
|
#![allow(missing_docs)]
use core::fmt;
use base64::Engine;
use masking::{ExposeInterface, PeekInterface, Secret, Strategy, StrongSecret};
#[cfg(feature = "encryption_service")]
use router_env::logger;
#[cfg(feature = "km_forward_x_request_id")]
use router_env::RequestId;
use rustc_hash::FxHashMap;
use serde::{
de::{self, Unexpected, Visitor},
ser, Deserialize, Deserializer, Serialize,
};
use crate::{
consts::BASE64_ENGINE,
crypto::Encryptable,
encryption::Encryption,
errors::{self, CustomResult},
id_type,
transformers::{ForeignFrom, ForeignTryFrom},
};
macro_rules! impl_get_tenant_for_request {
($ty:ident) => {
impl GetKeymanagerTenant for $ty {
fn get_tenant_id(&self, state: &KeyManagerState) -> id_type::TenantId {
match self.identifier {
Identifier::User(_) | Identifier::UserAuth(_) => state.global_tenant_id.clone(),
Identifier::Merchant(_) => state.tenant_id.clone(),
}
}
}
};
}
#[derive(Debug, Clone)]
pub struct KeyManagerState {
pub tenant_id: id_type::TenantId,
pub global_tenant_id: id_type::TenantId,
pub enabled: bool,
pub url: String,
pub client_idle_timeout: Option<u64>,
#[cfg(feature = "km_forward_x_request_id")]
pub request_id: Option<RequestId>,
#[cfg(feature = "keymanager_mtls")]
pub ca: Secret<String>,
#[cfg(feature = "keymanager_mtls")]
pub cert: Secret<String>,
pub infra_values: Option<serde_json::Value>,
pub use_legacy_key_store_decryption: bool,
}
impl KeyManagerState {
/// Creates a mock KeyManagerState with default values for testing.
pub fn mock() -> Self {
Self {
tenant_id: id_type::TenantId::get_default_tenant_id(),
global_tenant_id: id_type::TenantId::get_default_global_tenant_id(),
enabled: Default::default(),
url: String::default(),
client_idle_timeout: Default::default(),
#[cfg(feature = "km_forward_x_request_id")]
request_id: Default::default(),
#[cfg(feature = "keymanager_mtls")]
ca: Default::default(),
#[cfg(feature = "keymanager_mtls")]
cert: Default::default(),
infra_values: Default::default(),
use_legacy_key_store_decryption: false,
}
}
pub fn add_confirm_value_in_infra_values(
&self,
is_confirm_operation: bool,
) -> Option<serde_json::Value> {
self.infra_values.clone().map(|mut infra_values| {
if is_confirm_operation {
infra_values.as_object_mut().map(|obj| {
obj.insert(
"is_confirm_operation".to_string(),
serde_json::Value::Bool(true),
)
});
}
infra_values
})
}
}
pub trait GetKeymanagerTenant {
fn get_tenant_id(&self, state: &KeyManagerState) -> id_type::TenantId;
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
#[serde(tag = "data_identifier", content = "key_identifier")]
pub enum Identifier {
User(String),
Merchant(id_type::MerchantId),
UserAuth(String),
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
pub struct EncryptionCreateRequest {
#[serde(flatten)]
pub identifier: Identifier,
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
pub struct EncryptionTransferRequest {
#[serde(flatten)]
pub identifier: Identifier,
pub key: StrongSecret<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct DataKeyCreateResponse {
#[serde(flatten)]
pub identifier: Identifier,
pub key_version: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct BatchEncryptDataRequest {
#[serde(flatten)]
pub identifier: Identifier,
pub data: DecryptedDataGroup,
}
impl_get_tenant_for_request!(EncryptionCreateRequest);
impl_get_tenant_for_request!(EncryptionTransferRequest);
impl_get_tenant_for_request!(BatchEncryptDataRequest);
impl<S> From<(Secret<Vec<u8>, S>, Identifier)> for EncryptDataRequest
where
S: Strategy<Vec<u8>>,
{
fn from((secret, identifier): (Secret<Vec<u8>, S>, Identifier)) -> Self {
Self {
identifier,
data: DecryptedData(StrongSecret::new(secret.expose())),
}
}
}
impl<S> From<(FxHashMap<String, Secret<Vec<u8>, S>>, Identifier)> for BatchEncryptDataRequest
where
S: Strategy<Vec<u8>>,
{
fn from((map, identifier): (FxHashMap<String, Secret<Vec<u8>, S>>, Identifier)) -> Self {
let group = map
.into_iter()
.map(|(key, value)| (key, DecryptedData(StrongSecret::new(value.expose()))))
.collect();
Self {
identifier,
data: DecryptedDataGroup(group),
}
}
}
impl<S> From<(Secret<String, S>, Identifier)> for EncryptDataRequest
where
S: Strategy<String>,
{
fn from((secret, identifier): (Secret<String, S>, Identifier)) -> Self {
Self {
data: DecryptedData(StrongSecret::new(secret.expose().as_bytes().to_vec())),
identifier,
}
}
}
impl<S> From<(Secret<serde_json::Value, S>, Identifier)> for EncryptDataRequest
where
S: Strategy<serde_json::Value>,
{
fn from((secret, identifier): (Secret<serde_json::Value, S>, Identifier)) -> Self {
Self {
data: DecryptedData(StrongSecret::new(
secret.expose().to_string().as_bytes().to_vec(),
)),
identifier,
}
}
}
impl<S> From<(FxHashMap<String, Secret<serde_json::Value, S>>, Identifier)>
for BatchEncryptDataRequest
where
S: Strategy<serde_json::Value>,
{
fn from(
(map, identifier): (FxHashMap<String, Secret<serde_json::Value, S>>, Identifier),
) -> Self {
let group = map
.into_iter()
.map(|(key, value)| {
(
key,
DecryptedData(StrongSecret::new(
value.expose().to_string().as_bytes().to_vec(),
)),
)
})
.collect();
Self {
data: DecryptedDataGroup(group),
identifier,
}
}
}
impl<S> From<(FxHashMap<String, Secret<String, S>>, Identifier)> for BatchEncryptDataRequest
where
S: Strategy<String>,
{
fn from((map, identifier): (FxHashMap<String, Secret<String, S>>, Identifier)) -> Self {
let group = map
.into_iter()
.map(|(key, value)| {
(
key,
DecryptedData(StrongSecret::new(value.expose().as_bytes().to_vec())),
)
})
.collect();
Self {
data: DecryptedDataGroup(group),
identifier,
}
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct EncryptDataRequest {
#[serde(flatten)]
pub identifier: Identifier,
pub data: DecryptedData,
}
#[derive(Debug, Serialize, serde::Deserialize)]
pub struct DecryptedDataGroup(pub FxHashMap<String, DecryptedData>);
#[derive(Debug, Serialize, Deserialize)]
pub struct BatchEncryptDataResponse {
pub data: EncryptedDataGroup,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct EncryptDataResponse {
pub data: EncryptedData,
}
#[derive(Debug, Serialize, serde::Deserialize)]
pub struct EncryptedDataGroup(pub FxHashMap<String, EncryptedData>);
#[derive(Debug)]
pub struct TransientBatchDecryptDataRequest {
pub identifier: Identifier,
pub data: FxHashMap<String, StrongSecret<Vec<u8>>>,
}
#[derive(Debug)]
pub struct TransientDecryptDataRequest {
pub identifier: Identifier,
pub data: StrongSecret<Vec<u8>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BatchDecryptDataRequest {
#[serde(flatten)]
pub identifier: Identifier,
pub data: FxHashMap<String, StrongSecret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct DecryptDataRequest {
#[serde(flatten)]
pub identifier: Identifier,
pub data: StrongSecret<String>,
}
impl_get_tenant_for_request!(EncryptDataRequest);
impl_get_tenant_for_request!(TransientBatchDecryptDataRequest);
impl_get_tenant_for_request!(TransientDecryptDataRequest);
impl_get_tenant_for_request!(BatchDecryptDataRequest);
impl_get_tenant_for_request!(DecryptDataRequest);
impl<T, S> ForeignFrom<(FxHashMap<String, Secret<T, S>>, BatchEncryptDataResponse)>
for FxHashMap<String, Encryptable<Secret<T, S>>>
where
T: Clone,
S: Strategy<T> + Send,
{
fn foreign_from(
(mut masked_data, response): (FxHashMap<String, Secret<T, S>>, BatchEncryptDataResponse),
) -> Self {
response
.data
.0
.into_iter()
.flat_map(|(k, v)| {
masked_data.remove(&k).map(|inner| {
(
k,
Encryptable::new(inner.clone(), v.data.peek().clone().into()),
)
})
})
.collect()
}
}
impl<T, S> ForeignFrom<(Secret<T, S>, EncryptDataResponse)> for Encryptable<Secret<T, S>>
where
T: Clone,
S: Strategy<T> + Send,
{
fn foreign_from((masked_data, response): (Secret<T, S>, EncryptDataResponse)) -> Self {
Self::new(masked_data, response.data.data.peek().clone().into())
}
}
pub trait DecryptedDataConversion<T: Clone, S: Strategy<T> + Send>: Sized {
fn convert(
value: &DecryptedData,
encryption: Encryption,
) -> CustomResult<Self, errors::CryptoError>;
}
impl<S: Strategy<String> + Send> DecryptedDataConversion<String, S>
for Encryptable<Secret<String, S>>
{
fn convert(
value: &DecryptedData,
encryption: Encryption,
) -> CustomResult<Self, errors::CryptoError> {
let string = String::from_utf8(value.clone().inner().peek().clone()).map_err(|_err| {
#[cfg(feature = "encryption_service")]
logger::error!("Decryption error {:?}", _err);
errors::CryptoError::DecodingFailed
})?;
Ok(Self::new(Secret::new(string), encryption.into_inner()))
}
}
impl<S: Strategy<serde_json::Value> + Send> DecryptedDataConversion<serde_json::Value, S>
for Encryptable<Secret<serde_json::Value, S>>
{
fn convert(
value: &DecryptedData,
encryption: Encryption,
) -> CustomResult<Self, errors::CryptoError> {
let val = serde_json::from_slice(value.clone().inner().peek()).map_err(|_err| {
#[cfg(feature = "encryption_service")]
logger::error!("Decryption error {:?}", _err);
errors::CryptoError::DecodingFailed
})?;
Ok(Self::new(Secret::new(val), encryption.clone().into_inner()))
}
}
impl<S: Strategy<Vec<u8>> + Send> DecryptedDataConversion<Vec<u8>, S>
for Encryptable<Secret<Vec<u8>, S>>
{
fn convert(
value: &DecryptedData,
encryption: Encryption,
) -> CustomResult<Self, errors::CryptoError> {
Ok(Self::new(
Secret::new(value.clone().inner().peek().clone()),
encryption.clone().into_inner(),
))
}
}
impl<T, S> ForeignTryFrom<(Encryption, DecryptDataResponse)> for Encryptable<Secret<T, S>>
where
T: Clone,
S: Strategy<T> + Send,
Self: DecryptedDataConversion<T, S>,
{
type Error = error_stack::Report<errors::CryptoError>;
fn foreign_try_from(
(encrypted_data, response): (Encryption, DecryptDataResponse),
) -> Result<Self, Self::Error> {
Self::convert(&response.data, encrypted_data)
}
}
impl<T, S> ForeignTryFrom<(FxHashMap<String, Encryption>, BatchDecryptDataResponse)>
for FxHashMap<String, Encryptable<Secret<T, S>>>
where
T: Clone,
S: Strategy<T> + Send,
Encryptable<Secret<T, S>>: DecryptedDataConversion<T, S>,
{
type Error = error_stack::Report<errors::CryptoError>;
fn foreign_try_from(
(mut encrypted_data, response): (FxHashMap<String, Encryption>, BatchDecryptDataResponse),
) -> Result<Self, Self::Error> {
response
.data
.0
.into_iter()
.map(|(k, v)| match encrypted_data.remove(&k) {
Some(encrypted) => Ok((k.clone(), Encryptable::convert(&v, encrypted.clone())?)),
None => Err(errors::CryptoError::DecodingFailed)?,
})
.collect()
}
}
impl From<(Encryption, Identifier)> for TransientDecryptDataRequest {
fn from((encryption, identifier): (Encryption, Identifier)) -> Self {
Self {
data: StrongSecret::new(encryption.clone().into_inner().expose()),
identifier,
}
}
}
impl From<(FxHashMap<String, Encryption>, Identifier)> for TransientBatchDecryptDataRequest {
fn from((map, identifier): (FxHashMap<String, Encryption>, Identifier)) -> Self {
let data = map
.into_iter()
.map(|(k, v)| (k, StrongSecret::new(v.clone().into_inner().expose())))
.collect();
Self { data, identifier }
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BatchDecryptDataResponse {
pub data: DecryptedDataGroup,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct DecryptDataResponse {
pub data: DecryptedData,
}
#[derive(Clone, Debug)]
pub struct DecryptedData(StrongSecret<Vec<u8>>);
impl Serialize for DecryptedData {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let data = BASE64_ENGINE.encode(self.0.peek());
serializer.serialize_str(&data)
}
}
impl<'de> Deserialize<'de> for DecryptedData {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct DecryptedDataVisitor;
impl Visitor<'_> for DecryptedDataVisitor {
type Value = DecryptedData;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("string of the format {version}:{base64_encoded_data}'")
}
fn visit_str<E>(self, value: &str) -> Result<DecryptedData, E>
where
E: de::Error,
{
let dec_data = BASE64_ENGINE.decode(value).map_err(|err| {
let err = err.to_string();
E::invalid_value(Unexpected::Str(value), &err.as_str())
})?;
Ok(DecryptedData(dec_data.into()))
}
}
deserializer.deserialize_str(DecryptedDataVisitor)
}
}
impl DecryptedData {
pub fn from_data(data: StrongSecret<Vec<u8>>) -> Self {
Self(data)
}
pub fn inner(self) -> StrongSecret<Vec<u8>> {
self.0
}
}
#[derive(Debug)]
pub struct EncryptedData {
pub data: StrongSecret<Vec<u8>>,
}
impl Serialize for EncryptedData {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let data = String::from_utf8(self.data.peek().clone()).map_err(ser::Error::custom)?;
serializer.serialize_str(data.as_str())
}
}
impl<'de> Deserialize<'de> for EncryptedData {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct EncryptedDataVisitor;
impl Visitor<'_> for EncryptedDataVisitor {
type Value = EncryptedData;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("string of the format {version}:{base64_encoded_data}'")
}
fn visit_str<E>(self, value: &str) -> Result<EncryptedData, E>
where
E: de::Error,
{
Ok(EncryptedData {
data: StrongSecret::new(value.as_bytes().to_vec()),
})
}
}
deserializer.deserialize_str(EncryptedDataVisitor)
}
}
/// A trait which converts the struct to Hashmap required for encryption and back to struct
pub trait ToEncryptable<T, S: Clone, E>: Sized {
/// Serializes the type to a hashmap
fn to_encryptable(self) -> FxHashMap<String, E>;
/// Deserializes the hashmap back to the type
fn from_encryptable(
hashmap: FxHashMap<String, Encryptable<S>>,
) -> CustomResult<T, errors::ParsingError>;
}
|
crates__diesel_models__src__payment_method.rs
|
use std::collections::HashMap;
use common_enums::MerchantStorageScheme;
use common_utils::{
encryption::Encryption,
errors::{CustomResult, ParsingError},
pii,
};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use error_stack::ResultExt;
#[cfg(feature = "v1")]
use masking::ExposeInterface;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
#[cfg(feature = "v1")]
use crate::{enums as storage_enums, schema::payment_methods};
#[cfg(feature = "v2")]
use crate::{enums as storage_enums, schema_v2::payment_methods};
#[cfg(feature = "v1")]
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize,
)]
#[diesel(table_name = payment_methods, primary_key(payment_method_id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentMethod {
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_method_id: String,
#[diesel(deserialize_as = super::OptionalDieselArray<storage_enums::Currency>)]
pub accepted_currency: Option<Vec<storage_enums::Currency>>,
pub scheme: Option<String>,
pub token: Option<String>,
pub cardholder_name: Option<Secret<String>>,
pub issuer_name: Option<String>,
pub issuer_country: Option<String>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub payer_country: Option<Vec<String>>,
pub is_stored: Option<bool>,
pub swift_code: Option<String>,
pub direct_debit_token: Option<String>,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_issuer: Option<String>,
pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<serde_json::Value>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub client_secret: Option<String>,
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
pub network_token_payment_method_data: Option<Encryption>,
pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub vault_type: Option<storage_enums::VaultType>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
pub customer_details: Option<Encryption>,
pub locker_fingerprint_id: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)]
#[diesel(table_name = payment_methods, primary_key(id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentMethod {
pub customer_id: common_utils::id_type::GlobalCustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<CommonMandateReference>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<Secret<String>>,
pub client_secret: Option<String>,
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
pub network_token_payment_method_data: Option<Encryption>,
pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub vault_type: Option<storage_enums::VaultType>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
pub customer_details: Option<Encryption>,
pub locker_fingerprint_id: Option<String>,
pub payment_method_type_v2: Option<storage_enums::PaymentMethod>,
pub payment_method_subtype: Option<storage_enums::PaymentMethodType>,
pub id: common_utils::id_type::GlobalPaymentMethodId,
pub external_vault_token_data: Option<Encryption>,
}
impl PaymentMethod {
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &String {
&self.payment_method_id
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId {
&self.id
}
}
#[cfg(feature = "v1")]
#[derive(
Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize,
)]
#[diesel(table_name = payment_methods)]
pub struct PaymentMethodNew {
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_method_id: String,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_issuer: Option<String>,
pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
pub accepted_currency: Option<Vec<storage_enums::Currency>>,
pub scheme: Option<String>,
pub token: Option<String>,
pub cardholder_name: Option<Secret<String>>,
pub issuer_name: Option<String>,
pub issuer_country: Option<String>,
pub payer_country: Option<Vec<String>>,
pub is_stored: Option<bool>,
pub swift_code: Option<String>,
pub direct_debit_token: Option<String>,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<serde_json::Value>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub client_secret: Option<String>,
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
pub network_token_payment_method_data: Option<Encryption>,
pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub vault_type: Option<storage_enums::VaultType>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
pub customer_details: Option<Encryption>,
pub locker_fingerprint_id: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = payment_methods)]
pub struct PaymentMethodNew {
pub customer_id: common_utils::id_type::GlobalCustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<CommonMandateReference>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub client_secret: Option<String>,
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
pub network_token_payment_method_data: Option<Encryption>,
pub external_vault_token_data: Option<Encryption>,
pub locker_fingerprint_id: Option<String>,
pub payment_method_type_v2: Option<storage_enums::PaymentMethod>,
pub payment_method_subtype: Option<storage_enums::PaymentMethodType>,
pub id: common_utils::id_type::GlobalPaymentMethodId,
pub vault_type: Option<storage_enums::VaultType>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
pub customer_details: Option<Encryption>,
}
impl PaymentMethodNew {
pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) {
self.updated_by = Some(storage_scheme.to_string());
}
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &String {
&self.payment_method_id
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId {
&self.id
}
}
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct TokenizeCoreWorkflow {
pub lookup_key: String,
pub pm: storage_enums::PaymentMethod,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize)]
pub enum PaymentMethodUpdate {
MetadataUpdateAndLastUsed {
metadata: Option<serde_json::Value>,
last_used_at: PrimitiveDateTime,
last_modified_by: Option<String>,
},
UpdatePaymentMethodDataAndLastUsed {
payment_method_data: Option<Encryption>,
scheme: Option<String>,
last_used_at: PrimitiveDateTime,
last_modified_by: Option<String>,
},
PaymentMethodDataUpdate {
payment_method_data: Option<Encryption>,
last_modified_by: Option<String>,
},
LastUsedUpdate {
last_used_at: PrimitiveDateTime,
},
NetworkTransactionIdAndStatusUpdate {
network_transaction_id: Option<String>,
status: Option<storage_enums::PaymentMethodStatus>,
last_modified_by: Option<String>,
},
StatusUpdate {
status: Option<storage_enums::PaymentMethodStatus>,
last_modified_by: Option<String>,
},
AdditionalDataUpdate {
payment_method_data: Option<Encryption>,
status: Option<storage_enums::PaymentMethodStatus>,
locker_id: Option<String>,
payment_method: Option<storage_enums::PaymentMethod>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
payment_method_issuer: Option<String>,
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: Option<Encryption>,
last_modified_by: Option<String>,
},
ConnectorMandateDetailsUpdate {
connector_mandate_details: Option<serde_json::Value>,
last_modified_by: Option<String>,
},
NetworkTokenDataUpdate {
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: Option<Encryption>,
last_modified_by: Option<String>,
},
ConnectorNetworkTransactionIdAndMandateDetailsUpdate {
connector_mandate_details: Option<pii::SecretSerdeValue>,
network_transaction_id: Option<Secret<String>>,
last_modified_by: Option<String>,
},
PaymentMethodBatchUpdate {
connector_mandate_details: Option<pii::SecretSerdeValue>,
network_transaction_id: Option<String>,
status: Option<storage_enums::PaymentMethodStatus>,
payment_method_data: Option<Encryption>,
last_modified_by: Option<String>,
},
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize, Deserialize)]
pub enum PaymentMethodUpdate {
UpdatePaymentMethodDataAndLastUsed {
payment_method_data: Option<Encryption>,
scheme: Option<String>,
last_used_at: PrimitiveDateTime,
last_modified_by: Option<String>,
},
PaymentMethodDataUpdate {
payment_method_data: Option<Encryption>,
last_modified_by: Option<String>,
},
LastUsedUpdate {
last_used_at: PrimitiveDateTime,
},
NetworkTransactionIdAndStatusUpdate {
network_transaction_id: Option<Secret<String>>,
status: Option<storage_enums::PaymentMethodStatus>,
last_modified_by: Option<String>,
},
StatusUpdate {
status: Option<storage_enums::PaymentMethodStatus>,
last_modified_by: Option<String>,
},
GenericUpdate {
payment_method_data: Option<Encryption>,
status: Option<storage_enums::PaymentMethodStatus>,
locker_id: Option<String>,
payment_method_type_v2: Option<storage_enums::PaymentMethod>,
payment_method_subtype: Option<storage_enums::PaymentMethodType>,
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: Option<Encryption>,
locker_fingerprint_id: Option<String>,
connector_mandate_details: Option<CommonMandateReference>,
external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
network_transaction_id: Option<Secret<String>>,
last_modified_by: Option<String>,
},
ConnectorMandateDetailsUpdate {
connector_mandate_details: Option<CommonMandateReference>,
last_modified_by: Option<String>,
},
StatusAndFingerprintUpdate {
status: Option<storage_enums::PaymentMethodStatus>,
locker_fingerprint_id: Option<String>,
last_modified_by: Option<String>,
},
}
impl PaymentMethodUpdate {
pub fn convert_to_payment_method_update(
self,
storage_scheme: MerchantStorageScheme,
) -> PaymentMethodUpdateInternal {
let mut update_internal: PaymentMethodUpdateInternal = self.into();
update_internal.updated_by = Some(storage_scheme.to_string());
update_internal
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = payment_methods)]
pub struct PaymentMethodUpdateInternal {
payment_method_data: Option<Encryption>,
last_used_at: Option<PrimitiveDateTime>,
network_transaction_id: Option<Secret<String>>,
status: Option<storage_enums::PaymentMethodStatus>,
locker_id: Option<String>,
payment_method_type_v2: Option<storage_enums::PaymentMethod>,
connector_mandate_details: Option<CommonMandateReference>,
updated_by: Option<String>,
payment_method_subtype: Option<storage_enums::PaymentMethodType>,
last_modified: PrimitiveDateTime,
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: Option<Encryption>,
locker_fingerprint_id: Option<String>,
external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
last_modified_by: Option<String>,
customer_details: Option<Encryption>,
}
#[cfg(feature = "v2")]
impl PaymentMethodUpdateInternal {
pub fn apply_changeset(self, source: PaymentMethod) -> PaymentMethod {
let Self {
payment_method_data,
last_used_at,
network_transaction_id,
status,
locker_id,
payment_method_type_v2,
connector_mandate_details,
updated_by,
payment_method_subtype,
last_modified,
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
locker_fingerprint_id,
external_vault_source,
last_modified_by,
customer_details,
} = self;
PaymentMethod {
customer_id: source.customer_id,
merchant_id: source.merchant_id,
created_at: source.created_at,
last_modified,
payment_method_data: payment_method_data.or(source.payment_method_data),
locker_id: locker_id.or(source.locker_id),
last_used_at: last_used_at.unwrap_or(source.last_used_at),
connector_mandate_details: connector_mandate_details
.or(source.connector_mandate_details),
customer_acceptance: source.customer_acceptance,
status: status.unwrap_or(source.status),
network_transaction_id: network_transaction_id.or(source.network_transaction_id),
client_secret: source.client_secret,
payment_method_billing_address: source.payment_method_billing_address,
updated_by: updated_by.or(source.updated_by),
locker_fingerprint_id: locker_fingerprint_id.or(source.locker_fingerprint_id),
payment_method_type_v2: payment_method_type_v2.or(source.payment_method_type_v2),
payment_method_subtype: payment_method_subtype.or(source.payment_method_subtype),
id: source.id,
version: source.version,
network_token_requestor_reference_id: network_token_requestor_reference_id
.or(source.network_token_requestor_reference_id),
network_token_locker_id: network_token_locker_id.or(source.network_token_locker_id),
network_token_payment_method_data: network_token_payment_method_data
.or(source.network_token_payment_method_data),
external_vault_source: external_vault_source.or(source.external_vault_source),
external_vault_token_data: source.external_vault_token_data,
vault_type: source.vault_type,
created_by: source.created_by,
last_modified_by: last_modified_by.or(source.last_modified_by),
customer_details: customer_details.or(source.customer_details),
}
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = payment_methods)]
pub struct PaymentMethodUpdateInternal {
metadata: Option<serde_json::Value>,
payment_method_data: Option<Encryption>,
last_used_at: Option<PrimitiveDateTime>,
network_transaction_id: Option<String>,
status: Option<storage_enums::PaymentMethodStatus>,
locker_id: Option<String>,
network_token_requestor_reference_id: Option<String>,
payment_method: Option<storage_enums::PaymentMethod>,
connector_mandate_details: Option<serde_json::Value>,
updated_by: Option<String>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
payment_method_issuer: Option<String>,
last_modified: PrimitiveDateTime,
network_token_locker_id: Option<String>,
network_token_payment_method_data: Option<Encryption>,
scheme: Option<String>,
last_modified_by: Option<String>,
customer_details: Option<Encryption>,
}
#[cfg(feature = "v1")]
impl PaymentMethodUpdateInternal {
pub fn apply_changeset(self, source: PaymentMethod) -> PaymentMethod {
let Self {
metadata,
payment_method_data,
last_used_at,
network_transaction_id,
status,
locker_id,
network_token_requestor_reference_id,
payment_method,
connector_mandate_details,
updated_by,
payment_method_type,
payment_method_issuer,
last_modified,
network_token_locker_id,
network_token_payment_method_data,
scheme,
last_modified_by,
customer_details,
} = self;
PaymentMethod {
customer_id: source.customer_id,
merchant_id: source.merchant_id,
payment_method_id: source.payment_method_id,
accepted_currency: source.accepted_currency,
scheme: scheme.or(source.scheme),
token: source.token,
cardholder_name: source.cardholder_name,
issuer_name: source.issuer_name,
issuer_country: source.issuer_country,
payer_country: source.payer_country,
is_stored: source.is_stored,
swift_code: source.swift_code,
direct_debit_token: source.direct_debit_token,
created_at: source.created_at,
locker_fingerprint_id: source.locker_fingerprint_id,
last_modified,
payment_method: payment_method.or(source.payment_method),
payment_method_type: payment_method_type.or(source.payment_method_type),
payment_method_issuer: payment_method_issuer.or(source.payment_method_issuer),
payment_method_issuer_code: source.payment_method_issuer_code,
metadata: metadata.map_or(source.metadata, |v| Some(v.into())),
payment_method_data: payment_method_data.or(source.payment_method_data),
locker_id: locker_id.or(source.locker_id),
last_used_at: last_used_at.unwrap_or(source.last_used_at),
connector_mandate_details: connector_mandate_details
.or(source.connector_mandate_details),
customer_acceptance: source.customer_acceptance,
status: status.unwrap_or(source.status),
network_transaction_id: network_transaction_id.or(source.network_transaction_id),
client_secret: source.client_secret,
payment_method_billing_address: source.payment_method_billing_address,
updated_by: updated_by.or(source.updated_by),
version: source.version,
network_token_requestor_reference_id: network_token_requestor_reference_id
.or(source.network_token_requestor_reference_id),
network_token_locker_id: network_token_locker_id.or(source.network_token_locker_id),
network_token_payment_method_data: network_token_payment_method_data
.or(source.network_token_payment_method_data),
external_vault_source: source.external_vault_source,
vault_type: source.vault_type,
created_by: source.created_by,
last_modified_by: last_modified_by.or(source.last_modified_by),
customer_details: customer_details.or(source.customer_details),
}
}
}
#[cfg(feature = "v1")]
impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
fn from(payment_method_update: PaymentMethodUpdate) -> Self {
match payment_method_update {
PaymentMethodUpdate::MetadataUpdateAndLastUsed {
metadata,
last_used_at,
last_modified_by,
} => Self {
metadata,
payment_method_data: None,
last_used_at: Some(last_used_at),
network_transaction_id: None,
status: None,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
customer_details: None,
},
PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data,
last_modified_by,
} => Self {
metadata: None,
payment_method_data,
last_used_at: None,
network_transaction_id: None,
status: None,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
customer_details: None,
},
PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
metadata: None,
payment_method_data: None,
last_used_at: Some(last_used_at),
network_transaction_id: None,
status: None,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
last_modified_by: None,
customer_details: None,
},
PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed {
payment_method_data,
scheme,
last_used_at,
last_modified_by,
} => Self {
metadata: None,
payment_method_data,
last_used_at: Some(last_used_at),
network_transaction_id: None,
status: None,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme,
last_modified_by,
customer_details: None,
},
PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
status,
last_modified_by,
} => Self {
metadata: None,
payment_method_data: None,
last_used_at: None,
network_transaction_id,
status,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
customer_details: None,
},
PaymentMethodUpdate::StatusUpdate {
status,
last_modified_by,
} => Self {
metadata: None,
payment_method_data: None,
last_used_at: None,
network_transaction_id: None,
status,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
customer_details: None,
},
PaymentMethodUpdate::AdditionalDataUpdate {
payment_method_data,
status,
locker_id,
network_token_requestor_reference_id,
payment_method,
payment_method_type,
payment_method_issuer,
network_token_locker_id,
network_token_payment_method_data,
last_modified_by,
} => Self {
metadata: None,
payment_method_data,
last_used_at: None,
network_transaction_id: None,
status,
locker_id,
network_token_requestor_reference_id,
payment_method,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer,
payment_method_type,
last_modified: common_utils::date_time::now(),
network_token_locker_id,
network_token_payment_method_data,
scheme: None,
last_modified_by,
customer_details: None,
},
PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details,
last_modified_by,
} => Self {
metadata: None,
payment_method_data: None,
last_used_at: None,
status: None,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details,
network_transaction_id: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
customer_details: None,
},
PaymentMethodUpdate::NetworkTokenDataUpdate {
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
last_modified_by,
} => Self {
metadata: None,
payment_method_data: None,
last_used_at: None,
status: None,
locker_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_transaction_id: None,
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
scheme: None,
last_modified_by,
customer_details: None,
},
PaymentMethodUpdate::ConnectorNetworkTransactionIdAndMandateDetailsUpdate {
connector_mandate_details,
network_transaction_id,
last_modified_by,
} => Self {
connector_mandate_details: connector_mandate_details
.map(|mandate_details| mandate_details.expose()),
network_transaction_id: network_transaction_id.map(|txn_id| txn_id.expose()),
last_modified: common_utils::date_time::now(),
status: None,
metadata: None,
payment_method_data: None,
last_used_at: None,
locker_id: None,
payment_method: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
network_token_requestor_reference_id: None,
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
customer_details: None,
},
PaymentMethodUpdate::PaymentMethodBatchUpdate {
connector_mandate_details,
network_transaction_id,
status,
payment_method_data,
last_modified_by,
} => Self {
metadata: None,
last_used_at: None,
status,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: connector_mandate_details
.map(|mandate_details| mandate_details.expose()),
network_transaction_id,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
payment_method_data,
last_modified_by,
customer_details: None,
},
}
}
}
#[cfg(feature = "v2")]
impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
fn from(payment_method_update: PaymentMethodUpdate) -> Self {
match payment_method_update {
PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data,
last_modified_by,
} => Self {
payment_method_data,
last_used_at: None,
network_transaction_id: None,
status: None,
locker_id: None,
payment_method_type_v2: None,
connector_mandate_details: None,
updated_by: None,
payment_method_subtype: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_requestor_reference_id: None,
network_token_payment_method_data: None,
locker_fingerprint_id: None,
external_vault_source: None,
last_modified_by,
customer_details: None,
},
PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
payment_method_data: None,
last_used_at: Some(last_used_at),
network_transaction_id: None,
status: None,
locker_id: None,
payment_method_type_v2: None,
connector_mandate_details: None,
updated_by: None,
payment_method_subtype: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_requestor_reference_id: None,
network_token_payment_method_data: None,
locker_fingerprint_id: None,
external_vault_source: None,
last_modified_by: None,
customer_details: None,
},
PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed {
payment_method_data,
last_used_at,
last_modified_by,
..
} => Self {
payment_method_data,
last_used_at: Some(last_used_at),
network_transaction_id: None,
status: None,
locker_id: None,
payment_method_type_v2: None,
connector_mandate_details: None,
updated_by: None,
payment_method_subtype: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_requestor_reference_id: None,
network_token_payment_method_data: None,
locker_fingerprint_id: None,
external_vault_source: None,
last_modified_by,
customer_details: None,
},
PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
status,
last_modified_by,
} => Self {
payment_method_data: None,
last_used_at: None,
network_transaction_id,
status,
locker_id: None,
payment_method_type_v2: None,
connector_mandate_details: None,
updated_by: None,
payment_method_subtype: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_requestor_reference_id: None,
network_token_payment_method_data: None,
locker_fingerprint_id: None,
external_vault_source: None,
last_modified_by,
customer_details: None,
},
PaymentMethodUpdate::StatusUpdate {
status,
last_modified_by,
} => Self {
payment_method_data: None,
last_used_at: None,
network_transaction_id: None,
status,
locker_id: None,
payment_method_type_v2: None,
connector_mandate_details: None,
updated_by: None,
payment_method_subtype: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_requestor_reference_id: None,
network_token_payment_method_data: None,
locker_fingerprint_id: None,
external_vault_source: None,
last_modified_by,
customer_details: None,
},
PaymentMethodUpdate::GenericUpdate {
payment_method_data,
status,
locker_id,
payment_method_type_v2,
payment_method_subtype,
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
locker_fingerprint_id,
connector_mandate_details,
external_vault_source,
network_transaction_id,
last_modified_by,
} => Self {
payment_method_data,
last_used_at: None,
status,
locker_id,
payment_method_type_v2,
connector_mandate_details,
updated_by: None,
payment_method_subtype,
last_modified: common_utils::date_time::now(),
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
locker_fingerprint_id,
external_vault_source,
network_transaction_id,
last_modified_by,
customer_details: None,
},
PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details,
last_modified_by,
} => Self {
payment_method_data: None,
last_used_at: None,
status: None,
locker_id: None,
payment_method_type_v2: None,
connector_mandate_details,
network_transaction_id: None,
updated_by: None,
payment_method_subtype: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_requestor_reference_id: None,
network_token_payment_method_data: None,
locker_fingerprint_id: None,
external_vault_source: None,
last_modified_by,
customer_details: None,
},
PaymentMethodUpdate::StatusAndFingerprintUpdate {
status,
locker_fingerprint_id,
last_modified_by,
} => Self {
payment_method_data: None,
last_used_at: None,
network_transaction_id: None,
status,
locker_id: None,
payment_method_type_v2: None,
connector_mandate_details: None,
updated_by: None,
payment_method_subtype: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_requestor_reference_id: None,
network_token_payment_method_data: None,
locker_fingerprint_id,
external_vault_source: None,
last_modified_by,
customer_details: None,
},
}
}
}
#[cfg(feature = "v1")]
impl From<&PaymentMethodNew> for PaymentMethod {
fn from(payment_method_new: &PaymentMethodNew) -> Self {
Self {
customer_id: payment_method_new.customer_id.clone(),
merchant_id: payment_method_new.merchant_id.clone(),
payment_method_id: payment_method_new.payment_method_id.clone(),
locker_id: payment_method_new.locker_id.clone(),
network_token_requestor_reference_id: payment_method_new
.network_token_requestor_reference_id
.clone(),
accepted_currency: payment_method_new.accepted_currency.clone(),
scheme: payment_method_new.scheme.clone(),
token: payment_method_new.token.clone(),
cardholder_name: payment_method_new.cardholder_name.clone(),
issuer_name: payment_method_new.issuer_name.clone(),
issuer_country: payment_method_new.issuer_country.clone(),
payer_country: payment_method_new.payer_country.clone(),
is_stored: payment_method_new.is_stored,
swift_code: payment_method_new.swift_code.clone(),
direct_debit_token: payment_method_new.direct_debit_token.clone(),
created_at: payment_method_new.created_at,
last_modified: payment_method_new.last_modified,
payment_method: payment_method_new.payment_method,
payment_method_type: payment_method_new.payment_method_type,
payment_method_issuer: payment_method_new.payment_method_issuer.clone(),
payment_method_issuer_code: payment_method_new.payment_method_issuer_code,
metadata: payment_method_new.metadata.clone(),
payment_method_data: payment_method_new.payment_method_data.clone(),
last_used_at: payment_method_new.last_used_at,
connector_mandate_details: payment_method_new.connector_mandate_details.clone(),
customer_acceptance: payment_method_new.customer_acceptance.clone(),
status: payment_method_new.status,
network_transaction_id: payment_method_new.network_transaction_id.clone(),
client_secret: payment_method_new.client_secret.clone(),
updated_by: payment_method_new.updated_by.clone(),
payment_method_billing_address: payment_method_new
.payment_method_billing_address
.clone(),
version: payment_method_new.version,
network_token_locker_id: payment_method_new.network_token_locker_id.clone(),
network_token_payment_method_data: payment_method_new
.network_token_payment_method_data
.clone(),
external_vault_source: payment_method_new.external_vault_source.clone(),
vault_type: payment_method_new.vault_type,
created_by: payment_method_new.created_by.clone(),
last_modified_by: payment_method_new.last_modified_by.clone(),
customer_details: payment_method_new.customer_details.clone(),
locker_fingerprint_id: payment_method_new.locker_fingerprint_id.clone(),
}
}
}
#[cfg(feature = "v2")]
impl From<&PaymentMethodNew> for PaymentMethod {
fn from(payment_method_new: &PaymentMethodNew) -> Self {
Self {
customer_id: payment_method_new.customer_id.clone(),
merchant_id: payment_method_new.merchant_id.clone(),
locker_id: payment_method_new.locker_id.clone(),
created_at: payment_method_new.created_at,
last_modified: payment_method_new.last_modified,
payment_method_data: payment_method_new.payment_method_data.clone(),
last_used_at: payment_method_new.last_used_at,
connector_mandate_details: payment_method_new.connector_mandate_details.clone(),
customer_acceptance: payment_method_new.customer_acceptance.clone(),
status: payment_method_new.status,
network_transaction_id: payment_method_new
.network_transaction_id
.clone()
.map(Secret::new),
client_secret: payment_method_new.client_secret.clone(),
updated_by: payment_method_new.updated_by.clone(),
payment_method_billing_address: payment_method_new
.payment_method_billing_address
.clone(),
locker_fingerprint_id: payment_method_new.locker_fingerprint_id.clone(),
payment_method_type_v2: payment_method_new.payment_method_type_v2,
payment_method_subtype: payment_method_new.payment_method_subtype,
id: payment_method_new.id.clone(),
version: payment_method_new.version,
network_token_requestor_reference_id: payment_method_new
.network_token_requestor_reference_id
.clone(),
network_token_locker_id: payment_method_new.network_token_locker_id.clone(),
network_token_payment_method_data: payment_method_new
.network_token_payment_method_data
.clone(),
external_vault_source: None,
external_vault_token_data: payment_method_new.external_vault_token_data.clone(),
vault_type: payment_method_new.vault_type,
created_by: payment_method_new.created_by.clone(),
last_modified_by: payment_method_new.last_modified_by.clone(),
customer_details: payment_method_new.customer_details.clone(),
}
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
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>,
pub mandate_metadata: Option<pii::SecretSerdeValue>,
pub connector_mandate_status: Option<common_enums::ConnectorMandateStatus>,
pub connector_mandate_request_reference_id: Option<String>,
pub connector_customer_id: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConnectorTokenReferenceRecord {
pub connector_token: String,
pub payment_method_subtype: Option<common_enums::PaymentMethodType>,
pub original_payment_authorized_amount: Option<common_utils::types::MinorUnit>,
pub original_payment_authorized_currency: Option<common_enums::Currency>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_token_status: common_enums::ConnectorTokenStatus,
pub connector_token_request_reference_id: Option<String>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct PaymentsMandateReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>,
);
#[cfg(feature = "v1")]
impl std::ops::Deref for PaymentsMandateReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(feature = "v1")]
impl std::ops::DerefMut for PaymentsMandateReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct PaymentsTokenReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>,
);
#[cfg(feature = "v2")]
impl std::ops::Deref for PaymentsTokenReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(feature = "v2")]
impl std::ops::DerefMut for PaymentsTokenReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v1")]
common_utils::impl_to_sql_from_sql_json!(PaymentsMandateReference);
#[cfg(feature = "v2")]
common_utils::impl_to_sql_from_sql_json!(PaymentsTokenReference);
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct PayoutsMandateReferenceRecord {
pub transfer_method_id: Option<String>,
pub connector_customer_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct PayoutsMandateReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>,
);
impl std::ops::Deref for PayoutsMandateReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for PayoutsMandateReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct CommonMandateReference {
pub payments: Option<PaymentsMandateReference>,
pub payouts: Option<PayoutsMandateReference>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct CommonMandateReference {
pub payments: Option<PaymentsTokenReference>,
pub payouts: Option<PayoutsMandateReference>,
}
impl CommonMandateReference {
pub fn get_mandate_details_value(&self) -> CustomResult<serde_json::Value, ParsingError> {
let mut payments = self
.payments
.as_ref()
.map_or_else(|| Ok(serde_json::json!({})), serde_json::to_value)
.change_context(ParsingError::StructParseFailure("payment mandate details"))?;
self.payouts
.as_ref()
.map(|payouts_mandate| {
serde_json::to_value(payouts_mandate).map(|payouts_mandate_value| {
payments.as_object_mut().map(|payments_object| {
payments_object.insert("payouts".to_string(), payouts_mandate_value);
})
})
})
.transpose()
.change_context(ParsingError::StructParseFailure("payout mandate details"))?;
Ok(payments)
}
#[cfg(feature = "v2")]
/// Insert a new payment token reference for the given connector_id
pub fn insert_payment_token_reference_record(
&mut self,
connector_id: &common_utils::id_type::MerchantConnectorAccountId,
record: ConnectorTokenReferenceRecord,
) {
match self.payments {
Some(ref mut payments_reference) => {
payments_reference.insert(connector_id.clone(), record);
}
None => {
let mut payments_reference = HashMap::new();
payments_reference.insert(connector_id.clone(), record);
self.payments = Some(PaymentsTokenReference(payments_reference));
}
}
}
}
impl diesel::serialize::ToSql<diesel::sql_types::Jsonb, diesel::pg::Pg> for CommonMandateReference {
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>,
) -> diesel::serialize::Result {
let payments = self.get_mandate_details_value()?;
<serde_json::Value as diesel::serialize::ToSql<
diesel::sql_types::Jsonb,
diesel::pg::Pg,
>>::to_sql(&payments, &mut out.reborrow())
}
}
#[cfg(feature = "v1")]
impl<DB: diesel::backend::Backend> diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB>
for CommonMandateReference
where
serde_json::Value: diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
let value = <serde_json::Value as diesel::deserialize::FromSql<
diesel::sql_types::Jsonb,
DB,
>>::from_sql(bytes)?;
let payments_data = value
.clone()
.as_object_mut()
.map(|obj| {
obj.remove("payouts");
serde_json::from_value::<PaymentsMandateReference>(serde_json::Value::Object(
obj.clone(),
))
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payments data: {}", err);
})
.change_context(ParsingError::StructParseFailure(
"Failed to parse payments data",
))
})
.transpose()?;
let payouts_data = serde_json::from_value::<Option<Self>>(value)
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payouts data: {}", err);
})
.change_context(ParsingError::StructParseFailure(
"Failed to parse payouts data",
))
.map(|optional_common_mandate_details| {
optional_common_mandate_details
.and_then(|common_mandate_details| common_mandate_details.payouts)
})?;
Ok(Self {
payments: payments_data,
payouts: payouts_data,
})
}
}
#[cfg(feature = "v2")]
impl<DB: diesel::backend::Backend> diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB>
for CommonMandateReference
where
serde_json::Value: diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
let value = <serde_json::Value as diesel::deserialize::FromSql<
diesel::sql_types::Jsonb,
DB,
>>::from_sql(bytes)?;
let payments_data = value
.clone()
.as_object_mut()
.map(|obj| {
obj.remove("payouts");
serde_json::from_value::<PaymentsTokenReference>(serde_json::Value::Object(
obj.clone(),
))
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payments data: {}", err);
})
.change_context(ParsingError::StructParseFailure(
"Failed to parse payments data",
))
})
.transpose()?;
let payouts_data = serde_json::from_value::<Option<Self>>(value)
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payouts data: {}", err);
})
.change_context(ParsingError::StructParseFailure(
"Failed to parse payouts data",
))
.map(|optional_common_mandate_details| {
optional_common_mandate_details
.and_then(|common_mandate_details| common_mandate_details.payouts)
})?;
Ok(Self {
payments: payments_data,
payouts: payouts_data,
})
}
}
#[cfg(feature = "v1")]
impl From<PaymentsMandateReference> for CommonMandateReference {
fn from(payment_reference: PaymentsMandateReference) -> Self {
Self {
payments: Some(payment_reference),
payouts: None,
}
}
}
|
crates__hyperswitch_connectors__src__connectors__aci.rs
|
mod aci_result_codes;
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::IncomingWebhookEvent;
use common_enums::enums;
use common_utils::{
crypto,
errors::{CryptoError, CustomResult},
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{
PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, PaymentsVoidType,
RefundExecuteType, Response,
},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},
};
use masking::{Mask, PeekInterface};
use ring::aead::{self, UnboundKey};
use transformers as aci;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{
convert_amount, is_mandate_supported, PaymentMethodDataType, PaymentsAuthorizeRequestData,
},
};
#[derive(Clone)]
pub struct Aci {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Aci {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl ConnectorCommon for Aci {
fn id(&self) -> &'static str {
"aci"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.aci.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = aci::AciAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", auth.api_key.peek()).into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: aci::AciErrorResponse = res
.response
.parse_struct("AciErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.result.code,
message: response.result.description,
reason: response.result.parameter_errors.map(|errors| {
errors
.into_iter()
.map(|error_description| {
format!(
"Field is {} and the message is {}",
error_description.name, error_description.message
)
})
.collect::<Vec<String>>()
.join("; ")
}),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Aci {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]);
is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl api::Payment for Aci {}
impl api::PaymentAuthorize for Aci {}
impl api::PaymentSync for Aci {}
impl api::PaymentVoid for Aci {}
impl api::PaymentCapture for Aci {}
impl api::PaymentSession for Aci {}
impl api::ConnectorAccessToken for Aci {}
impl api::PaymentToken for Aci {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Aci
{
fn build_request(
&self,
_req: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "Payment method tokenization not supported".to_string(),
connector: "ACI",
}
.into())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Aci {
fn build_request(
&self,
_req: &RouterData<Session, PaymentsSessionData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "Payment sessions not supported".to_string(),
connector: "ACI",
}
.into())
}
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Aci {
fn build_request(
&self,
_req: &RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "Access token authentication not supported".to_string(),
connector: "ACI",
}
.into())
}
}
impl api::MandateSetup for Aci {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Aci {
fn get_headers(
&self,
req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.common_get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v1/registrations", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = aci::AciMandateRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&self.get_url(req, connectors)?)
.attach_default_headers()
.headers(self.get_headers(req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
errors::ConnectorError,
> {
let response: aci::AciMandateResponse = res
.response
.parse_struct("AciMandateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Aci {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PaymentsCaptureType::get_content_type(self)
.to_string()
.into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"v1/payments/",
req.request.connector_transaction_id,
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = aci::AciRouterData::from((amount, req));
let connector_req = aci::AciCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
.set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: aci::AciCaptureResponse = res
.response
.parse_struct("AciCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Aci {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PaymentsSyncType::get_content_type(self).to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth = aci::AciAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
"{}{}{}{}{}",
self.base_url(connectors),
"v1/payments/",
req.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
"?entityId=",
auth.entity_id.peek()
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError>
where
PaymentsSyncData: Clone,
PaymentsResponseData: Clone,
{
let response: aci::AciPaymentsResponse =
res.response
.parse_struct("AciPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Aci {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
match req.request.connector_mandate_id() {
Some(mandate_id) => Ok(format!(
"{}v1/registrations/{}/payments",
self.base_url(connectors),
mandate_id
)),
_ => Ok(format!("{}{}", self.base_url(connectors), "v1/payments")),
}
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = aci::AciRouterData::from((amount, req));
let connector_req = aci::AciPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: aci::AciPaymentsResponse =
res.response
.parse_struct("AciPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Aci {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = &req.request.connector_transaction_id;
Ok(format!("{}v1/payments/{}", self.base_url(connectors), id))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = aci::AciCancelRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: aci::AciPaymentsResponse =
res.response
.parse_struct("AciPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::Refund for Aci {}
impl api::RefundExecute for Aci {}
impl api::RefundSync for Aci {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Aci {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
RefundExecuteType::get_content_type(self).to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}v1/payments/{}",
self.base_url(connectors),
connector_payment_id,
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = aci::AciRouterData::from((amount, req));
let connector_req = aci::AciRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: aci::AciRefundResponse = res
.response
.parse_struct("AciRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Aci {}
/// Decrypts an AES-256-GCM encrypted payload where the IV, auth tag, and ciphertext
/// are provided separately as hex strings. This is specifically tailored for ACI webhooks.
///
/// # Arguments
/// * `hex_key`: The encryption key as a hex string (must decode to 32 bytes).
/// * `hex_iv`: The initialization vector (nonce) as a hex string (must decode to 12 bytes).
/// * `hex_auth_tag`: The authentication tag as a hex string (must decode to 16 bytes).
/// * `hex_encrypted_body`: The encrypted payload as a hex string.
fn decrypt_aci_webhook_payload(
hex_key: &str,
hex_iv: &str,
hex_auth_tag: &str,
hex_encrypted_body: &str,
) -> CustomResult<Vec<u8>, CryptoError> {
let key_bytes = hex::decode(hex_key)
.change_context(CryptoError::DecodingFailed)
.attach_printable("Failed to decode hex key")?;
let iv_bytes = hex::decode(hex_iv)
.change_context(CryptoError::DecodingFailed)
.attach_printable("Failed to decode hex IV")?;
let auth_tag_bytes = hex::decode(hex_auth_tag)
.change_context(CryptoError::DecodingFailed)
.attach_printable("Failed to decode hex auth tag")?;
let encrypted_body_bytes = hex::decode(hex_encrypted_body)
.change_context(CryptoError::DecodingFailed)
.attach_printable("Failed to decode hex encrypted body")?;
if key_bytes.len() != 32 {
return Err(CryptoError::InvalidKeyLength)
.attach_printable("Key must be 32 bytes for AES-256-GCM");
}
if iv_bytes.len() != aead::NONCE_LEN {
return Err(CryptoError::InvalidIvLength)
.attach_printable(format!("IV must be {} bytes for AES-GCM", aead::NONCE_LEN));
}
if auth_tag_bytes.len() != 16 {
return Err(CryptoError::InvalidTagLength)
.attach_printable("Auth tag must be 16 bytes for AES-256-GCM");
}
let unbound_key = UnboundKey::new(&aead::AES_256_GCM, &key_bytes)
.change_context(CryptoError::DecodingFailed)
.attach_printable("Failed to create unbound key")?;
let less_safe_key = aead::LessSafeKey::new(unbound_key);
let nonce_arr: [u8; aead::NONCE_LEN] = iv_bytes
.as_slice()
.try_into()
.map_err(|_| CryptoError::InvalidIvLength)
.attach_printable_lazy(|| {
format!(
"IV length is {} but expected {}",
iv_bytes.len(),
aead::NONCE_LEN
)
})?;
let nonce = aead::Nonce::assume_unique_for_key(nonce_arr);
let mut ciphertext_and_tag = encrypted_body_bytes;
ciphertext_and_tag.extend_from_slice(&auth_tag_bytes);
less_safe_key
.open_in_place(nonce, aead::Aad::empty(), &mut ciphertext_and_tag)
.change_context(CryptoError::DecodingFailed)
.attach_printable("Failed to decrypt payload using LessSafeKey")?;
let original_ciphertext_len = ciphertext_and_tag.len() - auth_tag_bytes.len();
ciphertext_and_tag.truncate(original_ciphertext_len);
Ok(ciphertext_and_tag)
}
#[async_trait::async_trait]
impl IncomingWebhook for Aci {
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let header_value_str = request
.headers
.get("X-Authentication-Tag")
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)
.attach_printable("Missing X-Authentication-Tag header")?
.to_str()
.map_err(|_| errors::ConnectorError::WebhookSignatureNotFound)
.attach_printable("Invalid X-Authentication-Tag header value (not UTF-8)")?;
Ok(header_value_str.as_bytes().to_vec())
}
fn get_webhook_source_verification_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let webhook_secret_str = String::from_utf8(connector_webhook_secrets.secret.to_vec())
.map_err(|_| errors::ConnectorError::WebhookVerificationSecretInvalid)
.attach_printable("ACI webhook secret is not a valid UTF-8 string")?;
let iv_hex_str = request
.headers
.get("X-Initialization-Vector")
.ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Missing X-Initialization-Vector header")?
.to_str()
.map_err(|_| errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Invalid X-Initialization-Vector header value (not UTF-8)")?;
let auth_tag_hex_str = request
.headers
.get("X-Authentication-Tag")
.ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Missing X-Authentication-Tag header")?
.to_str()
.map_err(|_| errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Invalid X-Authentication-Tag header value (not UTF-8)")?;
let encrypted_body_hex = String::from_utf8(request.body.to_vec())
.map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed)
.attach_printable(
"Failed to read encrypted body as UTF-8 string for verification message",
)?;
decrypt_aci_webhook_payload(
&webhook_secret_str,
iv_hex_str,
auth_tag_hex_str,
&encrypted_body_hex,
)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Failed to decrypt ACI webhook payload for verification")
}
fn get_webhook_object_reference_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let aci_notification: aci::AciWebhookNotification =
serde_json::from_slice(request.body)
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)
.attach_printable("Failed to deserialize ACI webhook notification for ID extraction (expected decrypted payload)")?;
let id_value_str = aci_notification
.payload
.get("id")
.and_then(|id| id.as_str())
.ok_or_else(|| {
report!(errors::ConnectorError::WebhookResourceObjectNotFound)
.attach_printable("Missing 'id' in webhook payload for ID extraction")
})?;
let payment_type_str = aci_notification
.payload
.get("paymentType")
.and_then(|pt| pt.as_str());
if payment_type_str.is_some_and(|pt| pt.to_uppercase() == "RF") {
Ok(api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(id_value_str.to_string()),
))
} else {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
id_value_str.to_string(),
),
))
}
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let aci_notification: aci::AciWebhookNotification =
serde_json::from_slice(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)
.attach_printable("Failed to deserialize ACI webhook notification for event type (expected decrypted payload)")?;
match aci_notification.event_type {
aci::AciWebhookEventType::Payment => {
let payment_payload: aci::AciPaymentWebhookPayload =
serde_json::from_value(aci_notification.payload)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)
.attach_printable("Could not deserialize ACI payment webhook payload for event type determination")?;
let code = &payment_payload.result.code;
if aci_result_codes::SUCCESSFUL_CODES.contains(&code.as_str()) {
if payment_payload.payment_type.to_uppercase() == "RF" {
Ok(IncomingWebhookEvent::RefundSuccess)
} else {
Ok(IncomingWebhookEvent::PaymentIntentSuccess)
}
} else if aci_result_codes::PENDING_CODES.contains(&code.as_str()) {
if payment_payload.payment_type.to_uppercase() == "RF" {
Ok(IncomingWebhookEvent::EventNotSupported)
} else {
Ok(IncomingWebhookEvent::PaymentIntentProcessing)
}
} else if aci_result_codes::FAILURE_CODES.contains(&code.as_str()) {
if payment_payload.payment_type.to_uppercase() == "RF" {
Ok(IncomingWebhookEvent::RefundFailure)
} else {
Ok(IncomingWebhookEvent::PaymentIntentFailure)
}
} else {
Ok(IncomingWebhookEvent::EventNotSupported)
}
}
}
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let aci_notification: aci::AciWebhookNotification =
serde_json::from_slice(request.body)
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)
.attach_printable("Failed to deserialize ACI webhook notification for resource object (expected decrypted payload)")?;
match aci_notification.event_type {
aci::AciWebhookEventType::Payment => {
let payment_payload: aci::AciPaymentWebhookPayload =
serde_json::from_value(aci_notification.payload)
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)
.attach_printable("Failed to deserialize ACI payment webhook payload")?;
Ok(Box::new(payment_payload))
}
}
}
}
static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
];
let supported_card_networks = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Maestro,
];
let mut aci_supported_payment_methods = SupportedPaymentMethods::new();
aci_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::MbWay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
aci_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::AliPay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
aci_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_networks.clone(),
}
}),
),
},
);
aci_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_networks.clone(),
}
}),
),
},
);
aci_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Eps,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
aci_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Eft,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
aci_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Ideal,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
aci_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Giropay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
aci_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Sofort,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
aci_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Interac,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
aci_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Przelewy24,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
aci_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Trustly,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
aci_supported_payment_methods.add(
enums::PaymentMethod::PayLater,
enums::PaymentMethodType::Klarna,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
aci_supported_payment_methods
});
static ACI_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "ACI",
description:
"ACI Payments delivers secure, real-time electronic payment solutions for businesses, banks, and governments, enabling seamless transactions across channels.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static ACI_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Aci {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&ACI_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*ACI_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&ACI_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__aci__transformers.rs
|
use std::str::FromStr;
use cards::NetworkToken;
use common_enums::enums;
use common_utils::{id_type, pii::Email, request::Method, types::StringMajorUnit};
use error_stack::report;
use hyperswitch_domain_models::{
payment_method_data::{
BankRedirectData, Card, NetworkTokenData, PayLaterData, PaymentMethodData, WalletData,
},
payment_methods::storage_enums::MitCategory,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::SetupMandate,
router_request_types::{
PaymentsAuthorizeData, PaymentsCancelData, PaymentsSyncData, ResponseId,
SetupMandateRequestData,
},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use super::aci_result_codes::{FAILURE_CODES, PENDING_CODES, SUCCESSFUL_CODES};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, CardData, NetworkTokenData as NetworkTokenDataTrait, PaymentsAuthorizeRequestData,
PhoneDetailsData, RouterData as _,
},
};
type Error = error_stack::Report<errors::ConnectorError>;
trait GetCaptureMethod {
fn get_capture_method(&self) -> Option<enums::CaptureMethod>;
}
impl GetCaptureMethod for PaymentsAuthorizeData {
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
self.capture_method
}
}
impl GetCaptureMethod for PaymentsSyncData {
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
self.capture_method
}
}
impl GetCaptureMethod for PaymentsCancelData {
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
None
}
}
#[derive(Debug, Serialize)]
pub struct AciRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for AciRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub struct AciAuthType {
pub api_key: Secret<String>,
pub entity_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AciAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = item {
Ok(Self {
api_key: api_key.to_owned(),
entity_id: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum AciRecurringType {
Initial,
Repeated,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciPaymentsRequest {
#[serde(flatten)]
pub txn_details: TransactionDetails,
#[serde(flatten)]
pub payment_method: PaymentDetails,
#[serde(flatten)]
pub instruction: Option<Instruction>,
pub shopper_result_url: Option<String>,
#[serde(rename = "customParameters[3DS2_enrolled]")]
pub three_ds_two_enrolled: Option<bool>,
pub recurring_type: Option<AciRecurringType>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionDetails {
pub entity_id: Secret<String>,
pub amount: StringMajorUnit,
pub currency: String,
pub payment_type: AciPaymentType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciCancelRequest {
pub entity_id: Secret<String>,
pub payment_type: AciPaymentType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciMandateRequest {
pub entity_id: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_brand: Option<PaymentBrand>,
#[serde(flatten)]
pub payment_details: PaymentDetails,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciMandateResponse {
pub id: String,
pub result: ResultCode,
pub build_number: String,
pub timestamp: String,
}
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum PaymentDetails {
#[serde(rename = "card")]
AciCard(Box<CardDetails>),
BankRedirect(Box<BankRedirectionPMData>),
Wallet(Box<WalletPMData>),
Klarna,
Mandate,
AciNetworkToken(Box<AciNetworkTokenData>),
}
impl TryFrom<(&WalletData, &PaymentsAuthorizeRouterData)> for PaymentDetails {
type Error = Error;
fn try_from(value: (&WalletData, &PaymentsAuthorizeRouterData)) -> Result<Self, Self::Error> {
let (wallet_data, item) = value;
let payment_data = match wallet_data {
WalletData::MbWayRedirect(_) => {
let phone_details = item.get_billing_phone()?;
Self::Wallet(Box::new(WalletPMData {
payment_brand: PaymentBrand::Mbway,
account_id: Some(phone_details.get_number_with_hash_country_code()?),
}))
}
WalletData::AliPayRedirect { .. } => Self::Wallet(Box::new(WalletPMData {
payment_brand: PaymentBrand::AliPay,
account_id: None,
})),
WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect { .. }
| WalletData::GooglePay(_)
| WalletData::BluecodeRedirect {}
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect { .. }
| WalletData::VippsRedirect { .. }
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::AliPayQr(_)
| WalletData::ApplePayRedirect(_)
| WalletData::GooglePayRedirect(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
"Payment method".to_string(),
))?,
};
Ok(payment_data)
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
&BankRedirectData,
)> for PaymentDetails
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
&BankRedirectData,
),
) -> Result<Self, Self::Error> {
let (item, bank_redirect_data) = value;
let payment_data = match bank_redirect_data {
BankRedirectData::Eps { .. } => Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Eps,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
})),
BankRedirectData::Eft { .. } => Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Eft,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
})),
BankRedirectData::Giropay {
bank_account_bic,
bank_account_iban,
..
} => Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Giropay,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: bank_account_bic.clone(),
bank_account_iban: bank_account_iban.clone(),
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
})),
BankRedirectData::Ideal { bank_name, .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Ideal,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: Some(bank_name.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "ideal.bank_name",
},
)?),
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
}))
}
BankRedirectData::Sofort { .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Sofortueberweisung,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
}))
}
BankRedirectData::Przelewy24 { .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Przelewy,
bank_account_country: None,
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: Some(item.router_data.get_billing_email()?),
}))
}
BankRedirectData::Interac { .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::InteracOnline,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: Some(item.router_data.get_billing_email()?),
}))
}
BankRedirectData::Trustly { .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Trustly,
bank_account_country: None,
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: Some(item.router_data.get_billing_country()?),
merchant_customer_id: Some(Secret::new(item.router_data.get_customer_id()?)),
merchant_transaction_id: Some(Secret::new(
item.router_data.connector_request_reference_id.clone(),
)),
customer_email: None,
}))
}
BankRedirectData::Bizum { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::BancontactCard { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {}
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::OpenBanking { .. } => Err(errors::ConnectorError::NotImplemented(
"Payment method".to_string(),
))?,
};
Ok(payment_data)
}
}
fn get_aci_payment_brand(
card_network: Option<common_enums::CardNetwork>,
is_network_token_flow: bool,
) -> Result<PaymentBrand, Error> {
match card_network {
Some(common_enums::CardNetwork::Visa) => Ok(PaymentBrand::Visa),
Some(common_enums::CardNetwork::Mastercard) => Ok(PaymentBrand::Mastercard),
Some(common_enums::CardNetwork::AmericanExpress) => Ok(PaymentBrand::AmericanExpress),
Some(common_enums::CardNetwork::JCB) => Ok(PaymentBrand::Jcb),
Some(common_enums::CardNetwork::DinersClub) => Ok(PaymentBrand::DinersClub),
Some(common_enums::CardNetwork::Discover) => Ok(PaymentBrand::Discover),
Some(common_enums::CardNetwork::UnionPay) => Ok(PaymentBrand::UnionPay),
Some(common_enums::CardNetwork::Maestro) => Ok(PaymentBrand::Maestro),
Some(unsupported_network) => Err(errors::ConnectorError::NotSupported {
message: format!("Card network {unsupported_network} is not supported by ACI"),
connector: "ACI",
})?,
None => {
if is_network_token_flow {
Ok(PaymentBrand::Visa)
} else {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "card.card_network",
}
.into())
}
}
}
}
impl TryFrom<(Card, Option<Secret<String>>)> for PaymentDetails {
type Error = Error;
fn try_from(
(card_data, card_holder_name): (Card, Option<Secret<String>>),
) -> Result<Self, Self::Error> {
let card_expiry_year = card_data.get_expiry_year_4_digit();
let payment_brand = get_aci_payment_brand(card_data.card_network, false).ok();
Ok(Self::AciCard(Box::new(CardDetails {
card_number: card_data.card_number,
card_holder: card_holder_name.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "card_holder_name",
})?,
card_expiry_month: card_data.card_exp_month.clone(),
card_expiry_year,
card_cvv: card_data.card_cvc,
payment_brand,
})))
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
&NetworkTokenData,
)> for PaymentDetails
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
&NetworkTokenData,
),
) -> Result<Self, Self::Error> {
let (_item, network_token_data) = value;
let token_number = network_token_data.get_network_token();
let payment_brand = get_aci_payment_brand(network_token_data.card_network.clone(), true)?;
let aci_network_token_data = AciNetworkTokenData {
token_type: AciTokenAccountType::Network,
token_number,
token_expiry_month: network_token_data.get_network_token_expiry_month(),
token_expiry_year: network_token_data.get_expiry_year_4_digit(),
token_cryptogram: Some(
network_token_data
.get_cryptogram()
.clone()
.unwrap_or_default(),
),
payment_brand,
};
Ok(Self::AciNetworkToken(Box::new(aci_network_token_data)))
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum AciTokenAccountType {
Network,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciNetworkTokenData {
#[serde(rename = "tokenAccount.type")]
pub token_type: AciTokenAccountType,
#[serde(rename = "tokenAccount.number")]
pub token_number: NetworkToken,
#[serde(rename = "tokenAccount.expiryMonth")]
pub token_expiry_month: Secret<String>,
#[serde(rename = "tokenAccount.expiryYear")]
pub token_expiry_year: Secret<String>,
#[serde(rename = "tokenAccount.cryptogram")]
pub token_cryptogram: Option<Secret<String>>,
#[serde(rename = "paymentBrand")]
pub payment_brand: PaymentBrand,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankRedirectionPMData {
payment_brand: PaymentBrand,
#[serde(rename = "bankAccount.country")]
bank_account_country: Option<api_models::enums::CountryAlpha2>,
#[serde(rename = "bankAccount.bankName")]
bank_account_bank_name: Option<common_enums::BankNames>,
#[serde(rename = "bankAccount.bic")]
bank_account_bic: Option<Secret<String>>,
#[serde(rename = "bankAccount.iban")]
bank_account_iban: Option<Secret<String>>,
#[serde(rename = "billing.country")]
billing_country: Option<api_models::enums::CountryAlpha2>,
#[serde(rename = "customer.email")]
customer_email: Option<Email>,
#[serde(rename = "customer.merchantCustomerId")]
merchant_customer_id: Option<Secret<id_type::CustomerId>>,
merchant_transaction_id: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletPMData {
payment_brand: PaymentBrand,
#[serde(rename = "virtualAccount.accountId")]
account_id: Option<Secret<String>>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentBrand {
Eps,
Eft,
Ideal,
Giropay,
Sofortueberweisung,
InteracOnline,
Przelewy,
Trustly,
Mbway,
#[serde(rename = "ALIPAY")]
AliPay,
// Card network brands
#[serde(rename = "VISA")]
Visa,
#[serde(rename = "MASTER")]
Mastercard,
#[serde(rename = "AMEX")]
AmericanExpress,
#[serde(rename = "JCB")]
Jcb,
#[serde(rename = "DINERS")]
DinersClub,
#[serde(rename = "DISCOVER")]
Discover,
#[serde(rename = "UNIONPAY")]
UnionPay,
#[serde(rename = "MAESTRO")]
Maestro,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
pub struct CardDetails {
#[serde(rename = "card.number")]
pub card_number: cards::CardNumber,
#[serde(rename = "card.holder")]
pub card_holder: Secret<String>,
#[serde(rename = "card.expiryMonth")]
pub card_expiry_month: Secret<String>,
#[serde(rename = "card.expiryYear")]
pub card_expiry_year: Secret<String>,
#[serde(rename = "card.cvv")]
pub card_cvv: Secret<String>,
#[serde(rename = "paymentBrand")]
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_brand: Option<PaymentBrand>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum InstructionMode {
Initial,
Repeated,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum InstructionType {
Unscheduled,
Recurring,
Installment,
}
#[derive(Debug, Clone, Serialize)]
pub enum InstructionSource {
#[serde(rename = "CIT")]
CardholderInitiatedTransaction,
#[serde(rename = "MIT")]
MerchantInitiatedTransaction,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Instruction {
#[serde(rename = "standingInstruction.mode")]
mode: InstructionMode,
#[serde(rename = "standingInstruction.type")]
transaction_type: InstructionType,
#[serde(rename = "standingInstruction.source")]
source: InstructionSource,
#[serde(rename = "standingInstruction.initialTransactionId")]
#[serde(skip_serializing_if = "Option::is_none")]
initial_transaction_id: Option<String>,
create_registration: Option<bool>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
pub struct BankDetails {
#[serde(rename = "bankAccount.holder")]
pub account_holder: Secret<String>,
}
#[allow(dead_code)]
#[derive(Debug, Default, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub enum AciPaymentType {
#[serde(rename = "PA")]
Preauthorization,
#[default]
#[serde(rename = "DB")]
Debit,
#[serde(rename = "CD")]
Credit,
#[serde(rename = "CP")]
Capture,
#[serde(rename = "RV")]
Reversal,
#[serde(rename = "RF")]
Refund,
}
impl TryFrom<&AciRouterData<&PaymentsAuthorizeRouterData>> for AciPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AciRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ref card_data) => Self::try_from((item, card_data)),
PaymentMethodData::NetworkToken(ref network_token_data) => {
Self::try_from((item, network_token_data))
}
PaymentMethodData::Wallet(ref wallet_data) => Self::try_from((item, wallet_data)),
PaymentMethodData::PayLater(ref pay_later_data) => {
Self::try_from((item, pay_later_data))
}
PaymentMethodData::BankRedirect(ref bank_redirect_data) => {
Self::try_from((item, bank_redirect_data))
}
PaymentMethodData::MandatePayment => {
let mandate_id = item.router_data.request.mandate_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "mandate_id",
},
)?;
Self::try_from((item, mandate_id))
}
PaymentMethodData::Crypto(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Aci"),
))?
}
}
}
}
impl TryFrom<(&AciRouterData<&PaymentsAuthorizeRouterData>, &WalletData)> for AciPaymentsRequest {
type Error = Error;
fn try_from(
value: (&AciRouterData<&PaymentsAuthorizeRouterData>, &WalletData),
) -> Result<Self, Self::Error> {
let (item, wallet_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((wallet_data, item.router_data))?;
Ok(Self {
txn_details,
payment_method,
instruction: None,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
&BankRedirectData,
)> for AciPaymentsRequest
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
&BankRedirectData,
),
) -> Result<Self, Self::Error> {
let (item, bank_redirect_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((item, bank_redirect_data))?;
Ok(Self {
txn_details,
payment_method,
instruction: None,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl TryFrom<(&AciRouterData<&PaymentsAuthorizeRouterData>, &PayLaterData)> for AciPaymentsRequest {
type Error = Error;
fn try_from(
value: (&AciRouterData<&PaymentsAuthorizeRouterData>, &PayLaterData),
) -> Result<Self, Self::Error> {
let (item, _pay_later_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::Klarna;
Ok(Self {
txn_details,
payment_method,
instruction: None,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl TryFrom<(&AciRouterData<&PaymentsAuthorizeRouterData>, &Card)> for AciPaymentsRequest {
type Error = Error;
fn try_from(
value: (&AciRouterData<&PaymentsAuthorizeRouterData>, &Card),
) -> Result<Self, Self::Error> {
let (item, card_data) = value;
let card_holder_name = item.router_data.get_optional_billing_full_name();
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((card_data.clone(), card_holder_name))?;
let instruction = get_instruction_details(item);
let recurring_type = get_recurring_type(item);
let three_ds_two_enrolled = item
.router_data
.is_three_ds()
.then_some(item.router_data.request.enrolled_for_3ds);
Ok(Self {
txn_details,
payment_method,
instruction,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled,
recurring_type,
})
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
&NetworkTokenData,
)> for AciPaymentsRequest
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
&NetworkTokenData,
),
) -> Result<Self, Self::Error> {
let (item, network_token_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((item, network_token_data))?;
let instruction = get_instruction_details(item);
Ok(Self {
txn_details,
payment_method,
instruction,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
api_models::payments::MandateIds,
)> for AciPaymentsRequest
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
api_models::payments::MandateIds,
),
) -> Result<Self, Self::Error> {
let (item, _mandate_data) = value;
let instruction = get_instruction_details(item);
let txn_details = get_transaction_details(item)?;
let recurring_type = get_recurring_type(item);
Ok(Self {
txn_details,
payment_method: PaymentDetails::Mandate,
instruction,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type,
})
}
}
fn get_transaction_details(
item: &AciRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<TransactionDetails, error_stack::Report<errors::ConnectorError>> {
let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?;
let payment_type = if item.router_data.request.is_auto_capture()? {
AciPaymentType::Debit
} else {
AciPaymentType::Preauthorization
};
Ok(TransactionDetails {
entity_id: auth.entity_id,
amount: item.amount.to_owned(),
currency: item.router_data.request.currency.to_string(),
payment_type,
})
}
fn get_instruction_details(
item: &AciRouterData<&PaymentsAuthorizeRouterData>,
) -> Option<Instruction> {
if item.router_data.request.customer_acceptance.is_some()
&& item.router_data.request.setup_future_usage == Some(enums::FutureUsage::OffSession)
{
return Some(Instruction {
mode: InstructionMode::Initial,
transaction_type: InstructionType::Unscheduled,
source: InstructionSource::CardholderInitiatedTransaction,
initial_transaction_id: None,
create_registration: Some(true),
});
} else if item.router_data.request.mandate_id.is_some() {
let initial_transaction_id = item
.router_data
.request
.get_connector_mandate_request_reference_id()
.ok();
let transaction_type = match item.router_data.request.mit_category.as_ref() {
Some(MitCategory::Installment) => InstructionType::Installment,
Some(MitCategory::Recurring) => InstructionType::Recurring,
Some(MitCategory::Unscheduled) | Some(MitCategory::Resubmission) | None => {
InstructionType::Unscheduled
}
};
return Some(Instruction {
mode: InstructionMode::Repeated,
transaction_type,
source: InstructionSource::MerchantInitiatedTransaction,
initial_transaction_id,
create_registration: None,
});
}
None
}
fn get_recurring_type(
item: &AciRouterData<&PaymentsAuthorizeRouterData>,
) -> Option<AciRecurringType> {
if item.router_data.request.mandate_id.is_some() {
Some(AciRecurringType::Repeated)
} else if item.router_data.request.customer_acceptance.is_some()
&& item.router_data.request.setup_future_usage == Some(enums::FutureUsage::OffSession)
{
Some(AciRecurringType::Initial)
} else {
None
}
}
impl TryFrom<&PaymentsCancelRouterData> for AciCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let auth = AciAuthType::try_from(&item.connector_auth_type)?;
let aci_payment_request = Self {
entity_id: auth.entity_id,
payment_type: AciPaymentType::Reversal,
};
Ok(aci_payment_request)
}
}
impl TryFrom<&RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>>
for AciMandateRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let auth = AciAuthType::try_from(&item.connector_auth_type)?;
let (payment_brand, payment_details) = match &item.request.payment_method_data {
PaymentMethodData::Card(card_data) => {
let brand = get_aci_payment_brand(card_data.card_network.clone(), false).ok();
match brand.as_ref() {
Some(PaymentBrand::Visa)
| Some(PaymentBrand::Mastercard)
| Some(PaymentBrand::AmericanExpress) => (),
Some(_) => {
return Err(errors::ConnectorError::NotSupported {
message: "Payment method not supported for mandate setup".to_string(),
connector: "ACI",
}
.into());
}
None => (),
};
let details = PaymentDetails::AciCard(Box::new(CardDetails {
card_number: card_data.card_number.clone(),
card_expiry_month: card_data.card_exp_month.clone(),
card_expiry_year: card_data.get_expiry_year_4_digit(),
card_cvv: card_data.card_cvc.clone(),
card_holder: card_data.card_holder_name.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "card_holder_name",
},
)?,
payment_brand: brand.clone(),
}));
(brand, details)
}
_ => {
return Err(errors::ConnectorError::NotSupported {
message: "Payment method not supported for mandate setup".to_string(),
connector: "ACI",
}
.into());
}
};
Ok(Self {
entity_id: auth.entity_id,
payment_brand,
payment_details,
})
}
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AciPaymentStatus {
Succeeded,
Failed,
#[default]
Pending,
RedirectShopper,
}
fn map_aci_attempt_status(item: AciPaymentStatus, auto_capture: bool) -> enums::AttemptStatus {
match item {
AciPaymentStatus::Succeeded => {
if auto_capture {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
AciPaymentStatus::Failed => enums::AttemptStatus::Failure,
AciPaymentStatus::Pending => enums::AttemptStatus::Authorizing,
AciPaymentStatus::RedirectShopper => enums::AttemptStatus::AuthenticationPending,
}
}
impl FromStr for AciPaymentStatus {
type Err = error_stack::Report<errors::ConnectorError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if FAILURE_CODES.contains(&s) {
Ok(Self::Failed)
} else if PENDING_CODES.contains(&s) {
Ok(Self::Pending)
} else if SUCCESSFUL_CODES.contains(&s) {
Ok(Self::Succeeded)
} else {
Err(report!(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(s.to_owned())
)))
}
}
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciPaymentsResponse {
id: String,
registration_id: Option<Secret<String>>,
ndc: String,
timestamp: String,
build_number: String,
pub(super) result: ResultCode,
pub(super) redirect: Option<AciRedirectionData>,
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciErrorResponse {
ndc: String,
timestamp: String,
build_number: String,
pub(super) result: ResultCode,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciRedirectionData {
pub method: Option<Method>,
pub parameters: Vec<Parameters>,
pub url: Url,
pub preconditions: Option<Vec<PreconditionData>>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PreconditionData {
pub method: Option<Method>,
pub parameters: Vec<Parameters>,
pub url: Url,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
pub struct Parameters {
pub name: String,
pub value: String,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResultCode {
pub(super) code: String,
pub(super) description: String,
pub(super) parameter_errors: Option<Vec<ErrorParameters>>,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq, Serialize)]
pub struct ErrorParameters {
pub(super) name: String,
pub(super) value: Option<String>,
pub(super) message: String,
}
impl<F, Req> TryFrom<ResponseRouterData<F, AciPaymentsResponse, Req, PaymentsResponseData>>
for RouterData<F, Req, PaymentsResponseData>
where
Req: GetCaptureMethod,
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AciPaymentsResponse, Req, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirection_data = item.response.redirect.map(|data| {
let mut form_fields = std::collections::HashMap::<_, _>::from_iter(
data.parameters
.iter()
.map(|parameter| (parameter.name.clone(), parameter.value.clone())),
);
if let Some(preconditions) = data.preconditions {
if let Some(first_precondition) = preconditions.first() {
for param in &first_precondition.parameters {
form_fields.insert(param.name.clone(), param.value.clone());
}
}
}
// If method is Get, parameters are appended to URL
// If method is post, we http Post the method to URL
RedirectForm::Form {
endpoint: data.url.to_string(),
// Handles method for Bank redirects currently.
// 3DS response have method within preconditions. That would require replacing below line with a function.
method: data.method.unwrap_or(Method::Post),
form_fields,
}
});
let mandate_reference = item
.response
.registration_id
.clone()
.map(|id| MandateReference {
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: Some(item.response.id.clone()),
});
let auto_capture = matches!(
item.data.request.get_capture_method(),
Some(enums::CaptureMethod::Automatic) | None
);
let status = if redirection_data.is_some() {
map_aci_attempt_status(AciPaymentStatus::RedirectShopper, auto_capture)
} else {
map_aci_attempt_status(
AciPaymentStatus::from_str(&item.response.result.code)?,
auto_capture,
)
};
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item.response.result.code.clone(),
message: item.response.result.description.clone(),
reason: Some(item.response.result.description),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(item.response.id.clone()),
connector_response_reference_id: Some(item.response.id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciCaptureRequest {
#[serde(flatten)]
pub txn_details: TransactionDetails,
}
impl TryFrom<&AciRouterData<&PaymentsCaptureRouterData>> for AciCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AciRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
txn_details: TransactionDetails {
entity_id: auth.entity_id,
amount: item.amount.to_owned(),
currency: item.router_data.request.currency.to_string(),
payment_type: AciPaymentType::Capture,
},
})
}
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciCaptureResponse {
id: String,
referenced_id: String,
payment_type: AciPaymentType,
amount: StringMajorUnit,
currency: String,
descriptor: String,
result: AciCaptureResult,
result_details: Option<AciCaptureResultDetails>,
build_number: String,
timestamp: String,
ndc: Secret<String>,
source: Option<Secret<String>>,
payment_method: Option<String>,
short_id: Option<String>,
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciCaptureResult {
code: String,
description: String,
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct AciCaptureResultDetails {
extended_description: String,
#[serde(rename = "clearingInstituteName")]
clearing_institute_name: Option<String>,
connector_tx_i_d1: Option<String>,
connector_tx_i_d3: Option<String>,
connector_tx_i_d2: Option<String>,
acquirer_response: Option<String>,
}
#[derive(Debug, Default, Clone, Deserialize)]
pub enum AciStatus {
Succeeded,
Failed,
#[default]
Pending,
}
impl FromStr for AciStatus {
type Err = error_stack::Report<errors::ConnectorError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if FAILURE_CODES.contains(&s) {
Ok(Self::Failed)
} else if PENDING_CODES.contains(&s) {
Ok(Self::Pending)
} else if SUCCESSFUL_CODES.contains(&s) {
Ok(Self::Succeeded)
} else {
Err(report!(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(s.to_owned())
)))
}
}
}
fn map_aci_capture_status(item: AciStatus) -> enums::AttemptStatus {
match item {
AciStatus::Succeeded => enums::AttemptStatus::Charged,
AciStatus::Failed => enums::AttemptStatus::Failure,
AciStatus::Pending => enums::AttemptStatus::Pending,
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AciCaptureResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AciCaptureResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = map_aci_capture_status(AciStatus::from_str(&item.response.result.code)?);
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item.response.result.code.clone(),
message: item.response.result.description.clone(),
reason: Some(item.response.result.description),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(item.response.id.clone()),
connector_response_reference_id: Some(item.response.id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.referenced_id.clone()),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Ok(Self {
status,
response,
reference_id: Some(item.response.referenced_id),
..item.data
})
}
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciVoidResponse {
id: String,
referenced_id: String,
payment_type: AciPaymentType,
amount: StringMajorUnit,
currency: String,
descriptor: String,
result: AciCaptureResult,
result_details: Option<AciCaptureResultDetails>,
build_number: String,
timestamp: String,
ndc: Secret<String>,
}
fn map_aci_void_status(item: AciStatus) -> enums::AttemptStatus {
match item {
AciStatus::Succeeded => enums::AttemptStatus::Voided,
AciStatus::Failed => enums::AttemptStatus::VoidFailed,
AciStatus::Pending => enums::AttemptStatus::VoidInitiated,
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AciVoidResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AciVoidResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = map_aci_void_status(AciStatus::from_str(&item.response.result.code)?);
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item.response.result.code.clone(),
message: item.response.result.description.clone(),
reason: Some(item.response.result.description),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(item.response.id.clone()),
..Default::default()
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.referenced_id.clone()),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Ok(Self {
status,
response,
reference_id: Some(item.response.referenced_id),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciRefundRequest {
pub amount: StringMajorUnit,
pub currency: String,
pub payment_type: AciPaymentType,
pub entity_id: Secret<String>,
}
impl<F> TryFrom<&AciRouterData<&RefundsRouterData<F>>> for AciRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AciRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let amount = item.amount.to_owned();
let currency = item.router_data.request.currency;
let payment_type = AciPaymentType::Refund;
let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
amount,
currency: currency.to_string(),
payment_type,
entity_id: auth.entity_id,
})
}
}
#[derive(Debug, Default, Deserialize, Clone)]
pub enum AciRefundStatus {
Succeeded,
Failed,
#[default]
Pending,
}
impl FromStr for AciRefundStatus {
type Err = error_stack::Report<errors::ConnectorError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if FAILURE_CODES.contains(&s) {
Ok(Self::Failed)
} else if PENDING_CODES.contains(&s) {
Ok(Self::Pending)
} else if SUCCESSFUL_CODES.contains(&s) {
Ok(Self::Succeeded)
} else {
Err(report!(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(s.to_owned())
)))
}
}
}
impl From<AciRefundStatus> for enums::RefundStatus {
fn from(item: AciRefundStatus) -> Self {
match item {
AciRefundStatus::Succeeded => Self::Success,
AciRefundStatus::Failed => Self::Failure,
AciRefundStatus::Pending => Self::Pending,
}
}
}
#[allow(dead_code)]
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciRefundResponse {
id: String,
ndc: String,
timestamp: String,
build_number: String,
pub(super) result: ResultCode,
}
impl<F> TryFrom<RefundsResponseRouterData<F, AciRefundResponse>> for RefundsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<F, AciRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status =
enums::RefundStatus::from(AciRefundStatus::from_str(&item.response.result.code)?);
let response = if refund_status == enums::RefundStatus::Failure {
Err(ErrorResponse {
code: item.response.result.code.clone(),
message: item.response.result.description.clone(),
reason: Some(item.response.result.description),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.id.clone()),
connector_response_reference_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
impl
TryFrom<
ResponseRouterData<
SetupMandate,
AciMandateResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
> for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
SetupMandate,
AciMandateResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let mandate_reference = Some(MandateReference {
connector_mandate_id: Some(item.response.id.clone()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: Some(item.response.id.clone()),
});
let status = if SUCCESSFUL_CODES.contains(&item.response.result.code.as_str()) {
enums::AttemptStatus::Charged
} else if FAILURE_CODES.contains(&item.response.result.code.as_str()) {
enums::AttemptStatus::Failure
} else {
enums::AttemptStatus::Pending
};
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item.response.result.code.clone(),
message: item.response.result.description.clone(),
reason: Some(item.response.result.description),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(item.response.id.clone()),
connector_response_reference_id: Some(item.response.id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum AciWebhookEventType {
Payment,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum AciWebhookAction {
Created,
Updated,
Deleted,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciWebhookCardDetails {
pub bin: Option<String>,
#[serde(rename = "last4Digits")]
pub last4_digits: Option<String>,
pub holder: Option<String>,
pub expiry_month: Option<Secret<String>>,
pub expiry_year: Option<Secret<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciWebhookCustomerDetails {
#[serde(rename = "givenName")]
pub given_name: Option<Secret<String>>,
pub surname: Option<Secret<String>>,
#[serde(rename = "merchantCustomerId")]
pub merchant_customer_id: Option<Secret<String>>,
pub sex: Option<Secret<String>>,
pub email: Option<Email>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciWebhookAuthenticationDetails {
#[serde(rename = "entityId")]
pub entity_id: Secret<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciWebhookRiskDetails {
pub score: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciPaymentWebhookPayload {
pub id: String,
pub payment_type: String,
pub payment_brand: String,
pub amount: StringMajorUnit,
pub currency: String,
pub presentation_amount: Option<StringMajorUnit>,
pub presentation_currency: Option<String>,
pub descriptor: Option<String>,
pub result: ResultCode,
pub authentication: Option<AciWebhookAuthenticationDetails>,
pub card: Option<AciWebhookCardDetails>,
pub customer: Option<AciWebhookCustomerDetails>,
#[serde(rename = "customParameters")]
pub custom_parameters: Option<serde_json::Value>,
pub risk: Option<AciWebhookRiskDetails>,
pub build_number: Option<String>,
pub timestamp: String,
pub ndc: String,
#[serde(rename = "channelName")]
pub channel_name: Option<String>,
pub source: Option<String>,
pub payment_method: Option<String>,
#[serde(rename = "shortId")]
pub short_id: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciWebhookNotification {
#[serde(rename = "type")]
pub event_type: AciWebhookEventType,
pub action: Option<AciWebhookAction>,
pub payload: serde_json::Value,
}
|
crates__hyperswitch_connectors__src__connectors__adyen.rs
|
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums::{self, PaymentMethodType};
use common_utils::{
consts,
errors::CustomResult,
ext_traits::{ByteSliceExt, OptionExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{
AmountConvertor, MinorUnit, MinorUnitForConnector, StringMinorUnit,
StringMinorUnitForConnector,
},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
api::ApplicationResponse,
payment_method_data,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
merchant_connector_webhook_management::ConnectorWebhookRegister,
payments::{
Authorize, Capture, ExtendAuthorization, PSync, PaymentMethodToken, PreProcessing,
Session, SetupMandate, Void,
},
refunds::{Execute, RSync},
Accept, Defend, Evidence, GiftCardBalanceCheck, Retrieve, Upload,
},
router_request_types::{
merchant_connector_webhook_management::ConnectorWebhookRegisterRequest,
AcceptDisputeRequestData, AccessTokenRequestData, DefendDisputeRequestData,
GiftCardBalanceCheckRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsExtendAuthorizationData,
PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData,
RetrieveFileRequestData, SetupMandateRequestData, SubmitEvidenceRequestData,
SyncRequestType, UploadFileRequestData,
},
router_response_types::{
merchant_connector_webhook_management::ConnectorWebhookRegisterResponse,
AcceptDisputeResponse, ConnectorInfo, DefendDisputeResponse,
GiftCardBalanceCheckResponseData, PaymentMethodDetails, PaymentsResponseData,
RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, SupportedPaymentMethods,
SupportedPaymentMethodsExt, UploadFileResponse,
},
types::{
ConnectorWebhookRegisterRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsExtendAuthorizationRouterData,
PaymentsGiftCardBalanceCheckRouterData, PaymentsPreProcessingRouterData,
PaymentsSyncRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::payouts::{PoCancel, PoCreate, PoEligibility, PoFulfill},
router_response_types::PayoutsResponseData,
types::{PayoutsData, PayoutsRouterData},
};
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::types::{
PayoutCancelType, PayoutCreateType, PayoutEligibilityType, PayoutFulfillType,
};
use hyperswitch_interfaces::{
api::{
self,
disputes::{AcceptDispute, DefendDispute, Dispute, SubmitEvidence},
files::{FilePurpose, FileUpload, RetrieveFile, UploadFile},
CaptureSyncMethod, ConnectorCommon, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation, WebhookRegister,
},
configs::Connectors,
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
disputes, errors,
events::connector_api_logs::ConnectorEvent,
types::{
AcceptDisputeType, ConnectorWebhookRegisterType, DefendDisputeType,
ExtendedAuthorizationType, PaymentsAuthorizeType, PaymentsCaptureType,
PaymentsGiftCardBalanceCheckType, PaymentsPreProcessingType, PaymentsSyncType,
PaymentsVoidType, RefundExecuteType, Response, SetupMandateType, SubmitEvidenceType,
},
webhooks::{
IncomingWebhook, IncomingWebhookFlowError, IncomingWebhookRequestDetails, WebhookContext,
},
};
use masking::{ExposeInterface, Mask, Maskable, Secret};
use ring::hmac;
use router_env::{instrument, tracing};
use transformers as adyen;
#[cfg(feature = "payouts")]
use crate::utils::PayoutsData as UtilsPayoutData;
use crate::{
capture_method_not_supported,
constants::{self, headers},
types::{
AcceptDisputeRouterData, DefendDisputeRouterData, ResponseRouterData,
SubmitEvidenceRouterData,
},
utils::{
convert_amount, convert_payment_authorize_router_response,
convert_setup_mandate_router_data_to_authorize_router_data, is_mandate_supported,
ForeignTryFrom, PaymentMethodDataType,
},
};
const ADYEN_API_VERSION: &str = "v68";
#[derive(Clone)]
pub struct Adyen {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
amount_converter_webhooks: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Adyen {
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
amount_converter_webhooks: &StringMinorUnitForConnector,
}
}
}
impl ConnectorCommon for Adyen {
fn id(&self) -> &'static str {
"adyen"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = adyen::AdyenAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::X_API_KEY.to_string(),
auth.api_key.into_masked(),
)])
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.adyen.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: adyen::AdyenErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_code,
message: response.message.to_owned(),
reason: Some(response.message),
attempt_status: None,
connector_transaction_id: response.psp_reference,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Adyen {
fn validate_connector_against_payment_request(
&self,
capture_method: Option<enums::CaptureMethod>,
_payment_method: enums::PaymentMethod,
pmt: Option<PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
let connector = self.id();
match pmt {
Some(payment_method_type) => match payment_method_type {
#[cfg(feature = "v1")]
PaymentMethodType::Affirm
| PaymentMethodType::AfterpayClearpay
| PaymentMethodType::ApplePay
| PaymentMethodType::Credit
| PaymentMethodType::Debit
| PaymentMethodType::GooglePay
| PaymentMethodType::MobilePay
| PaymentMethodType::PayBright
| PaymentMethodType::Sepa
| PaymentMethodType::Vipps
| PaymentMethodType::Venmo
| PaymentMethodType::Paypal => match capture_method {
enums::CaptureMethod::Automatic
| enums::CaptureMethod::SequentialAutomatic
| enums::CaptureMethod::Manual
| enums::CaptureMethod::ManualMultiple => Ok(()),
enums::CaptureMethod::Scheduled => {
capture_method_not_supported!(
connector,
capture_method,
payment_method_type
)
}
},
#[cfg(feature = "v2")]
PaymentMethodType::Affirm
| PaymentMethodType::AfterpayClearpay
| PaymentMethodType::ApplePay
| PaymentMethodType::Credit
| PaymentMethodType::Debit
| PaymentMethodType::Card
| PaymentMethodType::GooglePay
| PaymentMethodType::MobilePay
| PaymentMethodType::PayBright
| PaymentMethodType::Sepa
| PaymentMethodType::Vipps
| PaymentMethodType::Venmo
| PaymentMethodType::Skrill
| PaymentMethodType::Paypal => match capture_method {
enums::CaptureMethod::Automatic
| enums::CaptureMethod::SequentialAutomatic
| enums::CaptureMethod::Manual
| enums::CaptureMethod::ManualMultiple => Ok(()),
enums::CaptureMethod::Scheduled => {
capture_method_not_supported!(
connector,
capture_method,
payment_method_type
)
}
},
PaymentMethodType::Ach
| PaymentMethodType::SamsungPay
| PaymentMethodType::Paze
| PaymentMethodType::Alma
| PaymentMethodType::Bacs
| PaymentMethodType::Givex
| PaymentMethodType::Klarna
| PaymentMethodType::Twint
| PaymentMethodType::Walley
| PaymentMethodType::Payjustnow => match capture_method {
enums::CaptureMethod::Automatic
| enums::CaptureMethod::Manual
| enums::CaptureMethod::SequentialAutomatic => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => {
capture_method_not_supported!(
connector,
capture_method,
payment_method_type
)
}
},
PaymentMethodType::AliPay
| PaymentMethodType::AliPayHk
| PaymentMethodType::Atome
| PaymentMethodType::BancontactCard
| PaymentMethodType::Benefit
| PaymentMethodType::Bizum
| PaymentMethodType::Blik
| PaymentMethodType::Boleto
| PaymentMethodType::Dana
| PaymentMethodType::Eps
| PaymentMethodType::OnlineBankingFpx
| PaymentMethodType::Gcash
| PaymentMethodType::GoPay
| PaymentMethodType::Ideal
| PaymentMethodType::KakaoPay
| PaymentMethodType::Knet
| PaymentMethodType::MbWay
| PaymentMethodType::Momo
| PaymentMethodType::MomoAtm
| PaymentMethodType::OnlineBankingFinland
| PaymentMethodType::OnlineBankingPoland
| PaymentMethodType::OnlineBankingSlovakia
| PaymentMethodType::OnlineBankingThailand
| PaymentMethodType::Oxxo
| PaymentMethodType::PaySafeCard
| PaymentMethodType::Pix
| PaymentMethodType::Swish
| PaymentMethodType::TouchNGo
| PaymentMethodType::Trustly
| PaymentMethodType::WeChatPay
| PaymentMethodType::DanamonVa
| PaymentMethodType::BcaBankTransfer
| PaymentMethodType::BriVa
| PaymentMethodType::BniVa
| PaymentMethodType::CimbVa
| PaymentMethodType::MandiriVa
| PaymentMethodType::Alfamart
| PaymentMethodType::Indomaret
| PaymentMethodType::FamilyMart
| PaymentMethodType::Seicomart
| PaymentMethodType::PayEasy
| PaymentMethodType::MiniStop
| PaymentMethodType::Lawson
| PaymentMethodType::SevenEleven
| PaymentMethodType::OpenBankingUk
| PaymentMethodType::OnlineBankingCzechRepublic
| PaymentMethodType::PermataBankTransfer => match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::SequentialAutomatic => {
Ok(())
}
enums::CaptureMethod::Manual
| enums::CaptureMethod::ManualMultiple
| enums::CaptureMethod::Scheduled => {
capture_method_not_supported!(
connector,
capture_method,
payment_method_type
)
}
},
PaymentMethodType::AmazonPay
| PaymentMethodType::Breadpay
| PaymentMethodType::Paysera
| PaymentMethodType::Skrill
| PaymentMethodType::CardRedirect
| PaymentMethodType::DirectCarrierBilling
| PaymentMethodType::Fps
| PaymentMethodType::BhnCardNetwork
| PaymentMethodType::DuitNow
| PaymentMethodType::Interac
| PaymentMethodType::Multibanco
| PaymentMethodType::Przelewy24
| PaymentMethodType::Becs
| PaymentMethodType::Eft
| PaymentMethodType::ClassicReward
| PaymentMethodType::Pse
| PaymentMethodType::LocalBankTransfer
| PaymentMethodType::Efecty
| PaymentMethodType::Giropay
| PaymentMethodType::PagoEfectivo
| PaymentMethodType::PromptPay
| PaymentMethodType::RedCompra
| PaymentMethodType::RedPagos
| PaymentMethodType::Sofort
| PaymentMethodType::CryptoCurrency
| PaymentMethodType::Evoucher
| PaymentMethodType::Cashapp
| PaymentMethodType::UpiCollect
| PaymentMethodType::UpiIntent
| PaymentMethodType::UpiQr
| PaymentMethodType::VietQr
| PaymentMethodType::Mifinity
| PaymentMethodType::LocalBankRedirect
| PaymentMethodType::OpenBankingPIS
| PaymentMethodType::InstantBankTransfer
| PaymentMethodType::InstantBankTransferFinland
| PaymentMethodType::InstantBankTransferPoland
| PaymentMethodType::IndonesianBankTransfer
| PaymentMethodType::Qris
| PaymentMethodType::SepaBankTransfer
| PaymentMethodType::Flexiti
| PaymentMethodType::RevolutPay
| PaymentMethodType::Bluecode
| PaymentMethodType::SepaGuarenteedDebit
| PaymentMethodType::OpenBanking
| PaymentMethodType::NetworkToken => {
capture_method_not_supported!(connector, capture_method, payment_method_type)
}
},
None => match capture_method {
enums::CaptureMethod::Automatic
| enums::CaptureMethod::SequentialAutomatic
| enums::CaptureMethod::Manual
| enums::CaptureMethod::ManualMultiple => Ok(()),
enums::CaptureMethod::Scheduled => {
capture_method_not_supported!(connector, capture_method)
}
},
}
}
fn validate_mandate_payment(
&self,
pm_type: Option<PaymentMethodType>,
pm_data: payment_method_data::PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::ApplePay,
PaymentMethodDataType::GooglePay,
PaymentMethodDataType::PaypalRedirect,
PaymentMethodDataType::MomoRedirect,
PaymentMethodDataType::KakaoPayRedirect,
PaymentMethodDataType::GoPayRedirect,
PaymentMethodDataType::GcashRedirect,
PaymentMethodDataType::DanaRedirect,
PaymentMethodDataType::TwintRedirect,
PaymentMethodDataType::VippsRedirect,
PaymentMethodDataType::KlarnaRedirect,
PaymentMethodDataType::Ideal,
PaymentMethodDataType::OpenBankingUk,
PaymentMethodDataType::Trustly,
PaymentMethodDataType::BancontactCard,
PaymentMethodDataType::AchBankDebit,
PaymentMethodDataType::SepaBankDebit,
PaymentMethodDataType::BecsBankDebit,
]);
is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
fn validate_psync_reference_id(
&self,
data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
if data.encoded_data.is_some() {
return Ok(());
}
Err(errors::ConnectorError::MissingRequiredField {
field_name: "encoded_data",
}
.into())
}
fn is_webhook_source_verification_mandatory(&self) -> bool {
true
}
}
impl api::Payment for Adyen {}
impl api::PaymentAuthorize for Adyen {}
impl api::PaymentSync for Adyen {}
impl api::PaymentVoid for Adyen {}
impl api::PaymentCapture for Adyen {}
impl api::MandateSetup for Adyen {}
impl api::ConnectorAccessToken for Adyen {}
impl api::PaymentToken for Adyen {}
impl api::PaymentsGiftCardBalanceCheck for Adyen {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Adyen
{
// Not Implemented (R)
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Adyen {
// Not Implemented (R)
}
fn build_env_specific_endpoint(
base_url: &str,
test_mode: Option<bool>,
connector_metadata: &Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<String, errors::ConnectorError> {
if test_mode.unwrap_or(true) {
Ok(base_url.to_string())
} else {
let adyen_connector_metadata_object =
transformers::AdyenConnectorMetadataObject::try_from(connector_metadata)?;
let endpoint_prefix = adyen_connector_metadata_object.endpoint_prefix.ok_or(
errors::ConnectorError::InvalidConnectorConfig {
config: "metadata.endpoint_prefix",
},
)?;
Ok(base_url.replace("{{merchant_endpoint_prefix}}", &endpoint_prefix))
}
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Adyen {
fn get_headers(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
SetupMandateType::get_content_type(self).to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_url(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = build_env_specific_endpoint(
self.base_url(connectors),
req.test_mode,
&req.connector_meta_data,
)?;
Ok(format!("{endpoint}{ADYEN_API_VERSION}/payments"))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let authorize_req = convert_payment_authorize_router_response((
req,
convert_setup_mandate_router_data_to_authorize_router_data(req),
));
let amount = convert_amount(
self.amount_converter,
authorize_req.request.minor_amount,
authorize_req.request.currency,
)?;
let connector_router_data = adyen::AdyenRouterData::try_from((amount, &authorize_req))?;
let connector_req = adyen::AdyenPaymentRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(SetupMandateType::get_headers(self, req, connectors)?)
.set_body(SetupMandateType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
errors::ConnectorError,
>
where
SetupMandate: Clone,
SetupMandateRequestData: Clone,
PaymentsResponseData: Clone,
{
let response: adyen::AdyenPaymentResponse = res
.response
.parse_struct("AdyenPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::foreign_try_from((
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
None,
false,
data.request.payment_method_type,
))
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::PaymentSession for Adyen {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Adyen {
// Not Implemented (R)
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Adyen {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.common_get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req.request.connector_transaction_id.as_str();
let endpoint = build_env_specific_endpoint(
self.base_url(connectors),
req.test_mode,
&req.connector_meta_data,
)?;
Ok(format!(
"{endpoint}{ADYEN_API_VERSION}/payments/{id}/captures",
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_to_capture = convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = adyen::AdyenRouterData::try_from((amount_to_capture, req))?;
let connector_req = adyen::AdyenCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
.set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: adyen::AdyenCaptureResponse = res
.response
.parse_struct("AdyenCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
/// Payment Sync can be useful only incase of Redirect flow.
/// For payments which doesn't involve redrection we have to rely on webhooks.
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Adyen {
fn get_headers(
&self,
req: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PaymentsSyncType::get_content_type(self).to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_request_body(
&self,
req: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let encoded_data = req
.request
.encoded_data
.clone()
.get_required_value("encoded_data")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let adyen_redirection_type = serde_urlencoded::from_str::<
transformers::AdyenRedirectRequestTypes,
>(encoded_data.as_str())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let connector_req = match adyen_redirection_type {
adyen::AdyenRedirectRequestTypes::AdyenRedirection(req) => {
adyen::AdyenRedirectRequest {
details: adyen::AdyenRedirectRequestTypes::AdyenRedirection(
adyen::AdyenRedirection {
redirect_result: req.redirect_result,
type_of_redirection_result: None,
result_code: None,
},
),
}
}
adyen::AdyenRedirectRequestTypes::AdyenThreeDS(req) => adyen::AdyenRedirectRequest {
details: adyen::AdyenRedirectRequestTypes::AdyenThreeDS(adyen::AdyenThreeDS {
three_ds_result: req.three_ds_result,
type_of_redirection_result: None,
result_code: None,
}),
},
adyen::AdyenRedirectRequestTypes::AdyenRefusal(req) => adyen::AdyenRedirectRequest {
details: adyen::AdyenRedirectRequestTypes::AdyenRefusal(adyen::AdyenRefusal {
payload: req.payload,
type_of_redirection_result: None,
result_code: None,
}),
},
};
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn get_url(
&self,
req: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = build_env_specific_endpoint(
self.base_url(connectors),
req.test_mode,
&req.connector_meta_data,
)?;
Ok(format!("{endpoint}{ADYEN_API_VERSION}/payments/details"))
}
fn build_request(
&self,
req: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
// Adyen doesn't support PSync flow. We use PSync flow to fetch payment details,
// specifically the redirect URL that takes the user to their Payment page. In non-redirection flows,
// we rely on webhooks to obtain the payment status since there is no encoded data available.
// encoded_data only includes the redirect URL and is only relevant in redirection flows.
if req
.request
.encoded_data
.clone()
.get_required_value("encoded_data")
.is_ok()
{
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.set_body(PaymentsSyncType::get_request_body(self, req, connectors)?)
.build(),
))
} else {
Ok(None)
}
}
fn handle_response(
&self,
data: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
router_env::logger::debug!(payment_sync_response=?res);
let response: adyen::AdyenPaymentResponse = res
.response
.parse_struct("AdyenPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let is_multiple_capture_sync = match data.request.sync_type {
SyncRequestType::MultipleCaptureSync(_) => true,
SyncRequestType::SinglePaymentSync => false,
};
RouterData::foreign_try_from((
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
data.request.capture_method,
is_multiple_capture_sync,
data.request.payment_method_type,
))
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_multiple_capture_sync_method(
&self,
) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> {
Ok(CaptureSyncMethod::Individual)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Adyen {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError>
where
Self: ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
{
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = build_env_specific_endpoint(
self.base_url(connectors),
req.test_mode,
&req.connector_meta_data,
)?;
Ok(format!("{endpoint}{ADYEN_API_VERSION}/payments"))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = adyen::AdyenRouterData::try_from((amount, req))?;
let connector_req = adyen::AdyenPaymentRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: adyen::AdyenPaymentResponse = res
.response
.parse_struct("AdyenPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::foreign_try_from((
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
data.request.capture_method,
false,
data.request.payment_method_type,
))
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::PaymentsPreProcessing for Adyen {}
impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
for Adyen
{
fn get_headers(
&self,
req: &PaymentsPreProcessingRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PaymentsPreProcessingType::get_content_type(self)
.to_string()
.into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_url(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = build_env_specific_endpoint(
self.base_url(connectors),
req.test_mode,
&req.connector_meta_data,
)?;
Ok(format!(
"{endpoint}{ADYEN_API_VERSION}/paymentMethods/balance",
))
}
fn get_request_body(
&self,
req: &PaymentsPreProcessingRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = adyen::AdyenBalanceRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsPreProcessingType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsPreProcessingType::get_headers(
self, req, connectors,
)?)
.set_body(PaymentsPreProcessingType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsPreProcessingRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: adyen::AdyenBalanceResponse = res
.response
.parse_struct("AdyenBalanceResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let currency = match data.request.currency {
Some(currency) => currency,
None => Err(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?,
};
let amount = data.request.minor_amount;
let amount = convert_amount(self.amount_converter, amount, currency)?;
if response.balance.currency != currency || response.balance.value < amount {
Ok(RouterData {
response: Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: Some(constants::LOW_BALANCE_ERROR_MESSAGE.to_string()),
status_code: res.status_code,
attempt_status: Some(enums::AttemptStatus::Failure),
connector_transaction_id: Some(response.psp_reference),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..data.clone()
})
} else {
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Adyen {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req.request.connector_transaction_id.clone();
let endpoint = build_env_specific_endpoint(
self.base_url(connectors),
req.test_mode,
&req.connector_meta_data,
)?;
Ok(format!(
"{endpoint}{ADYEN_API_VERSION}/payments/{id}/cancels",
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = adyen::AdyenCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: adyen::AdyenCancelResponse = res
.response
.parse_struct("AdyenCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl
ConnectorIntegration<
GiftCardBalanceCheck,
GiftCardBalanceCheckRequestData,
GiftCardBalanceCheckResponseData,
> for Adyen
{
fn get_headers(
&self,
req: &PaymentsGiftCardBalanceCheckRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PaymentsGiftCardBalanceCheckType::get_content_type(self)
.to_string()
.into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_url(
&self,
req: &PaymentsGiftCardBalanceCheckRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = build_env_specific_endpoint(
self.base_url(connectors),
req.test_mode,
&req.connector_meta_data,
)?;
Ok(format!(
"{endpoint}{ADYEN_API_VERSION}/paymentMethods/balance",
))
}
fn get_request_body(
&self,
req: &PaymentsGiftCardBalanceCheckRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = adyen::AdyenBalanceRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsGiftCardBalanceCheckRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsGiftCardBalanceCheckType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(PaymentsGiftCardBalanceCheckType::get_headers(
self, req, connectors,
)?)
.set_body(PaymentsGiftCardBalanceCheckType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsGiftCardBalanceCheckRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsGiftCardBalanceCheckRouterData, errors::ConnectorError> {
let response: adyen::AdyenBalanceResponse = res
.response
.parse_struct("AdyenBalanceResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let currency = data
.request
.currency
.get_required_value("currency")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?;
if response.balance.currency != currency {
Ok(RouterData {
response: Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: Some(constants::MISMATCHED_CURRENCY.to_string()),
status_code: res.status_code,
attempt_status: Some(enums::AttemptStatus::Failure),
connector_transaction_id: Some(response.psp_reference),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..data.clone()
})
} else {
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::Payouts for Adyen {}
#[cfg(feature = "payouts")]
impl api::PayoutCancel for Adyen {}
#[cfg(feature = "payouts")]
impl api::PayoutCreate for Adyen {}
#[cfg(feature = "payouts")]
impl api::PayoutEligibility for Adyen {}
#[cfg(feature = "payouts")]
impl api::PayoutFulfill for Adyen {}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData> for Adyen {
fn get_url(
&self,
req: &PayoutsRouterData<PoCancel>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = build_env_specific_endpoint(
connectors.adyen.payout_base_url.as_str(),
req.test_mode,
&req.connector_meta_data,
)?;
Ok(format!(
"{endpoint}pal/servlet/Payout/{ADYEN_API_VERSION}/declineThirdParty",
))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoCancel>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PayoutCancelType::get_content_type(self).to_string().into(),
)];
let auth = adyen::AdyenAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let mut api_key = vec![(
headers::X_API_KEY.to_string(),
auth.review_key.unwrap_or(auth.api_key).into_masked(),
)];
header.append(&mut api_key);
Ok(header)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoCancel>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = adyen::AdyenPayoutCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoCancel>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutCancelType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutCancelType::get_headers(self, req, connectors)?)
.set_body(PayoutCancelType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoCancel>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoCancel>, errors::ConnectorError> {
let response: adyen::AdyenPayoutResponse = res
.response
.parse_struct("AdyenPayoutResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> for Adyen {
fn get_url(
&self,
req: &PayoutsRouterData<PoCreate>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = build_env_specific_endpoint(
connectors.adyen.payout_base_url.as_str(),
req.test_mode,
&req.connector_meta_data,
)?;
Ok(format!(
"{endpoint}pal/servlet/Payout/{ADYEN_API_VERSION}/storeDetailAndSubmitThirdParty",
))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoCreate>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PayoutCreateType::get_content_type(self).to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoCreate>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.destination_currency,
)?;
let connector_router_data = adyen::AdyenRouterData::try_from((amount, req))?;
let connector_req = adyen::AdyenPayoutCreateRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoCreate>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutCreateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutCreateType::get_headers(self, req, connectors)?)
.set_body(PayoutCreateType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoCreate>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoCreate>, errors::ConnectorError> {
let response: adyen::AdyenPayoutResponse = res
.response
.parse_struct("AdyenPayoutResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData> for Adyen {
fn get_url(
&self,
req: &PayoutsRouterData<PoEligibility>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = build_env_specific_endpoint(
self.base_url(connectors),
req.test_mode,
&req.connector_meta_data,
)?;
Ok(format!("{endpoint}{ADYEN_API_VERSION}/payments"))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoEligibility>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PayoutEligibilityType::get_content_type(self)
.to_string()
.into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoEligibility>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.destination_currency,
)?;
let connector_router_data = adyen::AdyenRouterData::try_from((amount, req))?;
let connector_req = adyen::AdyenPayoutEligibilityRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoEligibility>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutEligibilityType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutEligibilityType::get_headers(self, req, connectors)?)
.set_body(PayoutEligibilityType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoEligibility>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoEligibility>, errors::ConnectorError> {
let response: adyen::AdyenPayoutResponse = res
.response
.parse_struct("AdyenPayoutResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::PaymentExtendAuthorization for Adyen {}
impl
ConnectorIntegration<ExtendAuthorization, PaymentsExtendAuthorizationData, PaymentsResponseData>
for Adyen
{
fn get_headers(
&self,
req: &PaymentsExtendAuthorizationRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.common_get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsExtendAuthorizationRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req.request.connector_transaction_id.as_str();
let endpoint = build_env_specific_endpoint(
self.base_url(connectors),
req.test_mode,
&req.connector_meta_data,
)?;
Ok(format!(
"{endpoint}{ADYEN_API_VERSION}/payments/{id}/amountUpdates"
))
}
fn get_request_body(
&self,
req: &PaymentsExtendAuthorizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = adyen::AdyenRouterData::try_from((amount, req))?;
let connector_req =
adyen::AdyenExtendAuthorizationRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsExtendAuthorizationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&ExtendedAuthorizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(ExtendedAuthorizationType::get_headers(
self, req, connectors,
)?)
.set_body(ExtendedAuthorizationType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsExtendAuthorizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsExtendAuthorizationRouterData, errors::ConnectorError> {
let response: adyen::AdyenExtendAuthorizationResponse = res
.response
.parse_struct("Adyen AdyenExtendAuthorizationResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Adyen {
fn get_url(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = build_env_specific_endpoint(
connectors.adyen.payout_base_url.as_str(),
req.test_mode,
&req.connector_meta_data,
)?;
let payout_type = req.request.get_payout_type()?;
let path_segment = match payout_type {
enums::PayoutType::Bank | enums::PayoutType::Wallet => "confirmThirdParty",
enums::PayoutType::Card => "payout",
enums::PayoutType::BankRedirect => {
return Err(errors::ConnectorError::NotImplemented(
"bank redirect payouts not supoorted by adyen".to_string(),
)
.into())
}
};
Ok(format!(
"{}pal/servlet/Payout/{}/{}",
endpoint, ADYEN_API_VERSION, path_segment
))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoFulfill>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PayoutFulfillType::get_content_type(self).to_string().into(),
)];
let auth = adyen::AdyenAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let payout_type = req
.request
.payout_type
.to_owned()
.get_required_value("payout_type")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "payout_type",
})?;
let mut api_key = vec![(
headers::X_API_KEY.to_string(),
match payout_type {
enums::PayoutType::Bank
| enums::PayoutType::Wallet
| enums::PayoutType::BankRedirect => {
auth.review_key.unwrap_or(auth.api_key).into_masked()
}
enums::PayoutType::Card => auth.api_key.into_masked(),
},
)];
header.append(&mut api_key);
Ok(header)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoFulfill>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.destination_currency,
)?;
let connector_router_data = adyen::AdyenRouterData::try_from((amount, req))?;
let connector_req = adyen::AdyenPayoutFulfillRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutFulfillType::get_headers(self, req, connectors)?)
.set_body(PayoutFulfillType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoFulfill>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoFulfill>, errors::ConnectorError> {
let response: adyen::AdyenPayoutResponse = res
.response
.parse_struct("AdyenPayoutResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::Refund for Adyen {}
impl api::RefundExecute for Adyen {}
impl api::RefundSync for Adyen {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Adyen {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
RefundExecuteType::get_content_type(self).to_string().into(),
)];
let mut api_header = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_header);
Ok(header)
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
let endpoint = build_env_specific_endpoint(
self.base_url(connectors),
req.test_mode,
&req.connector_meta_data,
)?;
Ok(format!(
"{endpoint}{ADYEN_API_VERSION}/payments/{connector_payment_id}/refunds",
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = adyen::AdyenRouterData::try_from((refund_amount, req))?;
let connector_req = adyen::AdyenRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build(),
))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: adyen::AdyenRefundResponse = res
.response
.parse_struct("AdyenRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Adyen {}
fn get_webhook_object_from_body(
body: &[u8],
) -> CustomResult<adyen::AdyenNotificationRequestItemWH, common_utils::errors::ParsingError> {
let mut webhook: adyen::AdyenIncomingWebhook = body.parse_struct("AdyenIncomingWebhook")?;
let item_object = webhook
.notification_items
.drain(..)
.next()
// TODO: ParsingError doesn't seem to be an apt error for this case
.ok_or(common_utils::errors::ParsingError::UnknownError)?;
Ok(item_object.notification_request_item)
}
#[async_trait::async_trait]
impl IncomingWebhook for Adyen {
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn common_utils::crypto::VerifySignature + Send>, errors::ConnectorError>
{
Ok(Box::new(common_utils::crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let notif_item = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let base64_signature = notif_item.additional_data.hmac_signature.expose();
Ok(base64_signature.as_bytes().to_vec())
}
fn get_webhook_source_verification_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let message = format!(
"{}:{}:{}:{}:{}:{}:{}:{}",
notif.psp_reference,
notif.original_reference.unwrap_or_default(),
notif.merchant_account_code,
notif.merchant_reference,
notif.amount.value,
notif.amount.currency,
notif.event_code,
notif.success
);
Ok(message.into_bytes())
}
async fn verify_webhook_source(
&self,
request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_label,
connector_webhook_details,
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let signature = self
.get_webhook_source_verification_signature(request, &connector_webhook_secrets)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let message = self
.get_webhook_source_verification_message(
request,
merchant_id,
&connector_webhook_secrets,
)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let raw_key = hex::decode(connector_webhook_secrets.secret)
.change_context(errors::ConnectorError::WebhookVerificationSecretInvalid)?;
let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &raw_key);
let signed_messaged = hmac::sign(&signing_key, &message);
let payload_sign = consts::BASE64_ENGINE.encode(signed_messaged.as_ref());
Ok(payload_sign.as_bytes().eq(&signature))
}
fn get_webhook_object_reference_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
// for capture_event, original_reference field will have the authorized payment's PSP reference
if adyen::is_capture_or_cancel_or_adjust_event(¬if.event_code) {
return Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
notif
.original_reference
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?,
),
));
}
if adyen::is_transaction_event(¬if.event_code) {
return Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::PaymentAttemptId(notif.merchant_reference),
));
}
if adyen::is_refund_event(¬if.event_code) {
return Ok(api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::RefundId(notif.merchant_reference),
));
}
if adyen::is_chargeback_event(¬if.event_code) {
return Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
notif
.original_reference
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?,
),
));
}
#[cfg(feature = "payouts")]
if adyen::is_payout_event(¬if.event_code) {
return Ok(api_models::webhooks::ObjectReferenceId::PayoutId(
api_models::webhooks::PayoutIdType::PayoutAttemptId(notif.merchant_reference),
));
}
Err(report!(errors::ConnectorError::WebhookReferenceIdNotFound))
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(transformers::get_adyen_webhook_event(
notif.event_code,
notif.success,
notif.additional_data.dispute_status,
))
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
let response = adyen::AdyenWebhookResponse::from(notif);
Ok(Box::new(response))
}
fn get_webhook_api_response(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_error_kind: Option<IncomingWebhookFlowError>,
) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> {
Ok(ApplicationResponse::TextPlain("[accepted]".to_string()))
}
fn get_dispute_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<disputes::DisputePayload, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let amount = convert_amount(
self.amount_converter_webhooks,
notif.amount.value,
notif.amount.currency,
)?;
Ok(disputes::DisputePayload {
amount,
currency: notif.amount.currency,
dispute_stage: api_models::enums::DisputeStage::from(notif.event_code.clone()),
connector_dispute_id: notif.psp_reference,
connector_reason: notif.reason,
connector_reason_code: notif.additional_data.chargeback_reason_code,
challenge_required_by: notif.additional_data.defense_period_ends_at,
connector_status: notif.event_code.to_string(),
created_at: notif.event_date,
updated_at: notif.event_date,
})
}
fn get_mandate_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Option<hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails>,
errors::ConnectorError,
> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let mandate_reference =
notif
.additional_data
.recurring_detail_reference
.map(|mandate_id| {
hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails {
connector_mandate_id: mandate_id.clone(),
}
});
Ok(mandate_reference)
}
fn get_network_txn_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Option<hyperswitch_domain_models::router_flow_types::ConnectorNetworkTxnId>,
errors::ConnectorError,
> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let optional_network_txn_id =
notif
.additional_data
.network_tx_reference
.map(|network_txn_id| {
hyperswitch_domain_models::router_flow_types::ConnectorNetworkTxnId::new(
network_txn_id,
)
});
Ok(optional_network_txn_id)
}
#[cfg(feature = "v1")]
fn get_additional_payment_method_data(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Option<api_models::payment_methods::PaymentMethodUpdate>,
errors::ConnectorError,
> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let expiry = notif
.additional_data
.expiry_date
.map(|date| transformers::CardExpiry::parse(&date.expose()))
.transpose()?
.ok_or(errors::ConnectorError::ParsingFailed)?;
let month_str = expiry.month();
let year_str = expiry.year();
Ok(Some(api_models::payment_methods::PaymentMethodUpdate {
card: Some(api_models::payment_methods::CardDetailUpdate {
card_exp_month: Some(month_str),
card_exp_year: Some(year_str),
card_holder_name: None,
nick_name: None,
issuer_country: notif.additional_data.card_issuing_country.clone(),
issuer_country_code: None,
card_issuer: notif.additional_data.card_issuing_bank.clone(),
last4_digits: notif
.additional_data
.card_summary
.map(|last4| last4.expose().to_string()),
card_network: adyen::from_payment_method_variant(
notif
.additional_data
.payment_method_variant
.map(|network| network.expose()),
),
}),
wallet: None,
client_secret: None,
}))
}
}
impl Dispute for Adyen {}
impl DefendDispute for Adyen {}
impl AcceptDispute for Adyen {}
impl SubmitEvidence for Adyen {}
impl ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse> for Adyen {
fn get_headers(
&self,
req: &AcceptDisputeRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
AcceptDisputeType::get_content_type(self).to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_url(
&self,
req: &AcceptDisputeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = build_env_specific_endpoint(
connectors.adyen.dispute_base_url.as_str(),
req.test_mode,
&req.connector_meta_data,
)?;
Ok(format!(
"{endpoint}ca/services/DisputeService/v30/acceptDispute",
))
}
fn build_request(
&self,
req: &AcceptDisputeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&AcceptDisputeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(AcceptDisputeType::get_headers(self, req, connectors)?)
.set_body(AcceptDisputeType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn get_request_body(
&self,
req: &AcceptDisputeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = adyen::AdyenAcceptDisputeRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
&self,
data: &AcceptDisputeRouterData,
_event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<AcceptDisputeRouterData, errors::ConnectorError> {
let response: adyen::AdyenDisputeResponse = res
.response
.parse_struct("AdyenDisputeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
RouterData::foreign_try_from((data, response))
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse> for Adyen {
fn get_headers(
&self,
req: &DefendDisputeRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
DefendDisputeType::get_content_type(self).to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_url(
&self,
req: &DefendDisputeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = build_env_specific_endpoint(
connectors.adyen.dispute_base_url.as_str(),
req.test_mode,
&req.connector_meta_data,
)?;
Ok(format!(
"{endpoint}ca/services/DisputeService/v30/defendDispute",
))
}
fn build_request(
&self,
req: &DefendDisputeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&DefendDisputeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(DefendDisputeType::get_headers(self, req, connectors)?)
.set_body(DefendDisputeType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn get_request_body(
&self,
req: &DefendDisputeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = adyen::AdyenDefendDisputeRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
&self,
data: &DefendDisputeRouterData,
_event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<DefendDisputeRouterData, errors::ConnectorError> {
let response: adyen::AdyenDisputeResponse = res
.response
.parse_struct("AdyenDisputeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
RouterData::foreign_try_from((data, response))
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse> for Adyen {
fn get_headers(
&self,
req: &SubmitEvidenceRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
SubmitEvidenceType::get_content_type(self)
.to_string()
.into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_url(
&self,
req: &SubmitEvidenceRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = build_env_specific_endpoint(
connectors.adyen.dispute_base_url.as_str(),
req.test_mode,
&req.connector_meta_data,
)?;
Ok(format!(
"{endpoint}ca/services/DisputeService/v30/supplyDefenseDocument",
))
}
fn get_request_body(
&self,
req: &SubmitEvidenceRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = adyen::Evidence::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &SubmitEvidenceRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&SubmitEvidenceType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(SubmitEvidenceType::get_headers(self, req, connectors)?)
.set_body(SubmitEvidenceType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &SubmitEvidenceRouterData,
_event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SubmitEvidenceRouterData, errors::ConnectorError> {
let response: adyen::AdyenDisputeResponse = res
.response
.parse_struct("AdyenDisputeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
RouterData::foreign_try_from((data, response))
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl UploadFile for Adyen {}
impl RetrieveFile for Adyen {}
impl ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse> for Adyen {}
impl ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse> for Adyen {}
#[async_trait::async_trait]
impl FileUpload for Adyen {
fn validate_file_upload(
&self,
purpose: FilePurpose,
file_size: i32,
file_type: mime::Mime,
) -> CustomResult<(), errors::ConnectorError> {
match purpose {
FilePurpose::DisputeEvidence => {
let supported_file_types =
["image/jpeg", "image/jpg", "image/png", "application/pdf"];
if !supported_file_types.contains(&file_type.to_string().as_str()) {
Err(errors::ConnectorError::FileValidationFailed {
reason: "file_type does not match JPEG, JPG, PNG, or PDF format".to_owned(),
})?
}
//10 MB
if (file_type.to_string().as_str() == "image/jpeg"
|| file_type.to_string().as_str() == "image/jpg"
|| file_type.to_string().as_str() == "image/png")
&& file_size > 10000000
{
Err(errors::ConnectorError::FileValidationFailed {
reason: "file_size exceeded the max file size of 10MB for Image formats"
.to_owned(),
})?
}
//2 MB
if file_type.to_string().as_str() == "application/pdf" && file_size > 2000000 {
Err(errors::ConnectorError::FileValidationFailed {
reason: "file_size exceeded the max file size of 2MB for PDF formats"
.to_owned(),
})?
}
}
}
Ok(())
}
}
impl WebhookRegister for Adyen {}
impl
ConnectorIntegration<
ConnectorWebhookRegister,
ConnectorWebhookRegisterRequest,
ConnectorWebhookRegisterResponse,
> for Adyen
{
fn get_headers(
&self,
req: &ConnectorWebhookRegisterRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
ConnectorWebhookRegisterType::get_content_type(self)
.to_string()
.into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_url(
&self,
req: &ConnectorWebhookRegisterRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = connectors.adyen.management_base_url.as_str();
let auth = adyen::AdyenAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let merchant_id = auth.merchant_account.expose();
Ok(format!("{endpoint}/v3/merchants/{merchant_id}/webhooks",))
}
fn get_request_body(
&self,
req: &ConnectorWebhookRegisterRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = adyen::WebhookRegister::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &ConnectorWebhookRegisterRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&ConnectorWebhookRegisterType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(ConnectorWebhookRegisterType::get_headers(
self, req, connectors,
)?)
.set_body(ConnectorWebhookRegisterType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &ConnectorWebhookRegisterRouterData,
_event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<ConnectorWebhookRegisterRouterData, errors::ConnectorError> {
let response: adyen::AdyenWebhookRegisterResponse = res
.response
.parse_struct("AdyenWebhookRegisterResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
static ADYEN_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods1 = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
enums::CaptureMethod::ManualMultiple,
];
let supported_capture_methods2 = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_capture_methods3 = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Maestro,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
];
let mut adyen_supported_payment_methods = SupportedPaymentMethods::new();
adyen_supported_payment_methods.add(
enums::PaymentMethod::Card,
PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods1.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Card,
PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods1.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods1.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods1.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::Paypal,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods1.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::AliPay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::AliPayHk,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::GoPay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::KakaoPay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::Gcash,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::Momo,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::TouchNGo,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::MbWay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::MobilePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods1.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::WeChatPay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::SamsungPay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods2.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::Paze,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods2.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::Twint,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods2.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::Vipps,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods1.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::Dana,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::Swish,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::PayLater,
PaymentMethodType::Klarna,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods2.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::PayLater,
PaymentMethodType::Affirm,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods1.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::PayLater,
PaymentMethodType::AfterpayClearpay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods1.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::PayLater,
PaymentMethodType::PayBright,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods1.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::PayLater,
PaymentMethodType::Walley,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods2.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::PayLater,
PaymentMethodType::Alma,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods2.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::PayLater,
PaymentMethodType::Atome,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
PaymentMethodType::BancontactCard,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
PaymentMethodType::Bizum,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
PaymentMethodType::Blik,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
PaymentMethodType::Eps,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
PaymentMethodType::Ideal,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
PaymentMethodType::OnlineBankingCzechRepublic,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
PaymentMethodType::OnlineBankingFinland,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
PaymentMethodType::OnlineBankingPoland,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
PaymentMethodType::OnlineBankingSlovakia,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
PaymentMethodType::OnlineBankingFpx,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
PaymentMethodType::OnlineBankingThailand,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
PaymentMethodType::OpenBankingUk,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
PaymentMethodType::Trustly,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankDebit,
PaymentMethodType::Ach,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods2.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankDebit,
PaymentMethodType::Sepa,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods1.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankDebit,
PaymentMethodType::Bacs,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods2.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankTransfer,
PaymentMethodType::PermataBankTransfer,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankTransfer,
PaymentMethodType::BcaBankTransfer,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankTransfer,
PaymentMethodType::BniVa,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankTransfer,
PaymentMethodType::BriVa,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankTransfer,
PaymentMethodType::CimbVa,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankTransfer,
PaymentMethodType::DanamonVa,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankTransfer,
PaymentMethodType::MandiriVa,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::BankTransfer,
PaymentMethodType::Pix,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::CardRedirect,
PaymentMethodType::Knet,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::CardRedirect,
PaymentMethodType::Benefit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::CardRedirect,
PaymentMethodType::MomoAtm,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Voucher,
PaymentMethodType::Boleto,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Voucher,
PaymentMethodType::Alfamart,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Voucher,
PaymentMethodType::Indomaret,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Voucher,
PaymentMethodType::Oxxo,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Voucher,
PaymentMethodType::SevenEleven,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Voucher,
PaymentMethodType::Lawson,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Voucher,
PaymentMethodType::MiniStop,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Voucher,
PaymentMethodType::FamilyMart,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Voucher,
PaymentMethodType::Seicomart,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::Voucher,
PaymentMethodType::PayEasy,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::GiftCard,
PaymentMethodType::PaySafeCard,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods3.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods.add(
enums::PaymentMethod::GiftCard,
PaymentMethodType::Givex,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods2.clone(),
specific_features: None,
},
);
adyen_supported_payment_methods
});
static ADYEN_WEBHOOK_SETUP_CAPABILITIES:
common_types::connector_webhook_configuration::WebhookSetupCapabilities =
common_types::connector_webhook_configuration::WebhookSetupCapabilities {
is_webhook_auto_configuration_supported: true,
requires_webhook_secret: Some(false),
config_type: Some(
common_types::connector_webhook_configuration::WebhookConfigType::AllEvents,
),
};
static ADYEN_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Adyen",
description: "Adyen is a Dutch payment company with the status of an acquiring bank that allows businesses to accept e-commerce, mobile, and point-of-sale payments. It is listed on the stock exchange Euronext Amsterdam",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static ADYEN_SUPPORTED_WEBHOOK_FLOWS: &[enums::EventClass] = &[
enums::EventClass::Payments,
enums::EventClass::Refunds,
enums::EventClass::Disputes,
#[cfg(feature = "payouts")]
enums::EventClass::Payouts,
enums::EventClass::Mandates,
];
impl ConnectorSpecifications for Adyen {
fn is_balance_check_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool {
match current_flow {
api::CurrentFlowInfo::Authorize { request_data, .. } => {
matches!(&request_data.payment_method_data, payment_method_data::PaymentMethodData::GiftCard(giftcard_data) if giftcard_data.is_givex())
}
api::CurrentFlowInfo::SetupMandate { request_data, .. } => {
matches!(&request_data.payment_method_data, payment_method_data::PaymentMethodData::GiftCard(giftcard_data) if giftcard_data.is_givex())
}
api::CurrentFlowInfo::CompleteAuthorize { request_data, .. } => {
matches!(&request_data.payment_method_data, Some(payment_method_data::PaymentMethodData::GiftCard(giftcard_data)) if giftcard_data.is_givex())
}
}
}
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&ADYEN_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*ADYEN_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(ADYEN_SUPPORTED_WEBHOOK_FLOWS)
}
fn generate_connector_customer_id(
&self,
customer_id: &Option<common_utils::id_type::CustomerId>,
merchant_id: &common_utils::id_type::MerchantId,
) -> Option<String> {
customer_id.as_ref().map(|cid| {
format!(
"{}_{}",
merchant_id.get_string_repr(),
cid.get_string_repr()
)
})
}
fn get_api_webhook_config(
&self,
) -> &'static common_types::connector_webhook_configuration::WebhookSetupCapabilities {
&ADYEN_WEBHOOK_SETUP_CAPABILITIES
}
}
|
crates__hyperswitch_connectors__src__connectors__adyenplatform.rs
|
pub mod transformers;
use api_models::{self, webhooks::IncomingWebhookEvent};
#[cfg(feature = "payouts")]
use base64::Engine;
#[cfg(feature = "payouts")]
use common_utils::crypto;
use common_utils::errors::CustomResult;
#[cfg(feature = "payouts")]
use common_utils::ext_traits::{ByteSliceExt as _, BytesExt};
#[cfg(feature = "payouts")]
use common_utils::request::RequestContent;
#[cfg(feature = "payouts")]
use common_utils::request::{Method, Request, RequestBuilder};
#[cfg(feature = "payouts")]
use common_utils::types::MinorUnitForConnector;
#[cfg(feature = "payouts")]
use common_utils::types::{AmountConvertor, MinorUnit};
#[cfg(not(feature = "payouts"))]
use error_stack::report;
use error_stack::ResultExt;
#[cfg(feature = "payouts")]
use http::HeaderName;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::router_data::{ErrorResponse, RouterData};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::router_flow_types::PoFulfill;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::types::{PayoutsData, PayoutsResponseData, PayoutsRouterData};
use hyperswitch_domain_models::{
api::ApplicationResponse,
router_data::{AccessToken, ConnectorAuthType},
router_flow_types::{
AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session,
SetupMandate, Void,
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods,
},
};
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::events::connector_api_logs::ConnectorEvent;
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::types::{PayoutFulfillType, Response};
use hyperswitch_interfaces::{
api::{self, ConnectorCommon, ConnectorIntegration, ConnectorSpecifications},
configs::Connectors,
errors::ConnectorError,
webhooks::{
IncomingWebhook, IncomingWebhookFlowError, IncomingWebhookRequestDetails, WebhookContext,
},
};
use masking::{Mask as _, Maskable, Secret};
#[cfg(feature = "payouts")]
use ring::hmac;
#[cfg(feature = "payouts")]
use router_env::{instrument, tracing};
#[cfg(feature = "payouts")]
use transformers::get_adyen_payout_webhook_event;
use self::transformers as adyenplatform;
use crate::constants::headers;
#[cfg(feature = "payouts")]
use crate::types::ResponseRouterData;
#[cfg(feature = "payouts")]
use crate::utils::convert_amount;
#[derive(Clone)]
pub struct Adyenplatform {
#[cfg(feature = "payouts")]
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Adyenplatform {
pub const fn new() -> &'static Self {
&Self {
#[cfg(feature = "payouts")]
amount_converter: &MinorUnitForConnector,
}
}
}
impl ConnectorCommon for Adyenplatform {
fn id(&self) -> &'static str {
"adyenplatform"
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let auth = adyenplatform::AdyenplatformAuthType::try_from(auth_type)
.change_context(ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.into_masked(),
)])
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.adyenplatform.base_url.as_ref()
}
#[cfg(feature = "payouts")]
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
let response: adyenplatform::AdyenTransferErrorResponse = res
.response
.parse_struct("AdyenTransferErrorResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let message = if let Some(invalid_fields) = &response.invalid_fields {
match serde_json::to_string(invalid_fields) {
Ok(invalid_fields_json) => {
format!("{} Invalid fields: {}", response.title, invalid_fields_json)
}
Err(_) => response.title.clone(),
}
} else if let Some(detail) = &response.detail {
format!("{} Detail: {}", response.title, detail)
} else {
response.title.clone()
};
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_code,
message,
reason: response.detail,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl api::Payment for Adyenplatform {}
impl api::PaymentAuthorize for Adyenplatform {}
impl api::PaymentSync for Adyenplatform {}
impl api::PaymentVoid for Adyenplatform {}
impl api::PaymentCapture for Adyenplatform {}
impl api::MandateSetup for Adyenplatform {}
impl api::ConnectorAccessToken for Adyenplatform {}
impl api::PaymentToken for Adyenplatform {}
impl api::ConnectorValidation for Adyenplatform {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Adyenplatform
{
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Adyenplatform {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Adyenplatform
{
}
impl api::PaymentSession for Adyenplatform {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Adyenplatform {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Adyenplatform {}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Adyenplatform {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for Adyenplatform
{
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Adyenplatform {}
impl api::Payouts for Adyenplatform {}
#[cfg(feature = "payouts")]
impl api::PayoutFulfill for Adyenplatform {}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Adyenplatform {
fn get_url(
&self,
_req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!(
"{}btl/v4/transfers",
connectors.adyenplatform.base_url,
))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoFulfill>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PayoutFulfillType::get_content_type(self).to_string().into(),
)];
let auth = adyenplatform::AdyenplatformAuthType::try_from(&req.connector_auth_type)
.change_context(ConnectorError::FailedToObtainAuthType)?;
let mut api_key = vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.into_masked(),
)];
header.append(&mut api_key);
Ok(header)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoFulfill>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.destination_currency,
)?;
let connector_router_data =
adyenplatform::AdyenPlatformRouterData::try_from((amount, req))?;
let connector_req = adyenplatform::AdyenTransferRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutFulfillType::get_headers(self, req, connectors)?)
.set_body(PayoutFulfillType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoFulfill>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoFulfill>, ConnectorError> {
let response: adyenplatform::AdyenTransferResponse = res
.response
.parse_struct("AdyenTransferResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::Refund for Adyenplatform {}
impl api::RefundExecute for Adyenplatform {}
impl api::RefundSync for Adyenplatform {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Adyenplatform {}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Adyenplatform {}
#[async_trait::async_trait]
impl IncomingWebhook for Adyenplatform {
#[cfg(feature = "payouts")]
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
#[cfg(feature = "payouts")]
fn get_webhook_source_verification_signature(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, ConnectorError> {
let base64_signature = request
.headers
.get(HeaderName::from_static("hmacsignature"))
.ok_or(ConnectorError::WebhookSourceVerificationFailed)?;
Ok(base64_signature.as_bytes().to_vec())
}
#[cfg(feature = "payouts")]
fn get_webhook_source_verification_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, ConnectorError> {
Ok(request.body.to_vec())
}
#[cfg(feature = "payouts")]
async fn verify_webhook_source(
&self,
request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
) -> CustomResult<bool, ConnectorError> {
use common_utils::consts;
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_label,
connector_webhook_details,
)
.await
.change_context(ConnectorError::WebhookSourceVerificationFailed)?;
let signature = self
.get_webhook_source_verification_signature(request, &connector_webhook_secrets)
.change_context(ConnectorError::WebhookSourceVerificationFailed)?;
let message = self
.get_webhook_source_verification_message(
request,
merchant_id,
&connector_webhook_secrets,
)
.change_context(ConnectorError::WebhookSourceVerificationFailed)?;
let raw_key = hex::decode(connector_webhook_secrets.secret)
.change_context(ConnectorError::WebhookVerificationSecretInvalid)?;
let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &raw_key);
let signed_messaged = hmac::sign(&signing_key, &message);
let payload_sign = consts::BASE64_ENGINE.encode(signed_messaged.as_ref());
Ok(payload_sign.as_bytes().eq(&signature))
}
#[cfg(feature = "payouts")]
fn get_payout_webhook_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::PayoutWebhookUpdate, ConnectorError> {
let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request
.body
.parse_struct("AdyenplatformIncomingWebhook")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
let error_reason = webhook_body.data.reason.or(webhook_body
.data
.tracking
.and_then(|tracking_data| tracking_data.reason));
Ok(api_models::webhooks::PayoutWebhookUpdate {
error_message: error_reason.clone(),
error_code: error_reason,
})
}
fn get_webhook_object_reference_id(
&self,
#[cfg(feature = "payouts")] request: &IncomingWebhookRequestDetails<'_>,
#[cfg(not(feature = "payouts"))] _request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, ConnectorError> {
#[cfg(feature = "payouts")]
{
let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request
.body
.parse_struct("AdyenplatformIncomingWebhook")
.change_context(ConnectorError::WebhookSourceVerificationFailed)?;
Ok(api_models::webhooks::ObjectReferenceId::PayoutId(
api_models::webhooks::PayoutIdType::PayoutAttemptId(webhook_body.data.reference),
))
}
#[cfg(not(feature = "payouts"))]
{
Err(report!(ConnectorError::WebhooksNotImplemented))
}
}
fn get_webhook_api_response(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
error_kind: Option<IncomingWebhookFlowError>,
) -> CustomResult<ApplicationResponse<serde_json::Value>, ConnectorError> {
if error_kind.is_some() {
Ok(ApplicationResponse::JsonWithHeaders((
serde_json::Value::Null,
vec![(
"x-http-code".to_string(),
Maskable::Masked(Secret::new("404".to_string())),
)],
)))
} else {
Ok(ApplicationResponse::StatusOk)
}
}
fn get_webhook_event_type(
&self,
#[cfg(feature = "payouts")] request: &IncomingWebhookRequestDetails<'_>,
#[cfg(not(feature = "payouts"))] _request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<IncomingWebhookEvent, ConnectorError> {
#[cfg(feature = "payouts")]
{
let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request
.body
.parse_struct("AdyenplatformIncomingWebhook")
.change_context(ConnectorError::WebhookSourceVerificationFailed)?;
Ok(get_adyen_payout_webhook_event(
webhook_body.webhook_type,
webhook_body.data.status,
webhook_body.data.tracking,
))
}
#[cfg(not(feature = "payouts"))]
{
Err(report!(ConnectorError::WebhooksNotImplemented))
}
}
fn get_webhook_resource_object(
&self,
#[cfg(feature = "payouts")] request: &IncomingWebhookRequestDetails<'_>,
#[cfg(not(feature = "payouts"))] _request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> {
#[cfg(feature = "payouts")]
{
let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request
.body
.parse_struct("AdyenplatformIncomingWebhook")
.change_context(ConnectorError::WebhookSourceVerificationFailed)?;
Ok(Box::new(webhook_body))
}
#[cfg(not(feature = "payouts"))]
{
Err(report!(ConnectorError::WebhooksNotImplemented))
}
}
}
static ADYENPLATFORM_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Adyen Platform",
description: "Adyen Platform for marketplace payouts and disbursements",
connector_type: common_enums::HyperswitchConnectorCategory::PayoutProcessor,
integration_status: common_enums::ConnectorIntegrationStatus::Sandbox,
};
impl ConnectorSpecifications for Adyenplatform {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&ADYENPLATFORM_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
None
}
fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> {
None
}
#[cfg(feature = "v1")]
fn generate_connector_customer_id(
&self,
customer_id: &Option<common_utils::id_type::CustomerId>,
merchant_id: &common_utils::id_type::MerchantId,
) -> Option<String> {
customer_id.as_ref().map(|cid| {
format!(
"{}_{}",
merchant_id.get_string_repr(),
cid.get_string_repr()
)
})
}
}
|
crates__hyperswitch_connectors__src__connectors__adyenplatform__transformers__payouts.rs
|
use api_models::{payouts, webhooks};
use common_enums::enums;
use common_utils::pii;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::types::{self, PayoutsRouterData};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use super::{AdyenPlatformRouterData, Error};
use crate::{
connectors::adyen::transformers as adyen,
types::PayoutsResponseRouterData,
utils::{
self, AdditionalPayoutMethodData as _, AddressDetailsData, CardData,
PayoutFulfillRequestData, PayoutsData as _, RouterData as _,
},
};
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct AdyenPlatformConnectorMetadataObject {
source_balance_account: Option<Secret<String>>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for AdyenPlatformConnectorMetadataObject {
type Error = Error;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(ConnectorError::InvalidConnectorConfig { config: "metadata" })?;
Ok(metadata)
}
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenTransferRequest {
amount: adyen::Amount,
balance_account_id: Secret<String>,
category: AdyenPayoutMethod,
counterparty: AdyenPayoutMethodDetails,
priority: Option<AdyenPayoutPriority>,
reference: String,
reference_for_beneficiary: String,
description: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenPayoutMethod {
Bank,
Card,
PlatformPayment,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenPayoutMethodDetails {
BankAccount(AdyenBankAccountDetails),
Card(AdyenCardDetails),
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenBankAccountDetails {
account_holder: AdyenAccountHolder,
account_identification: AdyenBankAccountIdentification,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenAccountHolder {
address: Option<AdyenAddress>,
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
full_name: Option<Secret<String>>,
email: Option<pii::Email>,
#[serde(rename = "reference")]
customer_id: Option<String>,
#[serde(rename = "type")]
entity_type: Option<EntityType>,
}
#[serde_with::skip_serializing_none]
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenAddress {
line1: Secret<String>,
line2: Secret<String>,
postal_code: Option<Secret<String>>,
state_or_province: Option<Secret<String>>,
city: String,
country: enums::CountryAlpha2,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AdyenBankAccountIdentification {
#[serde(rename = "type")]
bank_type: String,
#[serde(flatten)]
account_details: AdyenBankAccountIdentificationDetails,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AdyenBankAccountIdentificationDetails {
Sepa(SepaDetails),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SepaDetails {
iban: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenCardDetails {
card_holder: AdyenAccountHolder,
card_identification: AdyenCardIdentification,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum AdyenCardIdentification {
Card(AdyenRawCardIdentification),
Stored(AdyenStoredCardIdentification),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenRawCardIdentification {
#[serde(rename = "number")]
card_number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
issue_number: Option<String>,
start_month: Option<String>,
start_year: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenStoredCardIdentification {
stored_payment_method_id: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenPayoutPriority {
Instant,
Fast,
Regular,
Wire,
CrossBorder,
Internal,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EntityType {
Individual,
Organization,
Unknown,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenTransferResponse {
id: String,
account_holder: AdyenPlatformAccountHolder,
amount: adyen::Amount,
balance_account: AdyenBalanceAccount,
category: AdyenPayoutMethod,
category_data: Option<AdyenCategoryData>,
direction: AdyenTransactionDirection,
reference: String,
reference_for_beneficiary: String,
status: AdyenTransferStatus,
#[serde(rename = "type")]
transaction_type: AdyenTransactionType,
reason: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AdyenPlatformAccountHolder {
description: String,
id: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AdyenCategoryData {
priority: AdyenPayoutPriority,
#[serde(rename = "type")]
category: AdyenPayoutMethod,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AdyenBalanceAccount {
description: String,
id: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AdyenTransactionDirection {
Incoming,
Outgoing,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, strum::Display)]
#[serde(rename_all = "lowercase")]
pub enum AdyenTransferStatus {
Authorised,
Refused,
Error,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenTransactionType {
BankTransfer,
CardTransfer,
InternalTransfer,
Payment,
Refund,
}
impl TryFrom<&hyperswitch_domain_models::address::AddressDetails> for AdyenAddress {
type Error = Error;
fn try_from(
address: &hyperswitch_domain_models::address::AddressDetails,
) -> Result<Self, Self::Error> {
let line1 = address
.get_line1()
.change_context(ConnectorError::MissingRequiredField {
field_name: "billing.address.line1",
})?
.clone();
let line2 = address
.get_line2()
.change_context(ConnectorError::MissingRequiredField {
field_name: "billing.address.line2",
})?
.clone();
Ok(Self {
line1,
line2,
postal_code: address.get_optional_zip(),
state_or_province: address.get_optional_state(),
city: address.get_city()?.to_owned(),
country: address.get_country()?.to_owned(),
})
}
}
impl<F> TryFrom<(&PayoutsRouterData<F>, &payouts::CardPayout)> for AdyenAccountHolder {
type Error = Error;
fn try_from(
(router_data, card): (&PayoutsRouterData<F>, &payouts::CardPayout),
) -> Result<Self, Self::Error> {
let billing_address = router_data.get_optional_billing();
let address = billing_address
.and_then(|billing| billing.address.as_ref().map(|addr| addr.try_into()))
.transpose()?
.ok_or(ConnectorError::MissingRequiredField {
field_name: "address",
})?;
let (first_name, last_name) = if let Some(card_holder_name) = &card.card_holder_name {
let exposed_name = card_holder_name.clone().expose();
let name_parts: Vec<&str> = exposed_name.split_whitespace().collect();
let first_name = name_parts
.first()
.map(|s| Secret::new(s.to_string()))
.ok_or(ConnectorError::MissingRequiredField {
field_name: "card_holder_name.first_name",
})?;
let last_name = if name_parts.len() > 1 {
let remaining_names: Vec<&str> = name_parts.iter().skip(1).copied().collect();
Some(Secret::new(remaining_names.join(" ")))
} else {
return Err(ConnectorError::MissingRequiredField {
field_name: "card_holder_name.last_name",
}
.into());
};
(Some(first_name), last_name)
} else {
return Err(ConnectorError::MissingRequiredField {
field_name: "card_holder_name",
}
.into());
};
let customer_id_reference = router_data.get_connector_customer_id()?;
Ok(Self {
address: Some(address),
first_name,
last_name,
full_name: None,
email: router_data.get_optional_billing_email(),
customer_id: Some(customer_id_reference),
entity_type: Some(EntityType::from(router_data.request.entity_type)),
})
}
}
impl<F> TryFrom<(&PayoutsRouterData<F>, &payouts::Bank)> for AdyenAccountHolder {
type Error = Error;
fn try_from(
(router_data, _bank): (&PayoutsRouterData<F>, &payouts::Bank),
) -> Result<Self, Self::Error> {
let billing_address = router_data.get_optional_billing();
let address = billing_address
.and_then(|billing| billing.address.as_ref().map(|addr| addr.try_into()))
.transpose()?
.ok_or(ConnectorError::MissingRequiredField {
field_name: "address",
})?;
let full_name = router_data.get_billing_full_name()?;
let customer_id_reference = router_data.get_connector_customer_id()?;
Ok(Self {
address: Some(address),
first_name: None,
last_name: None,
full_name: Some(full_name),
email: router_data.get_optional_billing_email(),
customer_id: Some(customer_id_reference),
entity_type: Some(EntityType::from(router_data.request.entity_type)),
})
}
}
#[derive(Debug)]
pub struct StoredPaymentCounterparty<'a, F> {
pub item: &'a AdyenPlatformRouterData<&'a PayoutsRouterData<F>>,
pub stored_payment_method_id: String,
}
#[derive(Debug)]
pub struct RawPaymentCounterparty<'a, F> {
pub item: &'a AdyenPlatformRouterData<&'a PayoutsRouterData<F>>,
pub raw_payout_method_data: payouts::PayoutMethodData,
}
impl<F> TryFrom<StoredPaymentCounterparty<'_, F>>
for (AdyenPayoutMethodDetails, Option<AdyenPayoutPriority>)
{
type Error = Error;
fn try_from(stored_payment: StoredPaymentCounterparty<'_, F>) -> Result<Self, Self::Error> {
let request = &stored_payment.item.router_data.request;
let payout_type = request.get_payout_type()?;
match payout_type {
enums::PayoutType::Card => {
let billing_address = stored_payment.item.router_data.get_optional_billing();
let address = billing_address
.and_then(|billing| billing.address.as_ref())
.ok_or(ConnectorError::MissingRequiredField {
field_name: "address",
})?
.try_into()?;
let customer_id_reference = stored_payment
.item
.router_data
.get_connector_customer_id()?;
let required_name: Name = stored_payment.item.router_data.try_into()?;
let card_holder = AdyenAccountHolder {
address: Some(address),
first_name: Some(required_name.first_name.clone()),
last_name: Some(required_name.last_name.clone()),
full_name: Some(required_name.get_full_name()),
email: stored_payment.item.router_data.get_optional_billing_email(),
customer_id: Some(customer_id_reference),
entity_type: Some(EntityType::from(request.entity_type)),
};
let card_identification =
AdyenCardIdentification::Stored(AdyenStoredCardIdentification {
stored_payment_method_id: Secret::new(
stored_payment.stored_payment_method_id,
),
});
let counterparty = AdyenPayoutMethodDetails::Card(AdyenCardDetails {
card_holder,
card_identification,
});
Ok((counterparty, None))
}
_ => Err(ConnectorError::NotSupported {
message: "Stored payment method is only supported for card payouts".to_string(),
connector: "Adyenplatform",
}
.into()),
}
}
}
struct Name {
first_name: Secret<String>,
last_name: Secret<String>,
}
impl Name {
fn get_full_name(&self) -> Secret<String> {
Secret::new(format!(
"{} {}",
self.first_name.peek(),
self.last_name.peek()
))
}
}
impl<F> TryFrom<&PayoutsRouterData<F>> for Name {
type Error = Error;
fn try_from(router_data: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let card_holder_name = router_data
.request
.get_optional_additional_payout_method_data()
.and_then(|additional_data| additional_data.get_optional_card_holder_name());
let billing_first_name = router_data
.get_optional_billing_first_name()
.map(|first_name| Secret::new(first_name.peek().trim().to_string()));
let billing_last_name = router_data
.get_optional_billing_last_name()
.map(|last_name| Secret::new(last_name.peek().trim().to_string()));
let mut should_fallback = billing_first_name.is_none() || billing_last_name.is_none();
//check for empty first name
billing_first_name.clone().inspect(|first_name| {
should_fallback = first_name.peek().is_empty() || should_fallback;
});
// check for empty last name
billing_last_name.clone().inspect(|last_name| {
should_fallback = last_name.peek().is_empty() || should_fallback;
});
// get first_name from the billing
// if not present in billing, get from card_holder_name
let first_name = if should_fallback {
card_holder_name.clone().and_then(|full_name| {
let mut name_collection = full_name.peek().split_whitespace();
name_collection
.next()
.map(|first_name| Secret::new(first_name.to_string()))
})
} else {
billing_first_name
};
// get last_name from the billing
// if not present in billing, get from card_holder_name
let last_name = if should_fallback {
card_holder_name.map(|full_name| {
let mut name_collection = full_name.peek().split_whitespace();
let _first_name = name_collection.next();
Secret::new(name_collection.collect::<Vec<_>>().join(" "))
})
} else {
billing_last_name
};
Ok(Self {
first_name: first_name.ok_or(ConnectorError::MissingRequiredField {
field_name: "first_name",
})?,
last_name: last_name.ok_or(ConnectorError::MissingRequiredField {
field_name: "first_name",
})?,
})
}
}
impl<F> TryFrom<RawPaymentCounterparty<'_, F>>
for (AdyenPayoutMethodDetails, Option<AdyenPayoutPriority>)
{
type Error = Error;
fn try_from(raw_payment: RawPaymentCounterparty<'_, F>) -> Result<Self, Self::Error> {
let request = &raw_payment.item.router_data.request;
match raw_payment.raw_payout_method_data {
payouts::PayoutMethodData::Wallet(_)
| payouts::PayoutMethodData::BankRedirect(_)
| payouts::PayoutMethodData::Passthrough(_) => Err(ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyenplatform"),
))?,
payouts::PayoutMethodData::Card(c) => {
let card_holder: AdyenAccountHolder =
(raw_payment.item.router_data, &c).try_into()?;
let card_identification =
AdyenCardIdentification::Card(AdyenRawCardIdentification {
expiry_year: c.get_expiry_year_4_digit(),
card_number: c.card_number,
expiry_month: c.expiry_month,
issue_number: None,
start_month: None,
start_year: None,
});
let counterparty = AdyenPayoutMethodDetails::Card(AdyenCardDetails {
card_holder,
card_identification,
});
Ok((counterparty, None))
}
payouts::PayoutMethodData::Bank(bd) => {
let account_holder: AdyenAccountHolder =
(raw_payment.item.router_data, &bd).try_into()?;
let bank_details = match bd {
payouts::Bank::Sepa(b) => AdyenBankAccountIdentification {
bank_type: "iban".to_string(),
account_details: AdyenBankAccountIdentificationDetails::Sepa(SepaDetails {
iban: b.iban,
}),
},
payouts::Bank::Ach(..) => Err(ConnectorError::NotSupported {
message: "Bank transfer via ACH is not supported".to_string(),
connector: "Adyenplatform",
})?,
payouts::Bank::Bacs(..) => Err(ConnectorError::NotSupported {
message: "Bank transfer via Bacs is not supported".to_string(),
connector: "Adyenplatform",
})?,
payouts::Bank::Pix(..) => Err(ConnectorError::NotSupported {
message: "Bank transfer via Pix is not supported".to_string(),
connector: "Adyenplatform",
})?,
};
let counterparty = AdyenPayoutMethodDetails::BankAccount(AdyenBankAccountDetails {
account_holder,
account_identification: bank_details,
});
let priority = request
.priority
.ok_or(ConnectorError::MissingRequiredField {
field_name: "priority",
})?;
Ok((counterparty, Some(AdyenPayoutPriority::from(priority))))
}
}
}
}
impl<F> TryFrom<&AdyenPlatformRouterData<&PayoutsRouterData<F>>> for AdyenTransferRequest {
type Error = Error;
fn try_from(
item: &AdyenPlatformRouterData<&PayoutsRouterData<F>>,
) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
let stored_payment_method_result =
item.router_data.request.get_connector_transfer_method_id();
let raw_payout_method_result = item.router_data.get_payout_method_data();
let (counterparty, priority) =
if let Ok(stored_payment_method_id) = stored_payment_method_result {
StoredPaymentCounterparty {
item,
stored_payment_method_id,
}
.try_into()?
} else if let Ok(raw_payout_method_data) = raw_payout_method_result {
RawPaymentCounterparty {
item,
raw_payout_method_data,
}
.try_into()?
} else {
return Err(ConnectorError::MissingRequiredField {
field_name: "payout_method_data or stored_payment_method_id",
}
.into());
};
let adyen_connector_metadata_object =
AdyenPlatformConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?;
let balance_account_id = adyen_connector_metadata_object
.source_balance_account
.ok_or(ConnectorError::InvalidConnectorConfig {
config: "metadata.source_balance_account",
})?;
let payout_type = request.get_payout_type()?;
Ok(Self {
amount: adyen::Amount {
value: item.amount,
currency: request.destination_currency,
},
balance_account_id,
category: AdyenPayoutMethod::try_from(payout_type)?,
counterparty,
priority,
reference: item.router_data.connector_request_reference_id.clone(),
reference_for_beneficiary: item.router_data.connector_request_reference_id.clone(),
description: item.router_data.description.clone(),
})
}
}
impl<F> TryFrom<PayoutsResponseRouterData<F, AdyenTransferResponse>> for PayoutsRouterData<F> {
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, AdyenTransferResponse>,
) -> Result<Self, Self::Error> {
let response: AdyenTransferResponse = item.response;
let status = enums::PayoutStatus::from(response.status);
if matches!(status, enums::PayoutStatus::Failed) {
return Ok(Self {
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: response.status.to_string(),
message: if !response.reason.is_empty() {
response.reason
} else {
response.status.to_string()
},
reason: None,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(response.id),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
});
}
Ok(Self {
response: Ok(types::PayoutsResponseData {
status: Some(status),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
impl From<AdyenTransferStatus> for enums::PayoutStatus {
fn from(adyen_status: AdyenTransferStatus) -> Self {
match adyen_status {
AdyenTransferStatus::Authorised => Self::Initiated,
AdyenTransferStatus::Error | AdyenTransferStatus::Refused => Self::Failed,
}
}
}
impl From<enums::PayoutEntityType> for EntityType {
fn from(entity: enums::PayoutEntityType) -> Self {
match entity {
enums::PayoutEntityType::Individual
| enums::PayoutEntityType::Personal
| enums::PayoutEntityType::NaturalPerson => Self::Individual,
enums::PayoutEntityType::Company | enums::PayoutEntityType::Business => {
Self::Organization
}
_ => Self::Unknown,
}
}
}
impl From<enums::PayoutSendPriority> for AdyenPayoutPriority {
fn from(entity: enums::PayoutSendPriority) -> Self {
match entity {
enums::PayoutSendPriority::Instant => Self::Instant,
enums::PayoutSendPriority::Fast => Self::Fast,
enums::PayoutSendPriority::Regular => Self::Regular,
enums::PayoutSendPriority::Wire => Self::Wire,
enums::PayoutSendPriority::CrossBorder => Self::CrossBorder,
enums::PayoutSendPriority::Internal => Self::Internal,
}
}
}
impl TryFrom<enums::PayoutType> for AdyenPayoutMethod {
type Error = Error;
fn try_from(payout_type: enums::PayoutType) -> Result<Self, Self::Error> {
match payout_type {
enums::PayoutType::Bank => Ok(Self::Bank),
enums::PayoutType::Card => Ok(Self::Card),
enums::PayoutType::Wallet | enums::PayoutType::BankRedirect => {
Err(report!(ConnectorError::NotSupported {
message: "Bakredirect or wallet payouts".to_string(),
connector: "Adyenplatform",
}))
}
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenplatformIncomingWebhook {
pub data: AdyenplatformIncomingWebhookData,
#[serde(rename = "type")]
pub webhook_type: AdyenplatformWebhookEventType,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenplatformIncomingWebhookData {
pub status: AdyenplatformWebhookStatus,
pub reference: String,
pub tracking: Option<AdyenplatformTrackingData>,
pub reason: Option<String>,
pub category: Option<AdyenPayoutMethod>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenplatformTrackingData {
pub status: TrackingStatus,
pub reason: Option<String>,
pub estimated_arrival_time: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum TrackingStatus {
Accepted,
Pending,
Credited,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum AdyenplatformWebhookEventType {
#[serde(rename = "balancePlatform.transfer.created")]
PayoutCreated,
#[serde(rename = "balancePlatform.transfer.updated")]
PayoutUpdated,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenplatformWebhookStatus {
Authorised,
Booked,
Pending,
Failed,
Returned,
Received,
}
pub fn get_adyen_payout_webhook_event(
event_type: AdyenplatformWebhookEventType,
status: AdyenplatformWebhookStatus,
tracking_data: Option<AdyenplatformTrackingData>,
) -> webhooks::IncomingWebhookEvent {
match (event_type, status, tracking_data) {
(AdyenplatformWebhookEventType::PayoutCreated, _, _) => {
webhooks::IncomingWebhookEvent::PayoutCreated
}
(AdyenplatformWebhookEventType::PayoutUpdated, _, Some(tracking_data)) => {
match tracking_data.status {
TrackingStatus::Credited | TrackingStatus::Accepted => {
webhooks::IncomingWebhookEvent::PayoutSuccess
}
TrackingStatus::Pending => webhooks::IncomingWebhookEvent::PayoutProcessing,
}
}
(AdyenplatformWebhookEventType::PayoutUpdated, status, _) => match status {
AdyenplatformWebhookStatus::Authorised | AdyenplatformWebhookStatus::Received => {
webhooks::IncomingWebhookEvent::PayoutCreated
}
AdyenplatformWebhookStatus::Booked | AdyenplatformWebhookStatus::Pending => {
webhooks::IncomingWebhookEvent::PayoutProcessing
}
AdyenplatformWebhookStatus::Failed => webhooks::IncomingWebhookEvent::PayoutFailure,
AdyenplatformWebhookStatus::Returned => webhooks::IncomingWebhookEvent::PayoutReversed,
},
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenTransferErrorResponse {
pub error_code: String,
#[serde(rename = "type")]
pub error_type: String,
pub status: u16,
pub title: String,
pub detail: Option<String>,
pub request_id: Option<String>,
pub invalid_fields: Option<Vec<AdyenInvalidField>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenInvalidField {
pub name: Option<String>,
pub value: Option<String>,
pub message: Option<String>,
}
|
crates__hyperswitch_connectors__src__connectors__affirm.rs
|
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{
Authorize, Capture, CompleteAuthorize, PSync, PaymentMethodToken, Session,
SetupMandate, Void,
},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{Mask, PeekInterface};
use transformers as affirm;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Affirm {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Affirm {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Affirm {}
impl api::PaymentSession for Affirm {}
impl api::ConnectorAccessToken for Affirm {}
impl api::MandateSetup for Affirm {}
impl api::PaymentAuthorize for Affirm {}
impl api::PaymentsCompleteAuthorize for Affirm {}
impl api::PaymentSync for Affirm {}
impl api::PaymentCapture for Affirm {}
impl api::PaymentVoid for Affirm {}
impl api::Refund for Affirm {}
impl api::RefundExecute for Affirm {}
impl api::RefundSync for Affirm {}
impl api::PaymentToken for Affirm {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Affirm
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Affirm
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Affirm {
fn id(&self) -> &'static str {
"affirm"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.affirm.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = affirm::AffirmAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let encoded_api_key = BASE64_ENGINE.encode(format!(
"{}:{}",
auth.public_key.peek(),
auth.private_key.peek()
));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Basic {encoded_api_key}").into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: affirm::AffirmErrorResponse = res
.response
.parse_struct("AffirmErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: response.status_code,
code: response.code,
message: response.message,
reason: Some(response.error_type),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Affirm {
fn validate_mandate_payment(
&self,
_pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
match pm_data {
PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
"validate_mandate_payment does not support cards".to_string(),
)
.into()),
_ => Ok(()),
}
}
fn validate_psync_reference_id(
&self,
_data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
Ok(())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Affirm {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Affirm {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Affirm {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Affirm {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
Ok(format!("{endpoint}/v2/checkout/direct"))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = affirm::AffirmRouterData::from((amount, req));
let connector_req = affirm::AffirmPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: affirm::AffirmResponseWrapper = res
.response
.parse_struct("Affirm PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Affirm
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
Ok(format!("{endpoint}/v1/transactions"))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = affirm::AffirmCompleteAuthorizeRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: affirm::AffirmCompleteAuthorizeResponse = res
.response
.parse_struct("Affirm PaymentsCompleteAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Affirm {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
let transaction_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!("{endpoint}/v1/transactions/{transaction_id}",))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: affirm::AffirmResponseWrapper = res
.response
.parse_struct("affirm PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Affirm {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
let transaction_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{endpoint}/v1/transactions/{transaction_id}/capture"
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = affirm::AffirmRouterData::from((amount, req));
let connector_req = affirm::AffirmCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: affirm::AffirmCaptureResponse = res
.response
.parse_struct("Affirm PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Affirm {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
let transaction_id = req.request.connector_transaction_id.clone();
Ok(format!("{endpoint}/v1/transactions/{transaction_id}/void"))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = affirm::AffirmCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: affirm::AffirmCancelResponse = res
.response
.parse_struct("GetnetPaymentsVoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Affirm {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
let transaction_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{endpoint}/v1/transactions/{transaction_id}/refund"
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = affirm::AffirmRouterData::from((refund_amount, req));
let connector_req = affirm::AffirmRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: affirm::AffirmRefundResponse = res
.response
.parse_struct("affirm RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Affirm {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
let transaction_id = req.request.connector_transaction_id.clone();
Ok(format!("{endpoint}/v1/transactions/{transaction_id}"))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: affirm::AffirmRsyncResponse = res
.response
.parse_struct("affirm RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Affirm {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static AFFIRM_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
];
let mut affirm_supported_payment_methods = SupportedPaymentMethods::new();
affirm_supported_payment_methods.add(
enums::PaymentMethod::PayLater,
enums::PaymentMethodType::Affirm,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
affirm_supported_payment_methods
});
static AFFIRM_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Affirm",
description: "Affirm connector is a payment gateway integration that processes Affirm’s buy now, pay later financing by managing payment authorization, capture, refunds, and transaction sync via Affirm’s API.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static AFFIRM_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Affirm {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&AFFIRM_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*AFFIRM_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&AFFIRM_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__affirm__transformers.rs
|
use common_enums::{enums, CountryAlpha2, Currency};
use common_utils::{pii, request::Method, types::MinorUnit};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::{PayLaterData, PaymentMethodData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
RefundsResponseRouterData, ResponseRouterData,
},
utils::{PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
pub struct AffirmRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for AffirmRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize)]
pub struct AffirmPaymentsRequest {
pub merchant: Merchant,
pub items: Vec<Item>,
pub shipping: Option<Shipping>,
pub billing: Option<Billing>,
pub total: MinorUnit,
pub currency: Currency,
pub order_id: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct AffirmCompleteAuthorizeRequest {
pub order_id: Option<String>,
pub reference_id: Option<String>,
pub transaction_id: String,
}
impl TryFrom<&PaymentsCompleteAuthorizeRouterData> for AffirmCompleteAuthorizeRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> {
let transaction_id = item.request.connector_transaction_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_transaction_id",
},
)?;
let reference_id = item.reference_id.clone();
let order_id = item.connector_request_reference_id.clone();
Ok(Self {
transaction_id,
order_id: Some(order_id),
reference_id,
})
}
}
#[derive(Debug, Serialize)]
pub struct Merchant {
pub public_api_key: Secret<String>,
pub user_confirmation_url: String,
pub user_cancel_url: String,
pub user_confirmation_url_action: Option<String>,
pub use_vcn: Option<String>,
pub name: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct Item {
pub display_name: String,
pub sku: String,
pub unit_price: MinorUnit,
pub qty: i64,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Shipping {
pub name: Name,
pub address: Address,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone_number: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<pii::Email>,
}
#[derive(Debug, Serialize)]
pub struct Billing {
pub name: Name,
pub address: Address,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone_number: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<pii::Email>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Name {
pub first: Option<Secret<String>>,
pub last: Option<Secret<String>>,
pub full: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Address {
pub line1: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub line2: Option<Secret<String>>,
pub city: Option<String>,
pub state: Option<Secret<String>>,
pub zipcode: Option<Secret<String>>,
pub country: Option<CountryAlpha2>,
}
#[derive(Debug, Serialize)]
pub struct Metadata {
#[serde(skip_serializing_if = "Option::is_none")]
pub shipping_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub entity_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub platform_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub platform_version: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub platform_affirm: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub webhook_session_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mode: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub itinerary: Option<Vec<Value>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub checkout_channel_type: Option<String>,
#[serde(rename = "BOPIS", skip_serializing_if = "Option::is_none")]
pub bopis: Option<bool>,
}
#[derive(Debug, Serialize)]
pub struct Discount {
pub discount_amount: MinorUnit,
pub discount_display_name: String,
pub discount_code: Option<String>,
}
impl TryFrom<&AffirmRouterData<&PaymentsAuthorizeRouterData>> for AffirmPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AffirmRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let router_data = &item.router_data;
let request = &router_data.request;
let billing = Some(Billing {
name: Name {
first: item.router_data.get_optional_billing_first_name(),
last: item.router_data.get_optional_billing_last_name(),
full: item.router_data.get_optional_billing_full_name(),
},
address: Address {
line1: item.router_data.get_optional_billing_line1(),
line2: item.router_data.get_optional_billing_line2(),
city: item.router_data.get_optional_billing_city(),
state: item.router_data.get_optional_billing_state(),
zipcode: item.router_data.get_optional_billing_zip(),
country: item.router_data.get_optional_billing_country(),
},
phone_number: item.router_data.get_optional_billing_phone_number(),
email: item.router_data.get_optional_billing_email(),
});
let shipping = Some(Shipping {
name: Name {
first: item.router_data.get_optional_shipping_first_name(),
last: item.router_data.get_optional_shipping_last_name(),
full: item.router_data.get_optional_shipping_full_name(),
},
address: Address {
line1: item.router_data.get_optional_shipping_line1(),
line2: item.router_data.get_optional_shipping_line2(),
city: item.router_data.get_optional_shipping_city(),
state: item.router_data.get_optional_shipping_state(),
zipcode: item.router_data.get_optional_shipping_zip(),
country: item.router_data.get_optional_shipping_country(),
},
phone_number: item.router_data.get_optional_shipping_phone_number(),
email: item.router_data.get_optional_shipping_email(),
});
match request.payment_method_data.clone() {
PaymentMethodData::PayLater(PayLaterData::AffirmRedirect {}) => {
let items = match request.order_details.clone() {
Some(order_details) => order_details
.iter()
.map(|data| {
Ok(Item {
display_name: data.product_name.clone(),
sku: data.product_id.clone().unwrap_or_default(),
unit_price: data.amount,
qty: data.quantity.into(),
})
})
.collect::<Result<Vec<_>, _>>(),
None => Err(report!(errors::ConnectorError::MissingRequiredField {
field_name: "order_details",
})),
}?;
let auth_type = AffirmAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let public_api_key = auth_type.public_key;
let merchant = Merchant {
public_api_key,
user_confirmation_url: request.get_complete_authorize_url()?,
user_cancel_url: request.get_router_return_url()?,
user_confirmation_url_action: None,
use_vcn: None,
name: None,
};
Ok(Self {
merchant,
items,
shipping,
billing,
total: item.amount,
currency: request.currency,
order_id: Some(item.router_data.connector_request_reference_id.clone()),
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
pub struct AffirmAuthType {
pub public_key: Secret<String>,
pub private_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AffirmAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
public_key: api_key.to_owned(),
private_key: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl From<AffirmTransactionStatus> for common_enums::AttemptStatus {
fn from(item: AffirmTransactionStatus) -> Self {
match item {
AffirmTransactionStatus::Authorized => Self::Authorized,
AffirmTransactionStatus::AuthExpired => Self::Failure,
AffirmTransactionStatus::Canceled => Self::Voided,
AffirmTransactionStatus::Captured => Self::Charged,
AffirmTransactionStatus::ConfirmationExpired => Self::Failure,
AffirmTransactionStatus::Confirmed => Self::Authorized,
AffirmTransactionStatus::Created => Self::Pending,
AffirmTransactionStatus::Declined => Self::Failure,
AffirmTransactionStatus::Disputed => Self::Unresolved,
AffirmTransactionStatus::DisputeRefunded => Self::Unresolved,
AffirmTransactionStatus::ExpiredAuthorization => Self::Failure,
AffirmTransactionStatus::ExpiredConfirmation => Self::Failure,
AffirmTransactionStatus::PartiallyCaptured => Self::Charged,
AffirmTransactionStatus::Voided => Self::Voided,
AffirmTransactionStatus::PartiallyVoided => Self::Voided,
}
}
}
impl From<AffirmRefundStatus> for common_enums::RefundStatus {
fn from(item: AffirmRefundStatus) -> Self {
match item {
AffirmRefundStatus::PartiallyRefunded => Self::Success,
AffirmRefundStatus::Refunded => Self::Success,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AffirmPaymentsResponse {
checkout_id: String,
redirect_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmCompleteAuthorizeResponse {
pub id: String,
pub status: AffirmTransactionStatus,
pub amount: MinorUnit,
pub amount_refunded: MinorUnit,
pub authorization_expiration: String,
pub checkout_id: String,
pub created: String,
pub currency: Currency,
pub events: Vec<TransactionEvent>,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
pub provider_id: Option<i64>,
pub remove_tax: Option<bool>,
pub checkout: Option<Value>,
pub refund_expires: Option<String>,
pub remaining_capturable_amount: Option<i64>,
pub loan_information: Option<LoanInformation>,
pub user_id: Option<String>,
pub platform: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct TransactionEvent {
pub id: String,
pub amount: MinorUnit,
pub created: String,
pub currency: Currency,
pub fee: Option<i64>,
pub fee_refunded: Option<MinorUnit>,
pub reference_id: Option<String>,
#[serde(rename = "type")]
pub event_type: AffirmEventType,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct LoanInformation {
pub fees: Option<LoanFees>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct LoanFees {
pub amount: Option<MinorUnit>,
pub description: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AffirmTransactionStatus {
Authorized,
AuthExpired,
Canceled,
Captured,
ConfirmationExpired,
Confirmed,
Created,
Declined,
Disputed,
DisputeRefunded,
ExpiredAuthorization,
ExpiredConfirmation,
PartiallyCaptured,
Voided,
PartiallyVoided,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AffirmRefundStatus {
PartiallyRefunded,
Refunded,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmPSyncResponse {
pub amount: MinorUnit,
pub amount_refunded: MinorUnit,
pub authorization_expiration: Option<String>,
pub checkout_id: String,
pub created: String,
pub currency: Currency,
pub events: Vec<TransactionEvent>,
pub id: String,
pub order_id: String,
pub provider_id: Option<i64>,
pub remove_tax: Option<bool>,
pub status: AffirmTransactionStatus,
pub checkout: Option<Value>,
pub refund_expires: Option<String>,
pub remaining_capturable_amount: Option<MinorUnit>,
pub loan_information: Option<LoanInformation>,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub merchant_transaction_id: Option<String>,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmRsyncResponse {
pub amount: MinorUnit,
pub amount_refunded: MinorUnit,
pub authorization_expiration: String,
pub checkout_id: String,
pub created: String,
pub currency: Currency,
pub events: Vec<TransactionEvent>,
pub id: String,
pub order_id: String,
pub status: AffirmRefundStatus,
pub refund_expires: Option<String>,
pub remaining_capturable_amount: Option<MinorUnit>,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub merchant_transaction_id: Option<String>,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AffirmResponseWrapper {
Authorize(AffirmPaymentsResponse),
Psync(Box<AffirmPSyncResponse>),
}
impl<F, T> TryFrom<ResponseRouterData<F, AffirmResponseWrapper, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AffirmResponseWrapper, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match &item.response {
AffirmResponseWrapper::Authorize(resp) => {
let redirection_data = url::Url::parse(&resp.redirect_url)
.ok()
.map(|url| RedirectForm::from((url, Method::Get)));
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(resp.checkout_id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
authentication_data: None,
charges: None,
incremental_authorization_allowed: None,
}),
..item.data
})
}
AffirmResponseWrapper::Psync(resp) => {
let status = enums::AttemptStatus::from(resp.status);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(resp.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
authentication_data: None,
charges: None,
incremental_authorization_allowed: None,
}),
..item.data
})
}
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AffirmCompleteAuthorizeResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AffirmCompleteAuthorizeResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct AffirmRefundRequest {
pub amount: MinorUnit,
#[serde(skip_serializing_if = "Option::is_none")]
pub reference_id: Option<String>,
}
impl<F> TryFrom<&AffirmRouterData<&RefundsRouterData<F>>> for AffirmRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AffirmRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let reference_id = item.router_data.request.connector_transaction_id.clone();
Ok(Self {
amount: item.amount.to_owned(),
reference_id: Some(reference_id),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmRefundResponse {
pub id: String,
pub amount: MinorUnit,
pub created: String,
pub currency: Currency,
pub fee: Option<MinorUnit>,
pub fee_refunded: Option<MinorUnit>,
pub reference_id: Option<String>,
#[serde(rename = "type")]
pub event_type: AffirmEventType,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
}
impl From<AffirmEventType> for enums::RefundStatus {
fn from(event_type: AffirmEventType) -> Self {
match event_type {
AffirmEventType::Refund => Self::Success,
_ => Self::Pending,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, AffirmRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, AffirmRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.event_type),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, AffirmRsyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, AffirmRsyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct AffirmErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
#[serde(rename = "type")]
pub error_type: String,
}
#[derive(Debug, Serialize)]
pub struct AffirmCaptureRequest {
pub order_id: Option<String>,
pub reference_id: Option<String>,
pub amount: MinorUnit,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
}
impl TryFrom<&AffirmRouterData<&PaymentsCaptureRouterData>> for AffirmCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AffirmRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let reference_id = match item.router_data.connector_request_reference_id.clone() {
ref_id if ref_id.is_empty() => None,
ref_id => Some(ref_id),
};
let amount = item.amount;
Ok(Self {
reference_id,
amount,
order_id: None,
shipping_carrier: None,
shipping_confirmation: None,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmCaptureResponse {
pub id: String,
pub amount: MinorUnit,
pub created: String,
pub currency: Currency,
pub fee: Option<MinorUnit>,
pub fee_refunded: Option<MinorUnit>,
pub reference_id: Option<String>,
#[serde(rename = "type")]
pub event_type: AffirmEventType,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AffirmEventType {
Auth,
AuthExpired,
Capture,
ChargeOff,
Confirm,
ConfirmationExpired,
ExpireAuthorization,
ExpireConfirmation,
Refund,
SplitCapture,
Update,
Void,
PartialVoid,
RefundVoided,
}
impl From<AffirmEventType> for enums::AttemptStatus {
fn from(event_type: AffirmEventType) -> Self {
match event_type {
AffirmEventType::Auth => Self::Authorized,
AffirmEventType::Capture | AffirmEventType::SplitCapture | AffirmEventType::Confirm => {
Self::Charged
}
AffirmEventType::AuthExpired
| AffirmEventType::ChargeOff
| AffirmEventType::ConfirmationExpired
| AffirmEventType::ExpireAuthorization
| AffirmEventType::ExpireConfirmation => Self::Failure,
AffirmEventType::Refund | AffirmEventType::RefundVoided => Self::AutoRefunded,
AffirmEventType::Update => Self::Pending,
AffirmEventType::Void | AffirmEventType::PartialVoid => Self::Voided,
}
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<AffirmCaptureResponse>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<AffirmCaptureResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.event_type.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for AffirmCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let request = &item.request;
let reference_id = request.connector_transaction_id.clone();
let amount = item
.request
.amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "amount",
})?;
Ok(Self {
reference_id: Some(reference_id),
amount,
merchant_transaction_id: None,
})
}
}
#[derive(Debug, Serialize)]
pub struct AffirmCancelRequest {
pub reference_id: Option<String>,
pub amount: i64,
pub merchant_transaction_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmCancelResponse {
pub id: String,
pub amount: MinorUnit,
pub created: String,
pub currency: Currency,
pub fee: Option<MinorUnit>,
pub fee_refunded: Option<MinorUnit>,
pub reference_id: Option<String>,
#[serde(rename = "type")]
pub event_type: AffirmEventType,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
}
impl TryFrom<PaymentsCancelResponseRouterData<AffirmCancelResponse>> for PaymentsCancelRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<AffirmCancelResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.event_type.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
|
crates__hyperswitch_connectors__src__connectors__airwallex__transformers.rs
|
use common_enums::enums;
use common_utils::{
errors::ParsingError,
ext_traits::ValueExt,
id_type,
pii::{Email, IpAddress},
request::Method,
types::{MinorUnit, StringMajorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{
BankRedirectData, BankTransferData, PayLaterData, PaymentMethodData, WalletData,
},
router_data::{AccessToken, ConnectorAuthType, RouterData},
router_flow_types::{
refunds::{Execute, RSync},
PSync,
},
router_request_types::{PaymentsSyncData, ResponseId},
router_response_types::{
ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, RedirectForm,
RefundsResponseData,
},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use url::Url;
use uuid::Uuid;
use crate::{
types::{CreateOrderResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, BrowserInformationData, CardData as _, ForeignTryFrom, PaymentsAuthorizeRequestData,
PhoneDetailsData, RouterData as _,
},
};
pub struct AirwallexAuthType {
pub x_api_key: Secret<String>,
pub x_client_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AirwallexAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
x_api_key: api_key.clone(),
x_client_id: key1.clone(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct ReferrerData {
#[serde(rename = "type")]
r_type: String,
version: String,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct AirwallexIntentRequest {
// Unique ID to be sent for each transaction/operation request to the connector
request_id: String,
amount: StringMajorUnit,
currency: enums::Currency,
//ID created in merchant's order system that corresponds to this PaymentIntent.
merchant_order_id: String,
// This data is required to whitelist Hyperswitch at Airwallex.
referrer_data: ReferrerData,
order: Option<AirwallexOrderData>,
}
impl TryFrom<&AirwallexRouterData<&types::CreateOrderRouterData>> for AirwallexIntentRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AirwallexRouterData<&types::CreateOrderRouterData>,
) -> Result<Self, Self::Error> {
let referrer_data = ReferrerData {
r_type: "hyperswitch".to_string(),
version: "1.0.0".to_string(),
};
let amount = item.amount.clone();
let currency = item.router_data.request.currency;
let order = match item.router_data.request.payment_method_data {
Some(PaymentMethodData::PayLater(_)) => Some(
item.router_data
.request
.order_details
.as_ref()
.map(|order_data| AirwallexOrderData {
products: order_data
.iter()
.map(|product| AirwallexProductData {
name: product.product_name.clone(),
quantity: product.quantity,
unit_price: product.amount,
})
.collect(),
shipping: Some(AirwallexShippingData {
first_name: item.router_data.get_optional_shipping_first_name(),
last_name: item.router_data.get_optional_shipping_last_name(),
phone_number: item.router_data.get_optional_shipping_phone_number(),
address: AirwallexPLShippingAddress {
country_code: item.router_data.get_optional_shipping_country(),
city: item.router_data.get_optional_shipping_city(),
street: item.router_data.get_optional_shipping_line1(),
postcode: item.router_data.get_optional_shipping_zip(),
},
}),
})
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "order_details",
})?,
),
_ => None,
};
Ok(Self {
request_id: Uuid::new_v4().to_string(),
amount,
currency,
merchant_order_id: item.router_data.connector_request_reference_id.clone(),
referrer_data,
order,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AirwallexOrderResponse {
pub status: AirwallexPaymentStatus,
pub id: String,
pub payment_consent_id: Option<Secret<String>>,
pub next_action: Option<AirwallexPaymentsNextAction>,
}
impl TryFrom<CreateOrderResponseRouterData<AirwallexOrderResponse>>
for types::CreateOrderRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: CreateOrderResponseRouterData<AirwallexOrderResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::PaymentsCreateOrderResponse {
order_id: item.response.id.clone(),
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct AirwallexRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(StringMajorUnit, T)> for AirwallexRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, router_data): (StringMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data,
})
}
}
#[derive(Debug, Serialize)]
pub struct AirwallexPaymentsRequest {
// Unique ID to be sent for each transaction/operation request to the connector
request_id: String,
payment_method: AirwallexPaymentMethod,
payment_method_options: Option<AirwallexPaymentOptions>,
return_url: Option<String>,
device_data: Option<DeviceData>,
payment_consent: Option<PaymentConsentData>,
customer_id: Option<String>,
payment_consent_id: Option<String>,
triggered_by: Option<TriggeredBy>,
}
#[derive(Debug, Serialize)]
pub struct PaymentConsentData {
next_triggered_by: TriggeredBy,
merchant_trigger_reason: MerchantTriggeredReason,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MerchantTriggeredReason {
Unscheduled,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TriggeredBy {
Merchant,
Customer,
}
#[derive(Debug, Serialize, Eq, PartialEq, Default)]
pub struct AirwallexOrderData {
products: Vec<AirwallexProductData>,
shipping: Option<AirwallexShippingData>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct AirwallexProductData {
name: String,
quantity: u16,
unit_price: MinorUnit,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct AirwallexShippingData {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
phone_number: Option<Secret<String>>,
address: AirwallexPLShippingAddress,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct AirwallexPLShippingAddress {
country_code: Option<enums::CountryAlpha2>,
city: Option<String>,
street: Option<Secret<String>>,
postcode: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct DeviceData {
accept_header: String,
browser: Browser,
ip_address: Secret<String, IpAddress>,
language: String,
mobile: Option<Mobile>,
screen_color_depth: u8,
screen_height: u32,
screen_width: u32,
timezone: String,
}
#[derive(Debug, Serialize)]
pub struct Browser {
java_enabled: bool,
javascript_enabled: bool,
user_agent: String,
}
#[derive(Debug, Serialize)]
pub struct Mobile {
device_model: Option<String>,
os_type: Option<String>,
os_version: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum AirwallexPaymentMethod {
Card(AirwallexCard),
Wallets(AirwallexWalletData),
PayLater(AirwallexPayLaterData),
BankRedirect(AirwallexBankRedirectData),
BankTransfer(AirwallexBankTransferData),
PaymentMethodId(AirwallexPaymentMethodId),
}
#[derive(Debug, Serialize)]
pub struct AirwallexPaymentMethodId {
id: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct AirwallexCard {
card: AirwallexCardDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct AirwallexCardDetails {
expiry_month: Secret<String>,
expiry_year: Secret<String>,
number: cards::CardNumber,
cvc: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum AirwallexWalletData {
GooglePay(GooglePayData),
Paypal(PaypalData),
Skrill(SkrillData),
}
#[derive(Debug, Serialize)]
pub struct GooglePayData {
googlepay: GooglePayDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct PaypalData {
paypal: PaypalDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct SkrillData {
skrill: SkrillDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct GooglePayDetails {
encrypted_payment_token: Secret<String>,
payment_data_type: GpayPaymentDataType,
}
#[derive(Debug, Serialize)]
pub struct PaypalDetails {
shopper_name: Secret<String>,
country_code: enums::CountryAlpha2,
}
#[derive(Debug, Serialize)]
pub struct SkrillDetails {
shopper_name: Secret<String>,
shopper_email: Email,
country_code: enums::CountryAlpha2,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum AirwallexPayLaterData {
Klarna(Box<KlarnaData>),
Atome(AtomeData),
}
#[derive(Debug, Serialize)]
pub struct KlarnaData {
klarna: KlarnaDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct KlarnaDetails {
country_code: enums::CountryAlpha2,
billing: Option<Billing>,
}
#[derive(Debug, Serialize)]
pub struct Billing {
date_of_birth: Option<Secret<String>>,
email: Option<Email>,
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
phone_number: Option<Secret<String>>,
address: Option<AddressAirwallex>,
}
#[derive(Debug, Serialize)]
pub struct AddressAirwallex {
country_code: Option<enums::CountryAlpha2>,
city: Option<String>,
street: Option<Secret<String>>,
postcode: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct AtomeData {
atome: AtomeDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct AtomeDetails {
shopper_phone: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum AirwallexBankTransferData {
IndonesianBankTransfer(IndonesianBankTransferData),
}
#[derive(Debug, Serialize)]
pub struct IndonesianBankTransferData {
bank_transfer: IndonesianBankTransferDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct IndonesianBankTransferDetails {
shopper_name: Secret<String>,
shopper_email: Email,
bank_name: common_enums::BankNames,
country_code: enums::CountryAlpha2,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum AirwallexBankRedirectData {
Trustly(TrustlyData),
Blik(BlikData),
Ideal(IdealData),
}
#[derive(Debug, Serialize)]
pub struct TrustlyData {
trustly: TrustlyDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct TrustlyDetails {
shopper_name: Secret<String>,
country_code: enums::CountryAlpha2,
}
#[derive(Debug, Serialize)]
pub struct BlikData {
blik: BlikDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct BlikDetails {
shopper_name: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct IdealData {
ideal: IdealDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct IdealDetails {
bank_name: Option<common_enums::BankNames>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AirwallexPaymentType {
Card,
Googlepay,
Paypal,
Klarna,
Atome,
Trustly,
Blik,
Ideal,
Skrill,
BankTransfer,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum GpayPaymentDataType {
EncryptedPaymentToken,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AirwallexPaymentOptions {
Card(AirwallexCardPaymentOptions),
Klarna(AirwallexPayLaterPaymentOptions),
Atome(AirwallexPayLaterPaymentOptions),
}
#[derive(Debug, Serialize)]
pub struct AirwallexCardPaymentOptions {
auto_capture: bool,
}
#[derive(Debug, Serialize)]
pub struct AirwallexPayLaterPaymentOptions {
auto_capture: bool,
}
impl TryFrom<&AirwallexRouterData<&types::PaymentsAuthorizeRouterData>>
for AirwallexPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AirwallexRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let mut payment_method_options = None;
let request = &item.router_data.request;
let payment_method = match request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => {
payment_method_options =
Some(AirwallexPaymentOptions::Card(AirwallexCardPaymentOptions {
auto_capture: matches!(
request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None
),
}));
Ok(AirwallexPaymentMethod::Card(AirwallexCard {
card: AirwallexCardDetails {
number: ccard.card_number.clone(),
expiry_month: ccard.card_exp_month.clone(),
expiry_year: ccard.get_expiry_year_4_digit(),
cvc: ccard.card_cvc,
},
payment_method_type: AirwallexPaymentType::Card,
}))
}
PaymentMethodData::Wallet(ref wallet_data) => get_wallet_details(wallet_data, item),
PaymentMethodData::PayLater(ref paylater_data) => {
let paylater_options = AirwallexPayLaterPaymentOptions {
auto_capture: item.router_data.request.is_auto_capture()?,
};
payment_method_options = match paylater_data {
PayLaterData::KlarnaRedirect { .. } => {
Some(AirwallexPaymentOptions::Klarna(paylater_options))
}
PayLaterData::AtomeRedirect { .. } => {
Some(AirwallexPaymentOptions::Atome(paylater_options))
}
_ => None,
};
get_paylater_details(paylater_data, item)
}
PaymentMethodData::BankTransfer(ref banktransfer_data) => {
get_banktransfer_details(banktransfer_data, item)
}
PaymentMethodData::BankRedirect(ref bankredirect_data) => {
get_bankredirect_details(bankredirect_data, item)
}
PaymentMethodData::MandatePayment => {
let mandate_data = item
.router_data
.request
.get_connector_mandate_data()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_data",
})?;
let mandate_metadata: AirwallexMandateMetadata = mandate_data
.get_mandate_metadata()
.ok_or(errors::ConnectorError::MissingConnectorMandateMetadata)?
.clone()
.parse_value("AirwallexMandateMetadata")
.change_context(errors::ConnectorError::ParsingFailed)?;
Ok(AirwallexPaymentMethod::PaymentMethodId(
AirwallexPaymentMethodId {
id: mandate_metadata.id.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "mandate_metadata.id",
},
)?,
},
))
}
PaymentMethodData::BankDebit(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("airwallex"),
))
}
}?;
let payment_consent = if item
.router_data
.request
.is_customer_initiated_mandate_payment()
{
Some(PaymentConsentData {
next_triggered_by: TriggeredBy::Merchant,
merchant_trigger_reason: MerchantTriggeredReason::Unscheduled,
})
} else {
None
};
let return_url = match &request.payment_method_data {
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::PaypalRedirect(_paypal_details) => {
item.router_data.request.router_return_url.clone()
}
WalletData::Skrill(_) => item.router_data.request.router_return_url.clone(),
_ => request.complete_authorize_url.clone(),
},
PaymentMethodData::BankRedirect(_bankredirect_data) => {
item.router_data.request.router_return_url.clone()
}
PaymentMethodData::PayLater(_paylater_data) => {
item.router_data.request.router_return_url.clone()
}
_ => request.complete_authorize_url.clone(),
};
let is_mandate_payment = item.router_data.request.is_mit_payment()
|| item
.router_data
.request
.is_customer_initiated_mandate_payment();
let (device_data, customer_id) = if is_mandate_payment {
let customer_id = item.router_data.get_connector_customer_id()?;
(None, Some(customer_id))
} else {
let device_data = Some(get_device_data(item.router_data)?);
(device_data, None)
};
let (payment_consent_id, triggered_by) = if item.router_data.request.is_mit_payment() {
let mandate_id = item.router_data.request.connector_mandate_id().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
},
)?;
(Some(mandate_id), Some(TriggeredBy::Merchant))
} else {
(None, None)
};
Ok(Self {
request_id: Uuid::new_v4().to_string(),
payment_method,
payment_method_options,
return_url,
device_data,
payment_consent,
customer_id,
payment_consent_id,
triggered_by,
})
}
}
fn get_device_data(
item: &types::PaymentsAuthorizeRouterData,
) -> Result<DeviceData, error_stack::Report<errors::ConnectorError>> {
let info = item.request.get_browser_info()?;
let browser = Browser {
java_enabled: info.get_java_enabled()?,
javascript_enabled: info.get_java_script_enabled()?,
user_agent: info.get_user_agent()?,
};
let mobile = {
let device_model = info.get_device_model().ok();
let os_type = info.get_os_type().ok();
let os_version = info.get_os_version().ok();
if device_model.is_some() || os_type.is_some() || os_version.is_some() {
Some(Mobile {
device_model,
os_type,
os_version,
})
} else {
None
}
};
Ok(DeviceData {
accept_header: info.get_accept_header()?,
browser,
ip_address: info.get_ip_address()?,
mobile,
screen_color_depth: info.get_color_depth()?,
screen_height: info.get_screen_height()?,
screen_width: info.get_screen_width()?,
timezone: info.get_time_zone()?.to_string(),
language: info.get_language()?,
})
}
fn get_banktransfer_details(
banktransfer_data: &BankTransferData,
item: &AirwallexRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<AirwallexPaymentMethod, errors::ConnectorError> {
let _bank_transfer_details = match banktransfer_data {
BankTransferData::IndonesianBankTransfer { bank_name } => {
AirwallexPaymentMethod::BankTransfer(AirwallexBankTransferData::IndonesianBankTransfer(
IndonesianBankTransferData {
bank_transfer: IndonesianBankTransferDetails {
shopper_name: item.router_data.get_billing_full_name().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "shopper_name",
}
})?,
shopper_email: item.router_data.get_billing_email().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "shopper_email",
}
})?,
bank_name: bank_name.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "bank_name",
},
)?,
country_code: item.router_data.get_billing_country().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "country_code",
}
})?,
},
payment_method_type: AirwallexPaymentType::BankTransfer,
},
))
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("airwallex"),
))?,
};
let not_implemented = Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("airwallex"),
))?;
Ok(not_implemented)
}
fn get_paylater_details(
paylater_data: &PayLaterData,
item: &AirwallexRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<AirwallexPaymentMethod, errors::ConnectorError> {
let paylater_details = match paylater_data {
PayLaterData::KlarnaRedirect {} => {
AirwallexPaymentMethod::PayLater(AirwallexPayLaterData::Klarna(Box::new(KlarnaData {
klarna: KlarnaDetails {
country_code: item.router_data.get_billing_country().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "country_code",
}
})?,
billing: Some(Billing {
date_of_birth: None,
first_name: item.router_data.get_optional_billing_first_name(),
last_name: item.router_data.get_optional_billing_last_name(),
email: item.router_data.get_optional_billing_email(),
phone_number: item.router_data.get_optional_billing_phone_number(),
address: Some(AddressAirwallex {
country_code: item.router_data.get_optional_billing_country(),
city: item.router_data.get_optional_billing_city(),
street: item.router_data.get_optional_billing_line1(),
postcode: item.router_data.get_optional_billing_zip(),
}),
}),
},
payment_method_type: AirwallexPaymentType::Klarna,
})))
}
PayLaterData::AtomeRedirect {} => {
AirwallexPaymentMethod::PayLater(AirwallexPayLaterData::Atome(AtomeData {
atome: AtomeDetails {
shopper_phone: item
.router_data
.get_billing_phone()
.map_err(|_| errors::ConnectorError::MissingRequiredField {
field_name: "shopper_phone",
})?
.get_number_with_country_code()
.map_err(|_| errors::ConnectorError::MissingRequiredField {
field_name: "country_code",
})?,
},
payment_method_type: AirwallexPaymentType::Atome,
}))
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("airwallex"),
))?,
};
Ok(paylater_details)
}
fn get_bankredirect_details(
bankredirect_data: &BankRedirectData,
item: &AirwallexRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<AirwallexPaymentMethod, errors::ConnectorError> {
let bank_redirect_details = match bankredirect_data {
BankRedirectData::Trustly { .. } => {
AirwallexPaymentMethod::BankRedirect(AirwallexBankRedirectData::Trustly(TrustlyData {
trustly: TrustlyDetails {
shopper_name: item.router_data.get_billing_full_name().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "shopper_name",
}
})?,
country_code: item.router_data.get_billing_country().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "country_code",
}
})?,
},
payment_method_type: AirwallexPaymentType::Trustly,
}))
}
BankRedirectData::Blik { .. } => {
AirwallexPaymentMethod::BankRedirect(AirwallexBankRedirectData::Blik(BlikData {
blik: BlikDetails {
shopper_name: item.router_data.get_billing_full_name().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "shopper_name",
}
})?,
},
payment_method_type: AirwallexPaymentType::Blik,
}))
}
BankRedirectData::Ideal { .. } => {
AirwallexPaymentMethod::BankRedirect(AirwallexBankRedirectData::Ideal(IdealData {
ideal: IdealDetails { bank_name: None },
payment_method_type: AirwallexPaymentType::Ideal,
}))
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("airwallex"),
))?,
};
Ok(bank_redirect_details)
}
fn get_wallet_details(
wallet_data: &WalletData,
item: &AirwallexRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<AirwallexPaymentMethod, errors::ConnectorError> {
let wallet_details: AirwallexPaymentMethod = match wallet_data {
WalletData::GooglePay(gpay_details) => {
let token = gpay_details
.tokenization_data
.get_encrypted_google_pay_token()
.attach_printable("Failed to get gpay wallet token")
.map_err(|_| errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?;
AirwallexPaymentMethod::Wallets(AirwallexWalletData::GooglePay(GooglePayData {
googlepay: GooglePayDetails {
encrypted_payment_token: Secret::new(token.clone()),
payment_data_type: GpayPaymentDataType::EncryptedPaymentToken,
},
payment_method_type: AirwallexPaymentType::Googlepay,
}))
}
WalletData::PaypalRedirect(_paypal_details) => {
AirwallexPaymentMethod::Wallets(AirwallexWalletData::Paypal(PaypalData {
paypal: PaypalDetails {
shopper_name: item
.router_data
.request
.customer_name
.as_ref()
.cloned()
.or_else(|| item.router_data.get_billing_full_name().ok())
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "shopper_name",
})?,
country_code: item.router_data.get_billing_country().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "country_code",
}
})?,
},
payment_method_type: AirwallexPaymentType::Paypal,
}))
}
WalletData::Skrill(_skrill_details) => {
AirwallexPaymentMethod::Wallets(AirwallexWalletData::Skrill(SkrillData {
skrill: SkrillDetails {
shopper_name: item
.router_data
.request
.customer_name
.as_ref()
.cloned()
.or_else(|| item.router_data.get_billing_full_name().ok())
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "shopper_name",
})?,
shopper_email: item.router_data.get_billing_email().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "shopper_email",
}
})?,
country_code: item.router_data.get_billing_country().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "country_code",
}
})?,
},
payment_method_type: AirwallexPaymentType::Skrill,
}))
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::ApplePay(_)
| WalletData::BluecodeRedirect {}
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("airwallex"),
))?,
};
Ok(wallet_details)
}
#[derive(Deserialize, Debug, Serialize)]
pub struct AirwallexAuthUpdateResponse {
#[serde(with = "common_utils::custom_serde::iso8601")]
expires_at: PrimitiveDateTime,
token: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, AirwallexAuthUpdateResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AirwallexAuthUpdateResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
let expires = (item.response.expires_at - common_utils::date_time::now()).whole_seconds();
Ok(Self {
response: Ok(AccessToken {
token: item.response.token,
expires,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct AirwallexCompleteRequest {
request_id: String,
three_ds: AirwallexThreeDsData,
#[serde(rename = "type")]
three_ds_type: AirwallexThreeDsType,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct AirwallexThreeDsData {
acs_response: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub enum AirwallexThreeDsType {
#[default]
#[serde(rename = "3ds_continue")]
ThreeDSContinue,
}
impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for AirwallexCompleteRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> {
Ok(Self {
request_id: Uuid::new_v4().to_string(),
three_ds: AirwallexThreeDsData {
acs_response: item
.request
.redirect_response
.as_ref()
.map(|f| f.payload.to_owned())
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response.payload",
})?
.as_ref()
.map(|data| serde_json::to_string(data.peek()))
.transpose()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?
.map(Secret::new),
},
three_ds_type: AirwallexThreeDsType::ThreeDSContinue,
})
}
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct AirwallexPaymentsCaptureRequest {
// Unique ID to be sent for each transaction/operation request to the connector
request_id: String,
amount: Option<String>,
}
impl TryFrom<&types::PaymentsCaptureRouterData> for AirwallexPaymentsCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
Ok(Self {
request_id: Uuid::new_v4().to_string(),
amount: Some(utils::to_currency_base_unit(
item.request.amount_to_capture,
item.request.currency,
)?),
})
}
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct AirwallexPaymentsCancelRequest {
// Unique ID to be sent for each transaction/operation request to the connector
request_id: String,
cancellation_reason: Option<String>,
}
impl TryFrom<&types::PaymentsCancelRouterData> for AirwallexPaymentsCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Ok(Self {
request_id: Uuid::new_v4().to_string(),
cancellation_reason: item.request.cancellation_reason.clone(),
})
}
}
// PaymentsResponse
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AirwallexPaymentStatus {
Succeeded,
Failed,
#[default]
Pending,
RequiresPaymentMethod,
RequiresCustomerAction,
RequiresCapture,
Cancelled,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AirwallexNextAction {
Payments(AirwallexPaymentsNextAction),
Redirect(AirwallexRedirectNextAction),
}
fn get_payment_status(
status: &AirwallexPaymentStatus,
next_action: &Option<AirwallexNextAction>,
) -> enums::AttemptStatus {
match status.clone() {
AirwallexPaymentStatus::Succeeded => enums::AttemptStatus::Charged,
AirwallexPaymentStatus::Failed => enums::AttemptStatus::Failure,
AirwallexPaymentStatus::Pending => enums::AttemptStatus::Pending,
AirwallexPaymentStatus::RequiresPaymentMethod => enums::AttemptStatus::PaymentMethodAwaited,
AirwallexPaymentStatus::RequiresCustomerAction => next_action.as_ref().map_or(
enums::AttemptStatus::AuthenticationPending,
|next_action| match next_action {
AirwallexNextAction::Payments(payments_next_action) => {
match payments_next_action.stage {
AirwallexNextActionStage::WaitingDeviceDataCollection => {
enums::AttemptStatus::DeviceDataCollectionPending
}
AirwallexNextActionStage::WaitingUserInfoInput => {
enums::AttemptStatus::AuthenticationPending
}
}
}
AirwallexNextAction::Redirect(_) => enums::AttemptStatus::AuthenticationPending,
},
),
AirwallexPaymentStatus::RequiresCapture => enums::AttemptStatus::Authorized,
AirwallexPaymentStatus::Cancelled => enums::AttemptStatus::Voided,
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AirwallexNextActionStage {
WaitingDeviceDataCollection,
WaitingUserInfoInput,
}
#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct AirwallexRedirectFormData {
#[serde(rename = "JWT")]
jwt: Option<Secret<String>>,
#[serde(rename = "threeDSMethodData")]
three_ds_method_data: Option<Secret<String>>,
token: Option<Secret<String>>,
provider: Option<String>,
version: Option<String>,
}
#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct AirwallexPaymentsNextAction {
url: Url,
method: Method,
data: AirwallexRedirectFormData,
stage: AirwallexNextActionStage,
}
#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct AirwallexRedirectNextAction {
url: Url,
method: Method,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct AirwallexPaymentsResponse {
status: AirwallexPaymentStatus,
//Unique identifier for the PaymentIntent
id: String,
amount: Option<f32>,
//ID of the PaymentConsent related to this PaymentIntent
payment_consent_id: Option<Secret<String>>,
next_action: Option<AirwallexPaymentsNextAction>,
latest_payment_attempt: Option<AirwallexPaymentAttemptResponse>,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct AirwallexPaymentAttemptResponse {
payment_method: Option<AirwallexPaymentMethodResponse>,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct AirwallexPaymentMethodResponse {
id: Option<Secret<String>>,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct AirwallexMandateMetadata {
id: Option<Secret<String>>,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct AirwallexRedirectResponse {
status: AirwallexPaymentStatus,
id: String,
amount: Option<f32>,
payment_consent_id: Option<Secret<String>>,
next_action: Option<AirwallexRedirectNextAction>,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct AirwallexPaymentsSyncResponse {
status: AirwallexPaymentStatus,
//Unique identifier for the PaymentIntent
id: String,
amount: Option<f32>,
//ID of the PaymentConsent related to this PaymentIntent
payment_consent_id: Option<Secret<String>>,
next_action: Option<AirwallexPaymentsNextAction>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum AirwallexAuthorizeResponse {
AirwallexPaymentsResponse(AirwallexPaymentsResponse),
AirwallexRedirectResponse(AirwallexRedirectResponse),
}
fn get_redirection_form(response_url_data: AirwallexPaymentsNextAction) -> Option<RedirectForm> {
Some(RedirectForm::Form {
endpoint: response_url_data.url.to_string(),
method: response_url_data.method,
form_fields: std::collections::HashMap::from([
//Some form fields might be empty based on the authentication type by the connector
(
"JWT".to_string(),
response_url_data
.data
.jwt
.map(|jwt| jwt.expose())
.unwrap_or_default(),
),
(
"threeDSMethodData".to_string(),
response_url_data
.data
.three_ds_method_data
.map(|three_ds_method_data| three_ds_method_data.expose())
.unwrap_or_default(),
),
(
"token".to_string(),
response_url_data
.data
.token
.map(|token: Secret<String>| token.expose())
.unwrap_or_default(),
),
(
"provider".to_string(),
response_url_data.data.provider.unwrap_or_default(),
),
(
"version".to_string(),
response_url_data.data.version.unwrap_or_default(),
),
]),
})
}
impl<F, T>
ForeignTryFrom<ResponseRouterData<F, AirwallexAuthorizeResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
item: ResponseRouterData<F, AirwallexAuthorizeResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
data,
http_code,
} = item;
match response {
AirwallexAuthorizeResponse::AirwallexPaymentsResponse(res) => {
Self::try_from(ResponseRouterData::<
F,
AirwallexPaymentsResponse,
T,
PaymentsResponseData,
> {
response: res,
data,
http_code,
})
}
AirwallexAuthorizeResponse::AirwallexRedirectResponse(res) => {
Self::try_from(ResponseRouterData::<
F,
AirwallexRedirectResponse,
T,
PaymentsResponseData,
> {
response: res,
data,
http_code,
})
}
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AirwallexPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AirwallexPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, redirection_data) = item.response.next_action.clone().map_or(
// If no next action is there, map the status and set redirection form as None
(
get_payment_status(
&item.response.status,
&item
.response
.next_action
.clone()
.map(AirwallexNextAction::Payments)
.clone(),
),
None,
),
|response_url_data| {
// If the connector sends a customer action response that is already under
// process from our end it can cause an infinite loop to break this this check
// is added and fail the payment
if matches!(
(
response_url_data.stage.clone(),
item.data.status,
item.response.status.clone(),
),
// If the connector sends waiting for DDC and our status is already DDC Pending
// that means we initiated the call to collect the data and now we expect a different response
(
AirwallexNextActionStage::WaitingDeviceDataCollection,
enums::AttemptStatus::DeviceDataCollectionPending,
_
)
// If the connector sends waiting for Customer Action and our status is already Authenticaition Pending
// that means we initiated the call to authenticate and now we do not expect a requires_customer action
// it will start a loop
| (
_,
enums::AttemptStatus::AuthenticationPending,
AirwallexPaymentStatus::RequiresCustomerAction,
)
) {
// Fail the payment for above conditions
(enums::AttemptStatus::AuthenticationFailed, None)
} else {
(
//Build the redirect form and update the payment status
get_payment_status(
&item.response.status,
&item
.response
.next_action
.map(AirwallexNextAction::Payments)
.clone(),
),
get_redirection_form(response_url_data),
)
}
},
);
let mandate_reference = Box::new(Some(MandateReference {
connector_mandate_id: item
.response
.payment_consent_id
.clone()
.map(|id| id.expose()),
payment_method_id: None,
mandate_metadata: item
.response
.latest_payment_attempt
.and_then(|attempt| attempt.payment_method)
.map(|pm| Secret::new(serde_json::json!(AirwallexMandateMetadata { id: pm.id }))),
connector_mandate_request_reference_id: None,
}));
Ok(Self {
status,
reference_id: Some(item.response.id.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AirwallexRedirectResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AirwallexRedirectResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, redirection_data) = item.response.next_action.clone().map_or(
(
get_payment_status(
&item.response.status,
&item
.response
.next_action
.clone()
.map(AirwallexNextAction::Redirect)
.clone(),
),
None,
),
|response_url_data| {
let redirection_data =
Some(RedirectForm::from((response_url_data.url, Method::Get)));
(
get_payment_status(
&item.response.status,
&item
.response
.next_action
.map(AirwallexNextAction::Redirect)
.clone(),
),
redirection_data,
)
},
);
Ok(Self {
status,
reference_id: Some(item.response.id.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
impl
TryFrom<
ResponseRouterData<
PSync,
AirwallexPaymentsSyncResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
> for types::PaymentsSyncRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
PSync,
AirwallexPaymentsSyncResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = get_payment_status(
&item.response.status,
&item
.response
.next_action
.clone()
.map(AirwallexNextAction::Payments)
.clone(),
);
let redirection_data = if let Some(redirect_url_data) = item.response.next_action {
get_redirection_form(redirect_url_data)
} else {
None
};
Ok(Self {
status,
reference_id: Some(item.response.id.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct AirwallexRefundRequest {
// Unique ID to be sent for each transaction/operation request to the connector
request_id: String,
amount: Option<StringMajorUnit>,
reason: Option<String>,
//Identifier for the PaymentIntent for which Refund is requested
payment_intent_id: String,
}
impl<F> TryFrom<&AirwallexRouterData<&types::RefundsRouterData<F>>> for AirwallexRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AirwallexRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
request_id: Uuid::new_v4().to_string(),
amount: Some(item.amount.to_owned()),
reason: item.router_data.request.reason.clone(),
payment_intent_id: item.router_data.request.connector_transaction_id.clone(),
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Received,
Accepted,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Received | RefundStatus::Accepted => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
//A unique number that tags a credit or debit card transaction when it goes from the merchant's bank through to the cardholder's bank.
acquirer_reference_number: Option<String>,
amount: f32,
//Unique identifier for the Refund
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<ParsingError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<ParsingError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
..item.data
})
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AirwallexWebhookData {
pub source_id: Option<String>,
pub name: AirwallexWebhookEventType,
pub data: AirwallexObjectData,
}
#[derive(Debug, Deserialize, strum::Display, PartialEq)]
pub enum AirwallexWebhookEventType {
#[serde(rename = "payment_intent.created")]
PaymentIntentCreated,
#[serde(rename = "payment_intent.requires_payment_method")]
PaymentIntentRequiresPaymentMethod,
#[serde(rename = "payment_intent.cancelled")]
PaymentIntentCancelled,
#[serde(rename = "payment_intent.succeeded")]
PaymentIntentSucceeded,
#[serde(rename = "payment_intent.requires_capture")]
PaymentIntentRequiresCapture,
#[serde(rename = "payment_intent.requires_customer_action")]
PaymentIntentRequiresCustomerAction,
#[serde(rename = "payment_attempt.authorized")]
PaymentAttemptAuthorized,
#[serde(rename = "payment_attempt.authorization_failed")]
PaymentAttemptAuthorizationFailed,
#[serde(rename = "payment_attempt.capture_requested")]
PaymentAttemptCaptureRequested,
#[serde(rename = "payment_attempt.capture_failed")]
PaymentAttemptCaptureFailed,
#[serde(rename = "payment_attempt.authentication_redirected")]
PaymentAttemptAuthenticationRedirected,
#[serde(rename = "payment_attempt.authentication_failed")]
PaymentAttemptAuthenticationFailed,
#[serde(rename = "payment_attempt.failed_to_process")]
PaymentAttemptFailedToProcess,
#[serde(rename = "payment_attempt.cancelled")]
PaymentAttemptCancelled,
#[serde(rename = "payment_attempt.expired")]
PaymentAttemptExpired,
#[serde(rename = "payment_attempt.risk_declined")]
PaymentAttemptRiskDeclined,
#[serde(rename = "payment_attempt.settled")]
PaymentAttemptSettled,
#[serde(rename = "payment_attempt.paid")]
PaymentAttemptPaid,
#[serde(rename = "refund.received")]
RefundReceived,
#[serde(rename = "refund.accepted")]
RefundAccepted,
#[serde(rename = "refund.succeeded")]
RefundSucceeded,
#[serde(rename = "refund.failed")]
RefundFailed,
#[serde(rename = "dispute.rfi_responded_by_merchant")]
DisputeRfiRespondedByMerchant,
#[serde(rename = "dispute.dispute.pre_chargeback_accepted")]
DisputePreChargebackAccepted,
#[serde(rename = "dispute.accepted")]
DisputeAccepted,
#[serde(rename = "dispute.dispute_received_by_merchant")]
DisputeReceivedByMerchant,
#[serde(rename = "dispute.dispute_responded_by_merchant")]
DisputeRespondedByMerchant,
#[serde(rename = "dispute.won")]
DisputeWon,
#[serde(rename = "dispute.lost")]
DisputeLost,
#[serde(rename = "dispute.dispute_reversed")]
DisputeReversed,
#[serde(other)]
Unknown,
}
pub fn is_transaction_event(event_code: &AirwallexWebhookEventType) -> bool {
matches!(
event_code,
AirwallexWebhookEventType::PaymentAttemptFailedToProcess
| AirwallexWebhookEventType::PaymentAttemptAuthorized
)
}
pub fn is_refund_event(event_code: &AirwallexWebhookEventType) -> bool {
matches!(
event_code,
AirwallexWebhookEventType::RefundSucceeded | AirwallexWebhookEventType::RefundFailed
)
}
pub fn is_dispute_event(event_code: &AirwallexWebhookEventType) -> bool {
matches!(
event_code,
AirwallexWebhookEventType::DisputeAccepted
| AirwallexWebhookEventType::DisputePreChargebackAccepted
| AirwallexWebhookEventType::DisputeRespondedByMerchant
| AirwallexWebhookEventType::DisputeWon
| AirwallexWebhookEventType::DisputeLost
)
}
#[derive(Debug, Deserialize)]
pub struct AirwallexObjectData {
pub object: serde_json::Value,
}
#[derive(Debug, Deserialize)]
pub struct AirwallexDisputeObject {
pub payment_intent_id: String,
pub dispute_amount: MinorUnit,
pub dispute_currency: enums::Currency,
pub stage: AirwallexDisputeStage,
pub dispute_id: String,
pub dispute_reason_type: Option<String>,
pub dispute_original_reason_code: Option<String>,
pub status: String,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub created_at: Option<PrimitiveDateTime>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub updated_at: Option<PrimitiveDateTime>,
}
#[derive(Debug, Deserialize, strum::Display, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AirwallexDisputeStage {
Rfi,
Dispute,
Arbitration,
}
#[derive(Debug, Deserialize)]
pub struct AirwallexWebhookDataResource {
// Should this be a secret by default since it represents webhook payload
pub object: Secret<serde_json::Value>,
}
#[derive(Debug, Deserialize)]
pub struct AirwallexWebhookObjectResource {
pub data: AirwallexWebhookDataResource,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct AirwallexErrorResponse {
pub code: String,
pub message: String,
pub source: Option<String>,
pub provider_original_response_code: Option<String>,
}
pub fn map_error_code_to_message(code: String) -> Option<String> {
match code.as_str() {
"01" => Some("Contact card issuer".to_string()),
"03" => Some("Invalid Merchant".to_string()),
"04" => Some("Pick up card(no fraud)".to_string()),
"05" => Some("Do not honor".to_string()),
"06" => Some("Error".to_string()),
"07" => Some("Pick up card, special condition (fraud account)".to_string()),
"12" => Some("Invalid transaction".to_string()),
"13" => Some("Invalid amount".to_string()),
"14" => Some("Invalid card number".to_string()),
"15" => Some("Invalid issuer".to_string()),
"19" => Some("Re-enter transaction".to_string()),
"21" => Some("No action taken".to_string()),
"22" => Some("Operation error".to_string()),
"30" => Some("Format error".to_string()),
"34" => Some("Fraudulent card".to_string()),
"40" => Some("Transaction that is not supported by the Issuer".to_string()),
"41" => Some("Lost card".to_string()),
"43" => Some("Stolen card".to_string()),
"46" => Some("Closed account".to_string()),
"51" => Some("Insufficient funds/over credit limit / Not sufficient funds".to_string()),
"52" => Some("No checking account".to_string()),
"53" => Some("No savings account".to_string()),
"54" => Some("Expired card".to_string()),
"55" => Some("Incorrect PIN".to_string()),
"57" => Some("Transaction not permitted to issuer/cardholder".to_string()),
"58" => Some("Transaction not permitted to acquirer/terminal".to_string()),
"59" => Some("Suspected fraud".to_string()),
"61" => Some("Exceeds withdrawal limit".to_string()),
"62" => Some("Restricted card".to_string()),
"63" => Some("Security violation".to_string()),
"64" => Some("AML requirement failure / Original transaction amount mismatch".to_string()),
"65" => Some("Exceeds withdrawal count limit / Additional customer authentication required".to_string()),
"6P" => Some("Customer ID verification failed".to_string()),
"70" => Some("Contact Card Issuer".to_string()),
"72" => Some("Account not yet activated".to_string()),
"78" => Some("Invalid/nonexistent account specified (general)".to_string()),
"79" => Some("Life Cycle".to_string()),
"80" => Some("Credit issuer unavailable ".to_string()),
"82" => Some("Policy / Negative online CAM, dCVV, iCVV, CVV, or CAVV results or Offline PIN authentication interrupted".to_string()),
"83" => Some("Fraud / Security violation".to_string()),
"85" => Some("No reason to decline".to_string()),
"90" => Some("Decline due to daily cutoff being in progress".to_string()),
"91" => Some("Authorization Platform or issuer system inoperative / Issuer not available OR Issuer unavailable or switch inoperative".to_string()),
"92" => Some("Destination cannot be found for routing / Unable to route transaction".to_string()),
"93" => Some("Transaction cannot be completed; violation of law".to_string()),
"96" => Some("System malfunction".to_string()),
"1A" => Some("Authentication Required".to_string()),
"R0" => Some("Stop payment order".to_string()),
"R1" => Some("Revocation of authorisation order".to_string()),
"R3" => Some("Revocation of all authorisation orders".to_string()),
"N7" => Some("Decline for CVV2 failure".to_string()),
"5C" => Some("Transaction not supported / blocked by issuer".to_string()),
"9G" => Some("Blocked by cardholder / contact cardholder".to_string()),
"100" => Some("Deny / Do Not Honor".to_string()),
"101" => Some("Expired Card / Invalid Expiration Date".to_string()),
"109" => Some("Invalid merchant".to_string()),
"110" => Some("Invalid amount".to_string()),
"111" => Some("Invalid account / Invalid MICR (Travelers Cheque) / Invalid Card Number".to_string()),
"115" => Some("Requested function not supported".to_string()),
"116" => Some("Not sufficient funds".to_string()),
"119" => Some("Cardmember not enrolled / not permitted".to_string()),
"121" => Some("Limit exceeded".to_string()),
"122" => Some("Invalid card security code (a.k.a., CID, 4DBC, 4CSC) / Card Validity Period Exceeded".to_string()),
"130" => Some("Additional customer identification required".to_string()),
"181" => Some("Format error".to_string()),
"183" => Some("Invalid currency code".to_string()),
"187" => Some("Deny - new card issued".to_string()),
"189" => Some("Deny - Canceled or Closed Merchant/SE".to_string()),
"190" => Some("National ID mismatch".to_string()),
"200" => Some("Deny - Pick up card / Do Not Honor".to_string()),
"909" => Some("System Malfunction (Cryptographic error)".to_string()),
"912" => Some("Issuer not available".to_string()),
"978" => Some("Invalid Payment Times".to_string()),
"800.100.100" => Some("Transaction declined for unknown reason".to_string()),
"800.100.150" => Some("Transaction declined (refund on gambling tx not allowed)".to_string()),
"800.100.151" => Some("Transaction declined (invalid card)".to_string()),
"800.100.152" => Some("Transaction declined by authorization system".to_string()),
"800.100.153" => Some("Transaction declined (invalid CVV)".to_string()),
"800.100.154" => Some("Transaction declined (transaction marked as invalid)".to_string()),
"800.100.155" => Some("Transaction declined (amount exceeds credit)".to_string()),
"800.100.156" => Some("Transaction declined (format error)".to_string()),
"800.100.157" => Some("Transaction declined (wrong expiry date)".to_string()),
"800.100.158" => Some("Transaction declined (suspecting manipulation)".to_string()),
"800.100.159" => Some("Transaction declined (stolen card)".to_string()),
"800.100.160" => Some("Transaction declined (card blocked)".to_string()),
"800.100.161" => Some("Transaction declined (too many invalid tries)".to_string()),
"800.100.162" => Some("Transaction declined (limit exceeded)".to_string()),
"800.100.163" => Some("Transaction declined (maximum transaction frequency exceeded)".to_string()),
"800.100.164" => Some("Transaction declined (merchants limit exceeded)".to_string()),
"800.100.165" => Some("Transaction declined (card lost)".to_string()),
"800.100.168" => Some("Transaction declined (restricted card)".to_string()),
"800.100.169" => Some("Transaction declined (card type is not processed by the authorization center)".to_string()),
"800.100.170" => Some("Transaction declined (transaction not permitted)".to_string()),
"800.100.171" => Some("Transaction declined (pick up card)".to_string()),
"800.100.172" => Some("Transaction declined (account blocked)".to_string()),
"800.100.173" => Some("Transaction declined (invalid currency, not processed by authorization center)".to_string()),
"800.100.174" => Some("Insufficient Funds".to_string()),
"800.100.176" => Some("Transaction declined (account temporarily not available. Please try again later)".to_string()),
"800.100.179" => Some("Transaction declined (exceeds withdrawal count limit)".to_string()),
"800.100.190" => Some("Transaction declined (invalid configuration data)".to_string()),
"800.100.192" => Some("Transaction declined (invalid CVV, Amount has still been reserved on the customer's card and will be released in a few business days.)".to_string()),
"800.100.195" => Some("Transaction declined (UserAccount Number/ID unknown)".to_string()),
"800.100.200" => Some("Refer to Payer due to reason not specified".to_string()),
"800.100.201" => Some("Account or Bank Details Incorrect".to_string()),
"800.100.202" => Some("Account Closed".to_string()),
"800.100.203" => Some("Insufficient Funds".to_string()),
"800.100.204" => Some("Mandate Expired".to_string()),
"800.100.205" => Some("Mandate Discarded".to_string()),
"800.100.402" => Some("CC/bank account holder not valid".to_string()),
"800.100.403" => Some("Transaction declined (revocation of authorisation order)".to_string()),
"800.100.500" => Some("The card holder has advised his bank to stop this recurring payment".to_string()),
"800.100.501" => Some("Card holder has advised his bank to stop all recurring payments for this merchant".to_string()),
"081" => Some("Approved by Issuer".to_string()),
"102" => Some("Suspected Fraud".to_string()),
"103" => Some("Customer Authentication Required".to_string()),
"104" => Some("Restricted Card".to_string()),
"106" => Some("Allowable PIN Tries Exceeded".to_string()),
"117" => Some("Incorrect PIN".to_string()),
"118" => Some("Cycle Range Suspended".to_string()),
"120" => Some("Transaction Not Permitted To Originator".to_string()),
"124" => Some("Violation Of Law".to_string()),
"125" => Some("Card Not Effective".to_string()),
"129" => Some("Suspected Counterfeit Card".to_string()),
"163" => Some("Security Violations".to_string()),
"182" => Some("Decline Given By Issuer".to_string()),
"192" => Some("Restricted Merchant".to_string()),
"197" => Some("Card Account Verification Failed".to_string()),
"198" => Some("TVR or CVR Validation Failed".to_string()),
"201" => Some("Expired Card".to_string()),
"202" => Some("Suspected Fraud".to_string()),
"204" => Some("Restricted Card".to_string()),
"206" => Some("Allowable Pin Tries Exceeded".to_string()),
"207" => Some("Special Conditions".to_string()),
"208" => Some("Lost Card".to_string()),
"209" => Some("Stolen Card".to_string()),
"210" => Some("Suspected Counterfeit Card".to_string()),
_ => None,
}
}
impl TryFrom<AirwallexWebhookEventType> for api_models::webhooks::IncomingWebhookEvent {
type Error = errors::ConnectorError;
fn try_from(value: AirwallexWebhookEventType) -> Result<Self, Self::Error> {
Ok(match value {
AirwallexWebhookEventType::PaymentAttemptFailedToProcess => Self::PaymentIntentFailure,
AirwallexWebhookEventType::PaymentAttemptAuthorized => Self::PaymentIntentSuccess,
AirwallexWebhookEventType::RefundSucceeded => Self::RefundSuccess,
AirwallexWebhookEventType::RefundFailed => Self::RefundFailure,
AirwallexWebhookEventType::DisputeAccepted
| AirwallexWebhookEventType::DisputePreChargebackAccepted => Self::DisputeAccepted,
AirwallexWebhookEventType::DisputeRespondedByMerchant => Self::DisputeChallenged,
AirwallexWebhookEventType::DisputeWon | AirwallexWebhookEventType::DisputeReversed => {
Self::DisputeWon
}
AirwallexWebhookEventType::DisputeLost => Self::DisputeLost,
AirwallexWebhookEventType::Unknown
| AirwallexWebhookEventType::PaymentAttemptAuthenticationRedirected
| AirwallexWebhookEventType::PaymentIntentCreated
| AirwallexWebhookEventType::PaymentIntentRequiresPaymentMethod
| AirwallexWebhookEventType::PaymentIntentCancelled
| AirwallexWebhookEventType::PaymentIntentSucceeded
| AirwallexWebhookEventType::PaymentIntentRequiresCapture
| AirwallexWebhookEventType::PaymentIntentRequiresCustomerAction
| AirwallexWebhookEventType::PaymentAttemptAuthorizationFailed
| AirwallexWebhookEventType::PaymentAttemptCaptureRequested
| AirwallexWebhookEventType::PaymentAttemptCaptureFailed
| AirwallexWebhookEventType::PaymentAttemptAuthenticationFailed
| AirwallexWebhookEventType::PaymentAttemptCancelled
| AirwallexWebhookEventType::PaymentAttemptExpired
| AirwallexWebhookEventType::PaymentAttemptRiskDeclined
| AirwallexWebhookEventType::PaymentAttemptSettled
| AirwallexWebhookEventType::PaymentAttemptPaid
| AirwallexWebhookEventType::RefundReceived
| AirwallexWebhookEventType::RefundAccepted
| AirwallexWebhookEventType::DisputeRfiRespondedByMerchant
| AirwallexWebhookEventType::DisputeReceivedByMerchant => Self::EventNotSupported,
})
}
}
impl From<AirwallexDisputeStage> for api_models::enums::DisputeStage {
fn from(code: AirwallexDisputeStage) -> Self {
match code {
AirwallexDisputeStage::Rfi => Self::PreDispute,
AirwallexDisputeStage::Dispute => Self::Dispute,
AirwallexDisputeStage::Arbitration => Self::PreArbitration,
}
}
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct CustomerRequest {
pub request_id: String,
pub email: Option<Email>,
pub phone_number: Option<Secret<String>>,
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub merchant_customer_id: id_type::CustomerId,
}
impl TryFrom<&types::ConnectorCustomerRouterData> for CustomerRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> {
Ok(Self {
request_id: Uuid::new_v4().to_string(),
email: item.request.email.to_owned(),
phone_number: item.request.phone.to_owned(),
first_name: item.request.name.to_owned(),
last_name: item.request.name.to_owned(),
merchant_customer_id: item.customer_id.to_owned().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "customer_id",
},
)?,
})
}
}
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct AirwallexCustomerResponse {
pub id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, AirwallexCustomerResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AirwallexCustomerResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(item.response.id),
)),
..item.data
})
}
}
|
crates__hyperswitch_connectors__src__connectors__amazonpay.rs
|
pub mod transformers;
use std::sync::LazyLock;
use base64::{engine::general_purpose::STANDARD, Engine};
use chrono::Utc;
use common_enums::enums;
use common_utils::{
crypto::{RsaPssSha256, SignMessage},
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData as WalletDataPaymentMethod},
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask, Maskable, PeekInterface, Secret};
use sha2::{Digest, Sha256};
use transformers as amazonpay;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, PaymentsSyncRequestData},
};
const SIGNING_ALGO: &str = "AMZN-PAY-RSASSA-PSS-V2";
const HEADER_ACCEPT: &str = "accept";
const HEADER_CONTENT_TYPE: &str = "content-type";
const HEADER_DATE: &str = "x-amz-pay-date";
const HEADER_HOST: &str = "x-amz-pay-host";
const HEADER_IDEMPOTENCY_KEY: &str = "x-amz-pay-idempotency-key";
const HEADER_REGION: &str = "x-amz-pay-region";
const FINALIZE_SEGMENT: &str = "finalize";
const AMAZON_PAY_API_BASE_URL: &str = "https://pay-api.amazon.com";
const AMAZON_PAY_HOST: &str = "pay-api.amazon.com";
#[derive(Clone)]
pub struct Amazonpay {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Amazonpay {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
fn get_last_segment(canonical_uri: &str) -> String {
canonical_uri
.chars()
.rev()
.take_while(|&c| c != '/')
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect()
}
pub fn create_authorization_header(
&self,
auth: amazonpay::AmazonpayAuthType,
canonical_uri: &str,
http_method: &Method,
hashed_payload: &str,
header: &[(String, Maskable<String>)],
) -> String {
let amazonpay::AmazonpayAuthType {
public_key,
private_key,
} = auth;
let mut signed_headers =
format!("{HEADER_ACCEPT};{HEADER_CONTENT_TYPE};{HEADER_DATE};{HEADER_HOST};",);
if *http_method == Method::Post
&& Self::get_last_segment(canonical_uri) != *FINALIZE_SEGMENT.to_string()
{
signed_headers.push_str(HEADER_IDEMPOTENCY_KEY);
signed_headers.push(';');
}
signed_headers.push_str(HEADER_REGION);
format!(
"{} PublicKeyId={}, SignedHeaders={}, Signature={}",
SIGNING_ALGO,
public_key.expose().clone(),
signed_headers,
Self::create_signature(
&private_key,
*http_method,
canonical_uri,
&signed_headers,
hashed_payload,
header
)
.unwrap_or_else(|_| "Invalid signature".to_string())
)
}
fn create_signature(
private_key: &Secret<String>,
http_method: Method,
canonical_uri: &str,
signed_headers: &str,
hashed_payload: &str,
header: &[(String, Maskable<String>)],
) -> Result<String, String> {
let mut canonical_request = http_method.to_string() + "\n" + canonical_uri + "\n\n";
let mut lowercase_sorted_header_keys: Vec<String> =
header.iter().map(|(key, _)| key.to_lowercase()).collect();
lowercase_sorted_header_keys.sort();
for key in lowercase_sorted_header_keys {
if let Some((_, maskable_value)) = header.iter().find(|(k, _)| k.to_lowercase() == key)
{
let value: String = match maskable_value {
Maskable::Normal(v) => v.clone(),
Maskable::Masked(secret) => secret.clone().expose(),
};
canonical_request.push_str(&format!("{key}:{value}\n"));
}
}
canonical_request.push_str(&("\n".to_owned() + signed_headers + "\n" + hashed_payload));
let string_to_sign = format!(
"{}\n{}",
SIGNING_ALGO,
hex::encode(Sha256::digest(canonical_request.as_bytes()))
);
Self::sign(private_key, &string_to_sign)
.map_err(|e| format!("Failed to create signature: {e}"))
}
fn sign(
private_key_pem_str: &Secret<String>,
string_to_sign: &String,
) -> Result<String, String> {
let rsa_pss_sha256_signer = RsaPssSha256;
let signature_bytes = rsa_pss_sha256_signer
.sign_message(
private_key_pem_str.peek().as_bytes(),
string_to_sign.as_bytes(),
)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.map_err(|e| format!("Crypto operation failed: {e:?}"))?;
Ok(STANDARD.encode(signature_bytes))
}
}
impl api::Payment for Amazonpay {}
impl api::PaymentSession for Amazonpay {}
impl api::ConnectorAccessToken for Amazonpay {}
impl api::MandateSetup for Amazonpay {}
impl api::PaymentAuthorize for Amazonpay {}
impl api::PaymentSync for Amazonpay {}
impl api::PaymentCapture for Amazonpay {}
impl api::PaymentVoid for Amazonpay {}
impl api::Refund for Amazonpay {}
impl api::RefundExecute for Amazonpay {}
impl api::RefundSync for Amazonpay {}
impl api::PaymentToken for Amazonpay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Amazonpay
{
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Amazonpay
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let http_method = self.get_http_method();
let canonical_uri: String =
self.get_url(req, connectors)?
.replacen(AMAZON_PAY_API_BASE_URL, "", 1);
let mut header = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
headers::ACCEPT.to_string(),
"application/json".to_string().into(),
),
(
HEADER_DATE.to_string(),
Utc::now()
.format("%Y-%m-%dT%H:%M:%SZ")
.to_string()
.into_masked(),
),
(
HEADER_HOST.to_string(),
AMAZON_PAY_HOST.to_string().into_masked(),
),
(HEADER_REGION.to_string(), "na".to_string().into_masked()),
];
if http_method == Method::Post
&& Self::get_last_segment(&canonical_uri) != *FINALIZE_SEGMENT.to_string()
{
header.push((
HEADER_IDEMPOTENCY_KEY.to_string(),
req.connector_request_reference_id.clone().into_masked(),
));
}
let hashed_payload = if http_method == Method::Get {
hex::encode(Sha256::digest("".as_bytes()))
} else {
hex::encode(Sha256::digest(
self.get_request_body(req, connectors)?
.get_inner_value()
.expose()
.as_bytes(),
))
};
let authorization = self.create_authorization_header(
amazonpay::AmazonpayAuthType::try_from(&req.connector_auth_type)?,
&canonical_uri,
&http_method,
&hashed_payload,
&header,
);
header.push((
headers::AUTHORIZATION.to_string(),
authorization.clone().into_masked(),
));
Ok(header)
}
}
impl ConnectorCommon for Amazonpay {
fn id(&self) -> &'static str {
"amazonpay"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.amazonpay.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: amazonpay::AmazonpayErrorResponse = res
.response
.parse_struct("AmazonpayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.reason_code.clone(),
message: response.message.clone(),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
reason: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Amazonpay {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Amazonpay {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Amazonpay {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Amazonpay
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Amazonpay {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
match req.request.payment_method_data.clone() {
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletDataPaymentMethod::AmazonPay(ref req_wallet) => Ok(format!(
"{}/checkoutSessions/{}/finalize",
self.base_url(connectors),
req_wallet.checkout_session_id.clone()
)),
WalletDataPaymentMethod::AliPayQr(_)
| WalletDataPaymentMethod::AliPayRedirect(_)
| WalletDataPaymentMethod::AliPayHkRedirect(_)
| WalletDataPaymentMethod::AmazonPayRedirect(_)
| WalletDataPaymentMethod::MomoRedirect(_)
| WalletDataPaymentMethod::KakaoPayRedirect(_)
| WalletDataPaymentMethod::GoPayRedirect(_)
| WalletDataPaymentMethod::GcashRedirect(_)
| WalletDataPaymentMethod::ApplePay(_)
| WalletDataPaymentMethod::ApplePayRedirect(_)
| WalletDataPaymentMethod::ApplePayThirdPartySdk(_)
| WalletDataPaymentMethod::DanaRedirect {}
| WalletDataPaymentMethod::GooglePay(_)
| WalletDataPaymentMethod::GooglePayRedirect(_)
| WalletDataPaymentMethod::GooglePayThirdPartySdk(_)
| WalletDataPaymentMethod::MbWayRedirect(_)
| WalletDataPaymentMethod::MobilePayRedirect(_)
| WalletDataPaymentMethod::PaypalRedirect(_)
| WalletDataPaymentMethod::PaypalSdk(_)
| WalletDataPaymentMethod::Paze(_)
| WalletDataPaymentMethod::SamsungPay(_)
| WalletDataPaymentMethod::TwintRedirect {}
| WalletDataPaymentMethod::VippsRedirect {}
| WalletDataPaymentMethod::BluecodeRedirect {}
| WalletDataPaymentMethod::TouchNGoRedirect(_)
| WalletDataPaymentMethod::WeChatPayRedirect(_)
| WalletDataPaymentMethod::WeChatPayQr(_)
| WalletDataPaymentMethod::CashappQr(_)
| WalletDataPaymentMethod::SwishQr(_)
| WalletDataPaymentMethod::RevolutPay(_)
| WalletDataPaymentMethod::Paysera(_)
| WalletDataPaymentMethod::Skrill(_)
| WalletDataPaymentMethod::Mifinity(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("amazonpay"),
)
.into())
}
},
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = amazonpay::AmazonpayRouterData::from((amount, req));
let connector_req = amazonpay::AmazonpayFinalizeRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: amazonpay::AmazonpayFinalizeResponse = res
.response
.parse_struct("Amazonpay PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Amazonpay {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/charges/{}",
self.base_url(connectors),
req.request.get_connector_transaction_id()?
))
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: amazonpay::AmazonpayPaymentsResponse = res
.response
.parse_struct("Amazonpay PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Amazonpay {
fn build_request(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("Capture".to_string()).into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Amazonpay {
fn build_request(
&self,
_req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("Void".to_string()).into())
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Amazonpay {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/refunds", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = amazonpay::AmazonpayRouterData::from((refund_amount, req));
let connector_req = amazonpay::AmazonpayRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: amazonpay::RefundResponse = res
.response
.parse_struct("amazonpay RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Amazonpay {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/refunds/{}",
self.base_url(connectors),
req.request.connector_refund_id.clone().unwrap_or_default()
))
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: amazonpay::RefundResponse = res
.response
.parse_struct("amazonpay RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Amazonpay {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static AMAZONPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![enums::CaptureMethod::Automatic];
let mut amazonpay_supported_payment_methods = SupportedPaymentMethods::new();
amazonpay_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::AmazonPay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
amazonpay_supported_payment_methods
});
static AMAZONPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Amazon Pay",
description: "Amazon Pay is an Alternative Payment Method (APM) connector that allows merchants to accept payments using customers' stored Amazon account details, providing a seamless checkout experience.",
connector_type: enums::HyperswitchConnectorCategory::AlternativePaymentMethod,
integration_status: enums::ConnectorIntegrationStatus::Beta,
};
static AMAZONPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Amazonpay {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&AMAZONPAY_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&AMAZONPAY_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&AMAZONPAY_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__amazonpay__transformers.rs
|
use std::collections::HashMap;
use common_enums::{enums, CaptureMethod};
use common_utils::{errors::CustomResult, pii, types::StringMajorUnit};
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::{consts, errors};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{is_refund_failure, RouterData as _},
};
pub struct AmazonpayRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for AmazonpayRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmazonpayFinalizeRequest {
charge_amount: ChargeAmount,
shipping_address: AddressDetails,
payment_intent: PaymentIntent,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ChargeAmount {
amount: StringMajorUnit,
currency_code: common_enums::Currency,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AddressDetails {
name: Secret<String>,
address_line_1: Secret<String>,
address_line_2: Option<Secret<String>>,
address_line_3: Option<Secret<String>>,
city: String,
state_or_region: Secret<String>,
postal_code: Secret<String>,
country_code: Option<common_enums::CountryAlpha2>,
phone_number: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq)]
pub enum PaymentIntent {
AuthorizeWithCapture,
}
fn get_amazonpay_capture_type(
item: Option<CaptureMethod>,
) -> CustomResult<PaymentIntent, errors::ConnectorError> {
match item {
Some(CaptureMethod::Automatic) | None => Ok(PaymentIntent::AuthorizeWithCapture),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
impl TryFrom<&AmazonpayRouterData<&PaymentsAuthorizeRouterData>> for AmazonpayFinalizeRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AmazonpayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let charge_amount = ChargeAmount {
amount: item.amount.clone(),
currency_code: item.router_data.request.currency,
};
let shipping_address = AddressDetails {
name: item.router_data.get_required_shipping_full_name()?,
address_line_1: item.router_data.get_required_shipping_line1()?,
address_line_2: item.router_data.get_optional_shipping_line2(),
address_line_3: item.router_data.get_optional_shipping_line3(),
city: item.router_data.get_required_shipping_city()?,
state_or_region: item.router_data.get_required_shipping_state()?,
postal_code: item.router_data.get_required_shipping_zip()?,
country_code: item.router_data.get_optional_shipping_country(),
phone_number: item.router_data.get_required_shipping_phone_number()?,
};
let payment_intent = get_amazonpay_capture_type(item.router_data.request.capture_method)?;
Ok(Self {
charge_amount,
shipping_address,
payment_intent,
})
}
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmazonpayFinalizeResponse {
checkout_session_id: String,
web_checkout_details: WebCheckoutDetails,
product_type: Option<String>,
payment_details: Option<PaymentDetails>,
cart_details: CartDetails,
charge_permission_type: String,
order_type: Option<String>,
recurring_metadata: Option<RecurringMetadata>,
payment_method_on_file_metadata: Option<String>,
processor_specifications: Option<String>,
merchant_details: Option<String>,
merchant_metadata: Option<MerchantMetadata>,
supplementary_data: Option<String>,
buyer: Option<BuyerDetails>,
billing_address: Option<AddressDetails>,
payment_preferences: Option<String>,
status_details: FinalizeStatusDetails,
shipping_address: Option<AddressDetails>,
platform_id: Option<String>,
charge_permission_id: String,
charge_id: String,
constraints: Option<String>,
creation_timestamp: String,
expiration_timestamp: Option<String>,
store_id: Option<String>,
provider_metadata: Option<ProviderMetadata>,
release_environment: Option<ReleaseEnvironment>,
checkout_button_text: Option<String>,
delivery_specifications: Option<DeliverySpecifications>,
tokens: Option<String>,
disbursement_details: Option<String>,
channel_type: Option<String>,
payment_processing_meta_data: PaymentProcessingMetaData,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct WebCheckoutDetails {
checkout_review_return_url: Option<String>,
checkout_result_return_url: Option<String>,
amazon_pay_redirect_url: Option<String>,
authorize_result_return_url: Option<String>,
sign_in_return_url: Option<String>,
sign_in_cancel_url: Option<String>,
checkout_error_url: Option<String>,
sign_in_error_url: Option<String>,
amazon_pay_decline_url: Option<String>,
checkout_cancel_url: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentDetails {
payment_intent: String,
can_handle_pending_authorization: bool,
charge_amount: ChargeAmount,
total_order_amount: ChargeAmount,
presentment_currency: String,
soft_descriptor: String,
allow_overcharge: bool,
extend_expiration: bool,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CartDetails {
line_items: Vec<String>,
delivery_options: Vec<DeliveryOptions>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DeliveryOptions {
id: String,
price: ChargeAmount,
shipping_method: ShippingMethod,
is_default: bool,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ShippingMethod {
shipping_method_name: String,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RecurringMetadata {
frequency: Frequency,
amount: ChargeAmount,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Frequency {
unit: String,
value: String,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct BuyerDetails {
buyer_id: Secret<String>,
name: Secret<String>,
email: pii::Email,
phone_number: Secret<String>,
prime_membership_types: Vec<String>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FinalizeStatusDetails {
state: FinalizeState,
reason_code: Option<String>,
reason_description: Option<String>,
last_updated_timestamp: String,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub enum FinalizeState {
Open,
Completed,
Canceled,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DeliverySpecifications {
special_restrictions: Vec<String>,
address_restrictions: AddressRestrictions,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AddressRestrictions {
r#type: String,
restrictions: HashMap<String, Restriction>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Restriction {
pub states_or_regions: Vec<Secret<String>>,
pub zip_codes: Vec<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentProcessingMetaData {
payment_processing_model: String,
}
impl From<FinalizeState> for common_enums::AttemptStatus {
fn from(item: FinalizeState) -> Self {
match item {
FinalizeState::Open => Self::Pending,
FinalizeState::Completed => Self::Charged,
FinalizeState::Canceled => Self::Failure,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AmazonpayFinalizeResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AmazonpayFinalizeResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.status_details.state {
FinalizeState::Canceled => {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "Checkout was not successfully completed".to_owned(),
reason: Some("Checkout was not successfully completed due to buyer abandoment, payment decline, or because checkout wasn't confirmed with Finalize Checkout Session.".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.checkout_session_id.clone()),
connector_response_reference_id: Some(item.response.checkout_session_id),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
FinalizeState::Open
| FinalizeState::Completed => {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status_details.state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.charge_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.checkout_session_id),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
}
}
pub struct AmazonpayAuthType {
pub(super) public_key: Secret<String>,
pub(super) private_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AmazonpayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
public_key: api_key.to_owned(),
private_key: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub enum AmazonpayPaymentStatus {
AuthorizationInitiated,
Authorized,
Canceled,
Captured,
CaptureInitiated,
Declined,
}
impl From<AmazonpayPaymentStatus> for common_enums::AttemptStatus {
fn from(item: AmazonpayPaymentStatus) -> Self {
match item {
AmazonpayPaymentStatus::AuthorizationInitiated => Self::Pending,
AmazonpayPaymentStatus::Authorized => Self::Authorized,
AmazonpayPaymentStatus::Canceled => Self::Voided,
AmazonpayPaymentStatus::Captured => Self::Charged,
AmazonpayPaymentStatus::CaptureInitiated => Self::CaptureInitiated,
AmazonpayPaymentStatus::Declined => Self::CaptureFailed,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmazonpayPaymentsResponse {
charge_id: String,
charge_amount: ChargeAmount,
charge_permission_id: String,
capture_amount: Option<ChargeAmount>,
refunded_amount: Option<ChargeAmount>,
soft_descriptor: Option<String>,
provider_metadata: Option<ProviderMetadata>,
converted_amount: Option<ChargeAmount>,
conversion_rate: Option<f64>,
channel: Option<String>,
charge_initiator: Option<String>,
status_details: PaymentsStatusDetails,
creation_timestamp: String,
expiration_timestamp: String,
release_environment: Option<ReleaseEnvironment>,
merchant_metadata: Option<MerchantMetadata>,
platform_id: Option<String>,
web_checkout_details: Option<WebCheckoutDetails>,
disbursement_details: Option<String>,
payment_method: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ProviderMetadata {
provider_reference_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentsStatusDetails {
state: AmazonpayPaymentStatus,
reason_code: Option<String>,
reason_description: Option<String>,
last_updated_timestamp: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ReleaseEnvironment {
Sandbox,
Live,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MerchantMetadata {
merchant_reference_id: Option<String>,
merchant_store_name: Option<String>,
note_to_buyer: Option<String>,
custom_information: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, AmazonpayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AmazonpayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.status_details.state {
AmazonpayPaymentStatus::Canceled => {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "Charge was canceled by Amazon or by the merchant".to_owned(),
reason: Some("Charge was canceled due to expiration, Amazon, buyer, merchant action, or charge permission cancellation.".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.charge_id),
connector_response_reference_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
AmazonpayPaymentStatus::Declined => {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "The authorization or capture was declined".to_owned(),
reason: Some("Charge was declined due to soft/hard decline, Amazon rejection, or internal processing failure.".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.charge_id),
connector_response_reference_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
_ => {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status_details.state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.charge_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AmazonpayRefundRequest {
pub refund_amount: ChargeAmount,
pub charge_id: String,
}
impl<F> TryFrom<&AmazonpayRouterData<&RefundsRouterData<F>>> for AmazonpayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AmazonpayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let refund_amount = ChargeAmount {
amount: item.amount.clone(),
currency_code: item.router_data.request.currency,
};
let charge_id = item.router_data.request.connector_transaction_id.clone();
Ok(Self {
refund_amount,
charge_id,
})
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum RefundStatus {
RefundInitiated,
Refunded,
Declined,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::RefundInitiated => Self::Pending,
RefundStatus::Refunded => Self::Success,
RefundStatus::Declined => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
refund_id: String,
charge_id: String,
creation_timestamp: String,
refund_amount: ChargeAmount,
status_details: RefundStatusDetails,
soft_descriptor: String,
release_environment: ReleaseEnvironment,
disbursement_details: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundStatusDetails {
state: RefundStatus,
reason_code: Option<String>,
reason_description: Option<String>,
last_updated_timestamp: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
match item.response.status_details.state {
RefundStatus::Declined => {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "Amazon has declined the refund.".to_owned(),
reason: Some("Amazon has declined the refund because maximum amount has been refunded or there was some other issue.".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.charge_id),
connector_response_reference_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
_ => {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund_id,
refund_status: enums::RefundStatus::from(item.response.status_details.state),
}),
..item.data
})
}
}
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status_details.state);
let response = if is_refund_failure(refund_status) {
Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "Amazon has declined the refund.".to_owned(),
reason: Some("Amazon has declined the refund because maximum amount has been refunded or there was some other issue.".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.refund_id.clone()),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.refund_id.to_string(),
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmazonpayErrorResponse {
pub reason_code: String,
pub message: String,
}
|
crates__hyperswitch_connectors__src__connectors__archipel.rs
|
use std::sync::LazyLock;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::{ByteSliceExt, ValueExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
IncrementalAuthorization,
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData,
PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsIncrementalAuthorizationRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts::NO_ERROR_MESSAGE,
errors,
events::connector_api_logs::ConnectorEvent,
types::Response,
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},
};
use masking::Maskable;
use router_env::{error, info};
use transformers::{
self as archipel, ArchipelCardAuthorizationRequest, ArchipelIncrementalAuthorizationRequest,
ArchipelPaymentsCancelRequest, ArchipelRefundRequest, ArchipelWalletAuthorizationRequest,
};
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{is_mandate_supported, PaymentMethodDataType, PaymentsAuthorizeRequestData},
};
pub mod transformers;
#[derive(Clone)]
pub struct Archipel {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Archipel {
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::PaymentAuthorize for Archipel {}
impl api::PaymentSync for Archipel {}
impl api::PaymentVoid for Archipel {}
impl api::PaymentCapture for Archipel {}
impl api::MandateSetup for Archipel {}
impl api::ConnectorAccessToken for Archipel {}
impl api::PaymentToken for Archipel {}
impl api::PaymentSession for Archipel {}
impl api::Refund for Archipel {}
impl api::RefundExecute for Archipel {}
impl api::RefundSync for Archipel {}
impl api::Payment for Archipel {}
impl api::PaymentIncrementalAuthorization for Archipel {}
fn build_env_specific_endpoint(
base_url: &str,
connector_metadata: &Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<String, errors::ConnectorError> {
let archipel_connector_metadata_object =
transformers::ArchipelConfigData::try_from(connector_metadata)?;
let endpoint_prefix = archipel_connector_metadata_object.platform_url;
Ok(base_url.replace("{{merchant_endpoint_prefix}}", &endpoint_prefix))
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Archipel
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Archipel {
fn id(&self) -> &'static str {
"archipel"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(vec![])
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.archipel.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let archipel_error: CustomResult<
archipel::ArchipelErrorMessage,
common_utils::errors::ParsingError,
> = res.response.parse_struct("ArchipelErrorMessage");
match archipel_error {
Ok(err) => {
event_builder.map(|i| i.set_error_response_body(&err));
info!(connector_response=?err);
Ok(ErrorResponse {
status_code: res.status_code,
code: err.code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
message: err
.description
.clone()
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: err.description,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Err(error) => {
event_builder.map(|event| {
event.set_error(serde_json::json!({
"error": res.response.escape_ascii().to_string(),
"status_code": res.status_code
}))
});
error!(deserialization_error=?error);
crate::utils::handle_json_response_deserialization_failure(res, "archipel")
}
}
}
}
impl ConnectorValidation for Archipel {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]);
is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Archipel {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let capture_method = req
.request
.capture_method
.ok_or(errors::ConnectorError::CaptureMethodNotSupported)?;
let base_url =
build_env_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::SequentialAutomatic => {
Ok(format!("{}{}", base_url, "/pay"))
}
enums::CaptureMethod::Manual => Ok(format!("{}{}", base_url, "/authorize")),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => {
Err(report!(errors::ConnectorError::CaptureMethodNotSupported))
}
}
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let config_data: archipel::ArchipelConfigData = (&req.connector_meta_data).try_into()?;
let amount = crate::utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let router_data: archipel::ArchipelRouterData<_> =
(amount, config_data.tenant_id, req).into();
if req.request.is_wallet() {
let request: ArchipelWalletAuthorizationRequest = router_data.try_into()?;
Ok(RequestContent::Json(Box::new(request)))
} else {
let request: ArchipelCardAuthorizationRequest = router_data.try_into()?;
Ok(RequestContent::Json(Box::new(request)))
}
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let auth_details = archipel::ArchipelAuthType::try_from(&req.connector_auth_type)?;
let url = &self.get_url(req, connectors)?;
let headers = self.get_headers(req, connectors)?;
let body = self.get_request_body(req, connectors)?;
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(url)
.attach_default_headers()
.headers(headers)
.add_ca_certificate_pem(auth_details.ca_certificate)
.set_body(body)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: archipel::ArchipelPaymentsResponse = res
.response
.parse_struct("ArchipelPaymentsResponse for Authorize flow")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl
ConnectorIntegration<
IncrementalAuthorization,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
> for Archipel
{
fn get_headers(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url =
build_env_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}{}{}",
base_url, "/incrementAuthorization/", connector_payment_id
))
}
fn get_request_body(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let config_data: archipel::ArchipelConfigData = (&req.connector_meta_data).try_into()?;
let router_data: archipel::ArchipelRouterData<_> = (
MinorUnit::new(req.request.additional_amount),
config_data.tenant_id,
req,
)
.into();
let request: ArchipelIncrementalAuthorizationRequest = router_data.into();
Ok(RequestContent::Json(Box::new(request)))
}
fn build_request(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let auth_details = archipel::ArchipelAuthType::try_from(&req.connector_auth_type)?;
let url = &self.get_url(req, connectors)?;
let headers = self.get_headers(req, connectors)?;
let body = self.get_request_body(req, connectors)?;
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(url)
.attach_default_headers()
.headers(headers)
.add_ca_certificate_pem(auth_details.ca_certificate)
.set_body(body)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsIncrementalAuthorizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsIncrementalAuthorizationRouterData, errors::ConnectorError> {
let response: archipel::ArchipelPaymentsResponse = res
.response
.parse_struct("ArchipelPaymentsResponse for IncrementalAuthorization flow")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Archipel {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url =
build_env_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
let metadata: archipel::ArchipelTransactionMetadata = req
.request
.connector_meta
.clone()
.and_then(|value| value.parse_value("ArchipelTransactionMetadata").ok())
.ok_or_else(|| errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}{}{}",
base_url, "/transactions/", metadata.transaction_id
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let auth_details = archipel::ArchipelAuthType::try_from(&req.connector_auth_type)?;
let url = &self.get_url(req, connectors)?;
let headers = self.get_headers(req, connectors)?;
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(url)
.attach_default_headers()
.headers(headers)
.add_ca_certificate_pem(auth_details.ca_certificate)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: archipel::ArchipelPaymentsResponse = res
.response
.parse_struct("ArchipelPaymentsResponse for PSync flow")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Archipel {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url =
build_env_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
Ok(format!(
"{}{}{}",
base_url, "/capture/", req.request.connector_transaction_id
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let config_data: archipel::ArchipelConfigData = (&req.connector_meta_data).try_into()?;
let amount_to_capture = crate::utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let router_data: archipel::ArchipelRouterData<_> =
(amount_to_capture, config_data.tenant_id, req).into();
let request: archipel::ArchipelCaptureRequest = router_data.into();
Ok(RequestContent::Json(Box::new(request)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let auth_details = archipel::ArchipelAuthType::try_from(&req.connector_auth_type)?;
let url = &self.get_url(req, connectors)?;
let headers = self.get_headers(req, connectors)?;
let body = self.get_request_body(req, connectors)?;
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(url)
.attach_default_headers()
.headers(headers)
.add_ca_certificate_pem(auth_details.ca_certificate)
.set_body(body)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: archipel::ArchipelPaymentsResponse = res
.response
.parse_struct("ArchipelPaymentsResponse for Capture flow")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Archipel
{
fn get_headers(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url =
build_env_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
Ok(format!("{}{}", base_url, "/verify"))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let config_data: archipel::ArchipelConfigData = (&req.connector_meta_data).try_into()?;
let router_data: archipel::ArchipelRouterData<_> =
(MinorUnit::zero(), config_data.tenant_id, req).into();
let request: ArchipelCardAuthorizationRequest = router_data.try_into()?;
Ok(RequestContent::Json(Box::new(request)))
}
fn build_request(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let auth_details = archipel::ArchipelAuthType::try_from(&req.connector_auth_type)?;
let url = &self.get_url(req, connectors)?;
let headers = self.get_headers(req, connectors)?;
let body = self.get_request_body(req, connectors)?;
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(url)
.attach_default_headers()
.headers(headers)
.add_ca_certificate_pem(auth_details.ca_certificate)
.set_body(body)
.build(),
))
}
fn handle_response(
&self,
data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
let response: archipel::ArchipelPaymentsResponse = res
.response
.parse_struct("ArchipelPaymentsResponse for SetupMandate flow")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Archipel {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url =
build_env_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
Ok(format!(
"{}{}{}",
base_url, "/refund/", req.request.connector_transaction_id
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let config_data: archipel::ArchipelConfigData = (&req.connector_meta_data).try_into()?;
let refund_amount = crate::utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let router_data: archipel::ArchipelRouterData<_> =
(refund_amount, config_data.tenant_id, req).into();
let request: ArchipelRefundRequest = router_data.into();
Ok(RequestContent::Json(Box::new(request)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let auth_details = archipel::ArchipelAuthType::try_from(&req.connector_auth_type)?;
let url = &self.get_url(req, connectors)?;
let headers = self.get_headers(req, connectors)?;
let body = self.get_request_body(req, connectors)?;
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(url)
.attach_default_headers()
.headers(headers)
.add_ca_certificate_pem(auth_details.ca_certificate)
.set_body(body)
.build(),
))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: archipel::ArchipelRefundResponse = res
.response
.parse_struct("ArchipelRefundResponse for Execute flow")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Archipel {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let config_data: archipel::ArchipelConfigData = (&req.connector_meta_data).try_into()?;
let platform_url = &config_data.platform_url;
let metadata: archipel::ArchipelTransactionMetadata = req
.request
.connector_metadata
.clone()
.and_then(|value| value.parse_value("ArchipelTransactionMetadata").ok())
.ok_or_else(|| errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{platform_url}{}{}",
"Transaction/v1/transactions/", metadata.transaction_id
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let auth_details = archipel::ArchipelAuthType::try_from(&req.connector_auth_type)?;
let url = &self.get_url(req, connectors)?;
let headers = self.get_headers(req, connectors)?;
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(url)
.attach_default_headers()
.headers(headers)
.add_ca_certificate_pem(auth_details.ca_certificate)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: archipel::ArchipelRefundResponse = res
.response
.parse_struct("ArchipelRefundResponse for RSync flow")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Archipel
{
// Not Implemented (R)
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Archipel {
// Not Implemented (R)
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Archipel {
// Not Implemented (R)
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Archipel {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url =
build_env_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
Ok(format!(
"{}{}{}",
base_url, "/cancel/", req.request.connector_transaction_id
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let config_data: archipel::ArchipelConfigData = (&req.connector_meta_data).try_into()?;
let router_data: archipel::ArchipelRouterData<_> = (
req.request
.minor_amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "Amount",
})?,
config_data.tenant_id,
req,
)
.into();
let request: ArchipelPaymentsCancelRequest = router_data.into();
Ok(RequestContent::Json(Box::new(request)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let auth_details = archipel::ArchipelAuthType::try_from(&req.connector_auth_type)?;
let url = &self.get_url(req, connectors)?;
let headers = self.get_headers(req, connectors)?;
let body = self.get_request_body(req, connectors)?;
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(url)
.attach_default_headers()
.headers(headers)
.add_ca_certificate_pem(auth_details.ca_certificate)
.set_body(body)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: archipel::ArchipelPaymentsResponse = res
.response
.parse_struct("ArchipelPaymentsResponse for Void flow")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Archipel {
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static ARCHIPEL_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::CartesBancaires,
];
let mut archipel_supported_payment_methods = SupportedPaymentMethods::new();
archipel_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
archipel_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network,
}
}),
),
},
);
archipel_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
archipel_supported_payment_methods
});
static ARCHIPEL_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Archipel",
description: "Full-service processor offering secure payment solutions and innovative banking technologies for businesses of all sizes.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static ARCHIPEL_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Archipel {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&ARCHIPEL_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*ARCHIPEL_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&ARCHIPEL_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__authipay__transformers.rs
|
use common_enums::enums;
use common_utils::types::FloatMajorUnit;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, CardData},
};
// Type definition for router data with amount
pub struct AuthipayRouterData<T> {
pub amount: FloatMajorUnit, // Amount in major units (e.g., dollars instead of cents)
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for AuthipayRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
// Basic request/response structs used across multiple operations
#[derive(Default, Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
total: FloatMajorUnit,
currency: String,
#[serde(skip_serializing_if = "Option::is_none")]
components: Option<AmountComponents>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmountComponents {
subtotal: FloatMajorUnit,
}
#[derive(Default, Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ExpiryDate {
month: Secret<String>,
year: Secret<String>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Card {
number: cards::CardNumber,
security_code: Secret<String>,
expiry_date: ExpiryDate,
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethod {
payment_card: Card,
}
#[derive(Default, Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SplitShipment {
total_count: i32,
final_shipment: bool,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayPaymentsRequest {
request_type: &'static str,
transaction_amount: Amount,
payment_method: PaymentMethod,
// split_shipment: Option<SplitShipment>,
// incremental_flag: Option<bool>,
}
impl TryFrom<&AuthipayRouterData<&PaymentsAuthorizeRouterData>> for AuthipayPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthipayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
// Check if 3DS is being requested - Authipay doesn't support 3DS
if matches!(
item.router_data.auth_type,
enums::AuthenticationType::ThreeDs
) {
return Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authipay"),
)
.into());
}
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let expiry_date = ExpiryDate {
month: req_card.card_exp_month.clone(),
year: req_card.get_card_expiry_year_2_digit()?,
};
let card = Card {
number: req_card.card_number.clone(),
security_code: req_card.card_cvc.clone(),
expiry_date,
};
let payment_method = PaymentMethod { payment_card: card };
let transaction_amount = Amount {
total: item.amount,
currency: item.router_data.request.currency.to_string(),
components: None,
};
// Determine request type based on capture method
let request_type = match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual) => "PaymentCardPreAuthTransaction",
Some(enums::CaptureMethod::Automatic) => "PaymentCardSaleTransaction",
Some(enums::CaptureMethod::SequentialAutomatic) => "PaymentCardSaleTransaction",
Some(enums::CaptureMethod::ManualMultiple)
| Some(enums::CaptureMethod::Scheduled) => {
return Err(errors::ConnectorError::NotSupported {
message: "Capture method not supported by Authipay".to_string(),
connector: "Authipay",
}
.into());
}
None => "PaymentCardSaleTransaction", // Default when not specified
};
let request = Self {
request_type,
transaction_amount,
payment_method,
};
Ok(request)
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authipay"),
)
.into()),
}
}
}
//TODO: Fill the struct with respective fields
// Auth Struct
pub struct AuthipayAuthType {
pub(super) api_key: Secret<String>,
pub(super) api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AuthipayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
api_secret: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// Transaction Status enum (like Fiserv's FiservPaymentStatus)
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum AuthipayTransactionStatus {
Authorized,
Captured,
Voided,
Declined,
Failed,
#[default]
Processing,
}
impl From<AuthipayTransactionStatus> for enums::AttemptStatus {
fn from(item: AuthipayTransactionStatus) -> Self {
match item {
AuthipayTransactionStatus::Captured => Self::Charged,
AuthipayTransactionStatus::Declined | AuthipayTransactionStatus::Failed => {
Self::Failure
}
AuthipayTransactionStatus::Processing => Self::Pending,
AuthipayTransactionStatus::Authorized => Self::Authorized,
AuthipayTransactionStatus::Voided => Self::Voided,
}
}
}
// Transaction Processing Details (like Fiserv's TransactionProcessingDetails)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayTransactionProcessingDetails {
pub order_id: String,
pub transaction_id: String,
}
// Gateway Response (like Fiserv's GatewayResponse)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayGatewayResponse {
pub transaction_state: AuthipayTransactionStatus,
pub transaction_processing_details: AuthipayTransactionProcessingDetails,
}
// Payment Receipt (like Fiserv's PaymentReceipt)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayPaymentReceipt {
pub approved_amount: Amount,
pub processor_response_details: Option<Processor>,
}
// Main Response (like Fiserv's FiservPaymentsResponse) - but flat for JSON deserialization
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayPaymentsResponse {
#[serde(rename = "type")]
response_type: Option<String>,
client_request_id: String,
api_trace_id: String,
ipg_transaction_id: String,
order_id: String,
transaction_type: String,
payment_token: Option<PaymentToken>,
transaction_origin: Option<String>,
payment_method_details: Option<PaymentMethodDetails>,
country: Option<String>,
terminal_id: Option<String>,
merchant_id: Option<String>,
transaction_time: i64,
approved_amount: Amount,
transaction_amount: Amount,
// For payment transactions (SALE)
transaction_status: Option<String>,
// For refund transactions (RETURN)
transaction_result: Option<String>,
transaction_state: Option<String>,
approval_code: String,
scheme_transaction_id: Option<String>,
processor: Processor,
}
impl AuthipayPaymentsResponse {
/// Get gateway response (like Fiserv's gateway_response)
pub fn gateway_response(&self) -> AuthipayGatewayResponse {
AuthipayGatewayResponse {
transaction_state: self.get_transaction_status(),
transaction_processing_details: AuthipayTransactionProcessingDetails {
order_id: self.order_id.clone(),
transaction_id: self.ipg_transaction_id.clone(),
},
}
}
/// Get payment receipt (like Fiserv's payment_receipt)
pub fn payment_receipt(&self) -> AuthipayPaymentReceipt {
AuthipayPaymentReceipt {
approved_amount: self.approved_amount.clone(),
processor_response_details: Some(self.processor.clone()),
}
}
/// Determine the transaction status based on transaction type and various status fields (like Fiserv)
fn get_transaction_status(&self) -> AuthipayTransactionStatus {
match self.transaction_type.as_str() {
"RETURN" => {
// Refund transaction - use transaction_result
match self.transaction_result.as_deref() {
Some("APPROVED") => AuthipayTransactionStatus::Captured,
Some("DECLINED") | Some("FAILED") => AuthipayTransactionStatus::Failed,
_ => AuthipayTransactionStatus::Processing,
}
}
"VOID" => {
// Void transaction - use transaction_result, fallback to transaction_state
match self.transaction_result.as_deref() {
Some("APPROVED") => AuthipayTransactionStatus::Voided,
Some("DECLINED") | Some("FAILED") => AuthipayTransactionStatus::Failed,
Some("PENDING") | Some("PROCESSING") => AuthipayTransactionStatus::Processing,
_ => {
// Fallback to transaction_state for void operations
match self.transaction_state.as_deref() {
Some("VOIDED") => AuthipayTransactionStatus::Voided,
Some("FAILED") | Some("DECLINED") => AuthipayTransactionStatus::Failed,
_ => AuthipayTransactionStatus::Voided, // Default assumption for void requests
}
}
}
}
_ => {
// Payment transaction - prioritize transaction_state over transaction_status
match self.transaction_state.as_deref() {
Some("AUTHORIZED") => AuthipayTransactionStatus::Authorized,
Some("CAPTURED") => AuthipayTransactionStatus::Captured,
Some("VOIDED") => AuthipayTransactionStatus::Voided,
Some("DECLINED") | Some("FAILED") => AuthipayTransactionStatus::Failed,
_ => {
// Fallback to transaction_status with transaction_type context
match (
self.transaction_type.as_str(),
self.transaction_status.as_deref(),
) {
// For PREAUTH transactions, "APPROVED" means authorized and awaiting capture
("PREAUTH", Some("APPROVED")) => AuthipayTransactionStatus::Authorized,
// For POSTAUTH transactions, "APPROVED" means successfully captured
("POSTAUTH", Some("APPROVED")) => AuthipayTransactionStatus::Captured,
// For SALE transactions, "APPROVED" means completed payment
("SALE", Some("APPROVED")) => AuthipayTransactionStatus::Captured,
// For VOID transactions, "APPROVED" means successfully voided
("VOID", Some("APPROVED")) => AuthipayTransactionStatus::Voided,
// Generic status mappings for other cases
(_, Some("APPROVED")) => AuthipayTransactionStatus::Captured,
(_, Some("AUTHORIZED")) => AuthipayTransactionStatus::Authorized,
(_, Some("DECLINED") | Some("FAILED")) => {
AuthipayTransactionStatus::Failed
}
_ => AuthipayTransactionStatus::Processing,
}
}
}
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentToken {
reusable: Option<bool>,
decline_duplicates: Option<bool>,
brand: Option<String>,
#[serde(rename = "type")]
token_type: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethodDetails {
payment_card: Option<PaymentCardDetails>,
payment_method_type: Option<String>,
payment_method_brand: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentCardDetails {
expiry_date: ExpiryDate,
bin: String,
last4: String,
brand: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Processor {
reference_number: Option<String>,
authorization_code: Option<String>,
response_code: String,
response_message: String,
avs_response: Option<AvsResponse>,
security_code_response: Option<String>,
tax_refund_data: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AvsResponse {
street_match: Option<String>,
postal_code_match: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, AuthipayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AuthipayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
// Get gateway response (like Fiserv pattern)
let gateway_resp = item.response.gateway_response();
// Store order_id in connector_metadata for void operations (like Fiserv)
let mut metadata = std::collections::HashMap::new();
metadata.insert(
"order_id".to_string(),
serde_json::Value::String(gateway_resp.transaction_processing_details.order_id.clone()),
);
let connector_metadata = Some(serde_json::Value::Object(serde_json::Map::from_iter(
metadata,
)));
Ok(Self {
status: enums::AttemptStatus::from(gateway_resp.transaction_state.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
gateway_resp
.transaction_processing_details
.transaction_id
.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(
gateway_resp.transaction_processing_details.order_id.clone(),
),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
// Type definition for CaptureRequest
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayCaptureRequest {
request_type: &'static str,
transaction_amount: Amount,
}
impl TryFrom<&AuthipayRouterData<&PaymentsCaptureRouterData>> for AuthipayCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthipayRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
request_type: "PostAuthTransaction",
transaction_amount: Amount {
total: item.amount,
currency: item.router_data.request.currency.to_string(),
components: None,
},
})
}
}
// Type definition for VoidRequest
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayVoidRequest {
request_type: &'static str,
}
impl TryFrom<&AuthipayRouterData<&PaymentsCancelRouterData>> for AuthipayVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
_item: &AuthipayRouterData<&PaymentsCancelRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
request_type: "VoidTransaction",
})
}
}
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayRefundRequest {
request_type: &'static str,
transaction_amount: Amount,
}
impl<F> TryFrom<&AuthipayRouterData<&RefundsRouterData<F>>> for AuthipayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AuthipayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
request_type: "ReturnTransaction",
transaction_amount: Amount {
total: item.amount.to_owned(),
currency: item.router_data.request.currency.to_string(),
components: None,
},
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
// Reusing the payments response structure for refunds
// because Authipay uses the same endpoint and response format
pub type RefundResponse = AuthipayPaymentsResponse;
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = if item.response.transaction_type == "RETURN" {
match item.response.transaction_result.as_deref() {
Some("APPROVED") => RefundStatus::Succeeded,
Some("DECLINED") | Some("FAILED") => RefundStatus::Failed,
_ => RefundStatus::Processing,
}
} else {
RefundStatus::Processing
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.ipg_transaction_id.to_string(),
refund_status: enums::RefundStatus::from(refund_status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = if item.response.transaction_type == "RETURN" {
match item.response.transaction_result.as_deref() {
Some("APPROVED") => RefundStatus::Succeeded,
Some("DECLINED") | Some("FAILED") => RefundStatus::Failed,
_ => RefundStatus::Processing,
}
} else {
RefundStatus::Processing
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.ipg_transaction_id.to_string(),
refund_status: enums::RefundStatus::from(refund_status),
}),
..item.data
})
}
}
// Error Response structs
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorDetailItem {
pub field: String,
pub message: String,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorDetails {
pub code: Option<String>,
pub message: String,
pub details: Option<Vec<ErrorDetailItem>>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayErrorResponse {
pub client_request_id: Option<String>,
pub api_trace_id: Option<String>,
pub response_type: Option<String>,
#[serde(rename = "type")]
pub response_object_type: Option<String>,
pub error: ErrorDetails,
pub decline_reason_code: Option<String>,
}
impl From<&AuthipayErrorResponse> for ErrorResponse {
fn from(item: &AuthipayErrorResponse) -> Self {
Self {
status_code: 500, // Default to Internal Server Error, will be overridden by actual HTTP status
code: item.error.code.clone().unwrap_or_default(),
message: item.error.message.clone(),
reason: None,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}
}
}
|
crates__hyperswitch_connectors__src__connectors__authorizedotnet.rs
|
pub mod transformers;
use std::sync::LazyLock;
use common_enums::{enums, PaymentAction};
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
CompleteAuthorize, CreateConnectorCustomer,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, ConnectorCustomerData,
PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData,
PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData,
SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData,
RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation, MandateSetup,
},
configs::Connectors,
consts, errors,
events::connector_api_logs::ConnectorEvent,
types::{
ConnectorCustomerType, PaymentsAuthorizeType, PaymentsCaptureType,
PaymentsCompleteAuthorizeType, PaymentsSyncType, PaymentsVoidType, RefundExecuteType,
RefundSyncType, Response, SetupMandateType,
},
webhooks,
};
use masking::Maskable;
use transformers as authorizedotnet;
use crate::{
connectors::authorizedotnet::transformers::AuthorizedotnetRouterData,
constants::headers,
types::ResponseRouterData,
utils::{
self as connector_utils, convert_amount, ForeignTryFrom, PaymentMethodDataType,
PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
},
};
#[derive(Clone)]
pub struct Authorizedotnet {
amount_convertor: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Authorizedotnet {
pub fn new() -> &'static Self {
&Self {
amount_convertor: &FloatMajorUnitForConnector,
}
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Authorizedotnet
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
_req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)])
}
}
impl ConnectorCommon for Authorizedotnet {
fn id(&self) -> &'static str {
"authorizedotnet"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.authorizedotnet.base_url.as_ref()
}
}
impl ConnectorValidation for Authorizedotnet {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::GooglePay,
PaymentMethodDataType::ApplePay,
]);
connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl api::Payment for Authorizedotnet {}
impl api::PaymentAuthorize for Authorizedotnet {}
impl api::PaymentSync for Authorizedotnet {}
impl api::PaymentVoid for Authorizedotnet {}
impl api::PaymentCapture for Authorizedotnet {}
impl api::PaymentSession for Authorizedotnet {}
impl api::ConnectorAccessToken for Authorizedotnet {}
impl api::PaymentToken for Authorizedotnet {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Authorizedotnet
{
// Not Implemented (R)
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Authorizedotnet {
// Not Implemented (R)
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>
for Authorizedotnet
{
// Not Implemented (R)
}
impl api::ConnectorCustomer for Authorizedotnet {}
impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>
for Authorizedotnet
{
fn get_headers(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &ConnectorCustomerRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = authorizedotnet::CustomerRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&ConnectorCustomerType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(ConnectorCustomerType::get_headers(self, req, connectors)?)
.set_body(ConnectorCustomerType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &ConnectorCustomerRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<ConnectorCustomerRouterData, errors::ConnectorError>
where
PaymentsResponseData: Clone,
{
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
let encoding = encoding_rs::UTF_8;
let intermediate_response = encoding.decode_with_bom_removal(res.response.chunk());
let intermediate_response =
bytes::Bytes::copy_from_slice(intermediate_response.0.as_bytes());
let response: authorizedotnet::AuthorizedotnetCustomerResponse = intermediate_response
.parse_struct("AuthorizedotnetCustomerResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
let encoding = encoding_rs::UTF_8;
let intermediate_response = encoding.decode_with_bom_removal(res.response.chunk());
let intermediate_response =
bytes::Bytes::copy_from_slice(intermediate_response.0.as_bytes());
let response: authorizedotnet::AuthorizedotnetErrorResponse = intermediate_response
.parse_struct("AuthorizedotnetErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response
.error
.code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: response
.error
.message
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: response.error.message,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl MandateSetup for Authorizedotnet {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Authorizedotnet
{
fn get_headers(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
// This connector does not require an auth header, the authentication details are sent in the request body
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = authorizedotnet::CreateCustomerPaymentProfileRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(SetupMandateType::get_headers(self, req, connectors)?)
.set_body(SetupMandateType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
let encoding = encoding_rs::UTF_8;
let intermediate_response = encoding.decode_with_bom_removal(res.response.chunk());
let intermediate_response =
bytes::Bytes::copy_from_slice(intermediate_response.0.as_bytes());
let response: authorizedotnet::AuthorizedotnetSetupMandateResponse = intermediate_response
.parse_struct("AuthorizedotnetPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
get_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Authorizedotnet {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = AuthorizedotnetRouterData::try_from((amount, req))?;
let connector_req =
authorizedotnet::CancelOrCaptureTransactionRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
.set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
let encoding = encoding_rs::UTF_8;
let intermediate_response = encoding.decode_with_bom_removal(res.response.chunk());
let intermediate_response =
bytes::Bytes::copy_from_slice(intermediate_response.0.as_bytes());
let response: authorizedotnet::AuthorizedotnetPaymentsResponse = intermediate_response
.parse_struct("AuthorizedotnetPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::foreign_try_from((
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
true,
))
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
get_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Authorizedotnet {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
// This connector does not require an auth header, the authentication details are sent in the request body
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = authorizedotnet::AuthorizedotnetCreateSyncRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.set_body(PaymentsSyncType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
let encoding = encoding_rs::UTF_8;
let intermediate_response = encoding.decode_with_bom_removal(res.response.chunk());
let intermediate_response =
bytes::Bytes::copy_from_slice(intermediate_response.0.as_bytes());
let response: authorizedotnet::AuthorizedotnetSyncResponse = intermediate_response
.parse_struct("AuthorizedotnetSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
get_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for Authorizedotnet
{
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
// This connector does not require an auth header, the authentication details are sent in the request body
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = AuthorizedotnetRouterData::try_from((amount, req))?;
let connector_req =
authorizedotnet::CreateTransactionRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
let encoding = encoding_rs::UTF_8;
let intermediate_response = encoding.decode_with_bom_removal(res.response.chunk());
let intermediate_response =
bytes::Bytes::copy_from_slice(intermediate_response.0.as_bytes());
let response: authorizedotnet::AuthorizedotnetPaymentsResponse = intermediate_response
.parse_struct("AuthorizedotnetPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::foreign_try_from((
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
data.request.is_auto_capture()?,
))
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
get_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Authorizedotnet {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = authorizedotnet::CancelOrCaptureTransactionRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
let encoding = encoding_rs::UTF_8;
let intermediate_response = encoding.decode_with_bom_removal(res.response.chunk());
let intermediate_response =
bytes::Bytes::copy_from_slice(intermediate_response.0.as_bytes());
let response: authorizedotnet::AuthorizedotnetVoidResponse = intermediate_response
.parse_struct("AuthorizedotnetPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
get_error_response(res, event_builder)
}
}
impl api::Refund for Authorizedotnet {}
impl api::RefundExecute for Authorizedotnet {}
impl api::RefundSync for Authorizedotnet {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Authorizedotnet {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
// This connector does not require an auth header, the authentication details are sent in the request body
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = AuthorizedotnetRouterData::try_from((amount, req))?;
let connector_req = authorizedotnet::CreateRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
let encoding = encoding_rs::UTF_8;
let intermediate_response = encoding.decode_with_bom_removal(res.response.chunk());
let intermediate_response =
bytes::Bytes::copy_from_slice(intermediate_response.0.as_bytes());
let response: authorizedotnet::AuthorizedotnetRefundResponse = intermediate_response
.parse_struct("AuthorizedotnetRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
get_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Authorizedotnet {
fn get_headers(
&self,
req: &RefundsRouterData<RSync>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
// This connector does not require an auth header, the authentication details are sent in the request body
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<RSync>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &RefundsRouterData<RSync>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = AuthorizedotnetRouterData::try_from((amount, req))?;
let connector_req =
authorizedotnet::AuthorizedotnetCreateSyncRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<RSync>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundSyncType::get_headers(self, req, connectors)?)
.set_body(RefundSyncType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<RSync>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<RSync>, errors::ConnectorError> {
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
let encoding = encoding_rs::UTF_8;
let intermediate_response = encoding.decode_with_bom_removal(res.response.chunk());
let intermediate_response =
bytes::Bytes::copy_from_slice(intermediate_response.0.as_bytes());
let response: authorizedotnet::AuthorizedotnetRSyncResponse = intermediate_response
.parse_struct("AuthorizedotnetRSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
get_error_response(res, event_builder)
}
}
impl api::PaymentsCompleteAuthorize for Authorizedotnet {}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Authorizedotnet
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = AuthorizedotnetRouterData::try_from((amount, req))?;
let connector_req =
authorizedotnet::PaypalConfirmRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
let encoding = encoding_rs::UTF_8;
let intermediate_response = encoding.decode_with_bom_removal(res.response.chunk());
let intermediate_response =
bytes::Bytes::copy_from_slice(intermediate_response.0.as_bytes());
let response: authorizedotnet::AuthorizedotnetPaymentsResponse = intermediate_response
.parse_struct("AuthorizedotnetPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::foreign_try_from((
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
data.request.is_auto_capture()?,
))
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
get_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Authorizedotnet {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha512))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let security_header = request
.headers
.get("X-ANET-Signature")
.map(|header_value| {
header_value
.to_str()
.map(String::from)
.map_err(|_| errors::ConnectorError::WebhookSignatureNotFound)
})
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)??
.to_lowercase();
let (_, sig_value) = security_header
.split_once('=')
.ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)?;
hex::decode(sig_value).change_context(errors::ConnectorError::WebhookSignatureNotFound)
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(request.body.to_vec())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let details: authorizedotnet::AuthorizedotnetWebhookObjectId = request
.body
.parse_struct("AuthorizedotnetWebhookObjectId")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
match details.event_type {
authorizedotnet::AuthorizedotnetWebhookEvent::RefundCreated => {
Ok(api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(
authorizedotnet::get_trans_id(&details)?,
),
))
}
authorizedotnet::AuthorizedotnetWebhookEvent::AuthorizationCreated
| authorizedotnet::AuthorizedotnetWebhookEvent::PriorAuthCapture
| authorizedotnet::AuthorizedotnetWebhookEvent::AuthCapCreated
| authorizedotnet::AuthorizedotnetWebhookEvent::CaptureCreated
| authorizedotnet::AuthorizedotnetWebhookEvent::VoidCreated => {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
authorizedotnet::get_trans_id(&details)?,
),
))
}
}
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let details: authorizedotnet::AuthorizedotnetWebhookEventType = request
.body
.parse_struct("AuthorizedotnetWebhookEventType")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(api_models::webhooks::IncomingWebhookEvent::from(
details.event_type,
))
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let payload: authorizedotnet::AuthorizedotnetWebhookObjectId = request
.body
.parse_struct("AuthorizedotnetWebhookObjectId")
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(
authorizedotnet::AuthorizedotnetSyncResponse::try_from(payload)?,
))
}
}
#[inline]
fn get_error_response(
Response {
response,
status_code,
..
}: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: authorizedotnet::AuthorizedotnetPaymentsResponse = response
.parse_struct("AuthorizedotnetPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
match response.transaction_response {
Some(authorizedotnet::TransactionResponse::AuthorizedotnetTransactionResponse(
payment_response,
)) => Ok(payment_response
.errors
.and_then(|errors| {
errors.into_iter().next().map(|error| ErrorResponse {
code: error.error_code,
message: error.error_text.to_owned(),
reason: Some(error.error_text),
status_code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
})
.unwrap_or_else(|| ErrorResponse {
code: consts::NO_ERROR_CODE.to_string(), // authorizedotnet sends 200 in case of bad request so this are hard coded to NO_ERROR_CODE and NO_ERROR_MESSAGE
message: consts::NO_ERROR_MESSAGE.to_string(),
reason: None,
status_code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})),
Some(authorizedotnet::TransactionResponse::AuthorizedotnetTransactionResponseError(_))
| None => {
let message = &response
.messages
.message
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?
.text;
Ok(ErrorResponse {
code: consts::NO_ERROR_CODE.to_string(),
message: message.to_string(),
reason: Some(message.to_string()),
status_code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
}
impl api::ConnectorRedirectResponse for Authorizedotnet {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
action: PaymentAction,
) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> {
match action {
PaymentAction::PSync
| PaymentAction::CompleteAuthorize
| PaymentAction::PaymentAuthenticateCompleteAuthorize => {
Ok(enums::CallConnectorAction::Trigger)
}
}
}
}
static AUTHORIZEDOTNET_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
];
let mut authorizedotnet_supported_payment_methods = SupportedPaymentMethods::new();
authorizedotnet_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
authorizedotnet_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
authorizedotnet_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Paypal,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
authorizedotnet_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
authorizedotnet_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
authorizedotnet_supported_payment_methods
});
static AUTHORIZEDOTNET_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Authorize.net",
description:
" Authorize.net supports payment processing by helping small businesses accept credit card and eCheck payments online, in person on the go.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static AUTHORIZEDOTNET_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] =
[enums::EventClass::Payments, enums::EventClass::Refunds];
impl ConnectorSpecifications for Authorizedotnet {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&AUTHORIZEDOTNET_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*AUTHORIZEDOTNET_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&AUTHORIZEDOTNET_SUPPORTED_WEBHOOK_FLOWS)
}
fn should_call_connector_customer(
&self,
_payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> bool {
true
}
}
|
crates__hyperswitch_connectors__src__connectors__authorizedotnet__transformers.rs
|
use std::collections::BTreeMap;
use api_models::{payments::AdditionalPaymentData, webhooks::IncomingWebhookEvent};
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::{Encode, OptionExt, ValueExt},
id_type::CustomerId,
pii::Email,
request::Method,
types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{Card, PaymentMethodData, WalletData},
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ErrorResponse, RouterData,
},
router_flow_types::RSync,
router_request_types::ResponseId,
router_response_types::{
ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, RedirectForm,
RefundsResponseData,
},
types::{
ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData,
RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret, StrongSecret};
use rand::distributions::{Alphanumeric, DistString};
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, CardData, ForeignTryFrom, PaymentsAuthorizeRequestData, PaymentsSyncRequestData,
RefundsRequestData, RouterData as OtherRouterData, WalletData as OtherWalletData,
},
};
const MAX_ID_LENGTH: usize = 20;
const ADDRESS_MAX_LENGTH: usize = 60;
fn get_random_string() -> String {
Alphanumeric.sample_string(&mut rand::thread_rng(), MAX_ID_LENGTH)
}
#[derive(Debug, Serialize)]
pub enum TransactionType {
#[serde(rename = "authCaptureTransaction")]
Payment,
#[serde(rename = "authOnlyTransaction")]
Authorization,
#[serde(rename = "priorAuthCaptureTransaction")]
Capture,
#[serde(rename = "refundTransaction")]
Refund,
#[serde(rename = "voidTransaction")]
Void,
#[serde(rename = "authOnlyContinueTransaction")]
ContinueAuthorization,
#[serde(rename = "authCaptureContinueTransaction")]
ContinueCapture,
}
#[derive(Debug, Serialize)]
pub struct AuthorizedotnetRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(FloatMajorUnit, T)> for AuthorizedotnetRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (FloatMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetAuthType {
name: Secret<String>,
transaction_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AuthorizedotnetAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
name: api_key.to_owned(),
transaction_key: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct CreditCardDetails {
card_number: StrongSecret<String, cards::CardNumberStrategy>,
expiration_date: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
card_code: Option<Secret<String>>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
enum PaymentDetails {
CreditCard(CreditCardDetails),
OpaqueData(WalletDetails),
PayPal(PayPalDetails),
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PayPalDetails {
pub success_url: Option<String>,
pub cancel_url: Option<String>,
}
#[derive(Serialize, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletDetails {
pub data_descriptor: WalletMethod,
pub data_value: Secret<String>,
}
#[derive(Serialize, Debug, Deserialize)]
pub enum WalletMethod {
#[serde(rename = "COMMON.GOOGLE.INAPP.PAYMENT")]
Googlepay,
#[serde(rename = "COMMON.APPLE.INAPP.PAYMENT")]
Applepay,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct TransactionRequest {
transaction_type: TransactionType,
amount: FloatMajorUnit,
currency_code: common_enums::Currency,
#[serde(skip_serializing_if = "Option::is_none")]
payment: Option<PaymentDetails>,
#[serde(skip_serializing_if = "Option::is_none")]
profile: Option<ProfileDetails>,
order: Order,
#[serde(skip_serializing_if = "Option::is_none")]
customer: Option<CustomerDetails>,
#[serde(skip_serializing_if = "Option::is_none")]
bill_to: Option<BillTo>,
#[serde(skip_serializing_if = "Option::is_none")]
user_fields: Option<UserFields>,
#[serde(skip_serializing_if = "Option::is_none")]
processing_options: Option<ProcessingOptions>,
#[serde(skip_serializing_if = "Option::is_none")]
subsequent_auth_information: Option<SubsequentAuthInformation>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UserFields {
user_field: Vec<UserField>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UserField {
name: String,
value: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
enum ProfileDetails {
CreateProfileDetails(CreateProfileDetails),
CustomerProfileDetails(CustomerProfileDetails),
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct CreateProfileDetails {
create_profile: bool,
#[serde(skip_serializing_if = "Option::is_none")]
customer_profile_id: Option<Secret<String>>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct CustomerProfileDetails {
customer_profile_id: Secret<String>,
payment_profile: PaymentProfileDetails,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct PaymentProfileDetails {
payment_profile_id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomerDetails {
id: String,
email: Option<Email>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingOptions {
is_subsequent_auth: bool,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BillTo {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address: Option<Secret<String>>,
city: Option<String>,
state: Option<Secret<String>>,
zip: Option<Secret<String>>,
country: Option<enums::CountryAlpha2>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Order {
invoice_number: String,
description: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SubsequentAuthInformation {
original_network_trans_id: Secret<String>,
// original_auth_amount: String, Required for Discover, Diners Club, JCB, and China Union Pay transactions.
reason: Reason,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Reason {
Resubmission,
#[serde(rename = "delayedCharge")]
DelayedCharge,
Reauthorization,
#[serde(rename = "noShow")]
NoShow,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct TransactionVoidOrCaptureRequest {
transaction_type: TransactionType,
#[serde(skip_serializing_if = "Option::is_none")]
amount: Option<FloatMajorUnit>,
ref_trans_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetPaymentsRequest {
merchant_authentication: AuthorizedotnetAuthType,
ref_id: Option<String>,
transaction_request: TransactionRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetPaymentCancelOrCaptureRequest {
merchant_authentication: AuthorizedotnetAuthType,
transaction_request: TransactionVoidOrCaptureRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
// The connector enforces field ordering, it expects fields to be in the same order as in their API documentation
pub struct CustomerRequest {
create_customer_profile_request: CreateCustomerRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateCustomerRequest {
merchant_authentication: AuthorizedotnetAuthType,
profile: Profile,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateCustomerPaymentProfileRequest {
create_customer_payment_profile_request: AuthorizedotnetPaymentProfileRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetPaymentProfileRequest {
merchant_authentication: AuthorizedotnetAuthType,
customer_profile_id: Secret<String>,
payment_profile: PaymentProfile,
validation_mode: ValidationMode,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ShipToList {
#[serde(skip_serializing_if = "Option::is_none")]
first_name: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
last_name: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
address: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
city: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
state: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
zip: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
country: Option<enums::CountryAlpha2>,
#[serde(skip_serializing_if = "Option::is_none")]
phone_number: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct Profile {
#[serde(skip_serializing_if = "Option::is_none")]
merchant_customer_id: Option<CustomerId>,
#[serde(skip_serializing_if = "Option::is_none")]
description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
email: Option<Email>,
#[serde(skip_serializing_if = "Option::is_none")]
payment_profiles: Option<PaymentProfiles>,
#[serde(skip_serializing_if = "Option::is_none")]
ship_to_list: Option<Vec<ShipToList>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct PaymentProfiles {
customer_type: CustomerType,
#[serde(skip_serializing_if = "Option::is_none")]
bill_to: Option<BillTo>,
payment: PaymentDetails,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct PaymentProfile {
#[serde(skip_serializing_if = "Option::is_none")]
bill_to: Option<BillTo>,
payment: PaymentDetails,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CustomerType {
Individual,
Business,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ValidationMode {
// testMode performs a Luhn mod-10 check on the card number, without further validation at connector.
TestMode,
// liveMode submits a zero-dollar or one-cent transaction (depending on card type and processor support) to confirm that the card number belongs to an active credit or debit account.
LiveMode,
}
impl ForeignTryFrom<Value> for Vec<UserField> {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(metadata: Value) -> Result<Self, Self::Error> {
let hashmap: BTreeMap<String, Value> = serde_json::from_str(&metadata.to_string())
.change_context(errors::ConnectorError::RequestEncodingFailedWithReason(
"Failed to serialize request metadata".to_owned(),
))
.attach_printable("")?;
let mut vector: Self = Self::new();
for (key, value) in hashmap {
let string_value = match value {
Value::Bool(boolean) => boolean.to_string(),
Value::Number(number) => number.to_string(),
Value::String(string) => string.to_string(),
_ => value.to_string(),
};
vector.push(UserField {
name: key,
value: string_value,
});
}
Ok(vector)
}
}
impl TryFrom<&ConnectorCustomerRouterData> for CustomerRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ConnectorCustomerRouterData) -> Result<Self, Self::Error> {
let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
let ship_to_list = item.get_optional_shipping().and_then(|shipping| {
shipping.address.as_ref().map(|address| {
vec![ShipToList {
first_name: address.first_name.clone(),
last_name: address.last_name.clone(),
address: address.line1.clone(),
city: address.city.clone(),
state: address.state.clone(),
zip: address.zip.clone(),
country: address.country,
phone_number: shipping
.phone
.as_ref()
.and_then(|phone| phone.number.as_ref().map(|number| number.to_owned())),
}]
})
});
let merchant_customer_id = match item.customer_id.as_ref() {
Some(cid) if cid.get_string_repr().len() <= MAX_ID_LENGTH => Some(cid.clone()),
_ => None,
};
Ok(Self {
create_customer_profile_request: CreateCustomerRequest {
merchant_authentication,
profile: Profile {
merchant_customer_id,
description: None,
email: item.request.email.clone(),
payment_profiles: None,
ship_to_list,
},
},
})
}
}
impl TryFrom<&SetupMandateRouterData> for CreateCustomerPaymentProfileRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
let validation_mode = match item.test_mode {
Some(true) | None => ValidationMode::TestMode,
Some(false) => ValidationMode::LiveMode,
};
let customer_profile_id = item.get_connector_customer_id()?.into();
let bill_to = item
.get_optional_billing()
.and_then(|billing_address| billing_address.address.as_ref())
.map(|address| BillTo {
first_name: address.first_name.clone(),
last_name: address.last_name.clone(),
address: get_address_line(&address.line1, &address.line2, &address.line3),
city: address.city.clone(),
state: address.state.clone(),
zip: address.zip.clone(),
country: address.country,
});
let payment_profile = match item.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => Ok(PaymentProfile {
bill_to,
payment: PaymentDetails::CreditCard(CreditCardDetails {
card_number: (*ccard.card_number).clone(),
expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
card_code: Some(ccard.card_cvc.clone()),
}),
}),
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::GooglePay(_) => Ok(PaymentProfile {
bill_to,
payment: PaymentDetails::OpaqueData(WalletDetails {
data_descriptor: WalletMethod::Googlepay,
data_value: Secret::new(wallet_data.get_encoded_wallet_token()?),
}),
}),
WalletData::ApplePay(applepay_token) => {
let apple_pay_encrypted_data = applepay_token
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
Ok(PaymentProfile {
bill_to,
payment: PaymentDetails::OpaqueData(WalletDetails {
data_descriptor: WalletMethod::Applepay,
data_value: Secret::new(apple_pay_encrypted_data.clone()),
}),
})
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::BluecodeRedirect {}
| WalletData::Skrill(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
)),
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))
}
}?;
Ok(Self {
create_customer_payment_profile_request: AuthorizedotnetPaymentProfileRequest {
merchant_authentication,
customer_profile_id,
payment_profile,
validation_mode,
},
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetSetupMandateResponse {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
customer_payment_profile_id_list: Vec<String>,
customer_profile_id: Option<String>,
#[serde(rename = "customerPaymentProfileId")]
customer_payment_profile_id: Option<String>,
validation_direct_response_list: Option<Vec<Secret<String>>>,
pub messages: ResponseMessages,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetCustomerResponse {
customer_profile_id: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
customer_payment_profile_id_list: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
customer_shipping_address_id_list: Vec<String>,
pub messages: ResponseMessages,
}
fn extract_customer_id(text: &str) -> Option<String> {
let re = Regex::new(r"ID (\d+)").ok()?;
re.captures(text)
.and_then(|captures| captures.get(1))
.map(|capture_match| capture_match.as_str().to_string())
}
impl<F, T> TryFrom<ResponseRouterData<F, AuthorizedotnetCustomerResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AuthorizedotnetCustomerResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.messages.result_code {
ResultCode::Ok => match item.response.customer_profile_id.clone() {
Some(connector_customer_id) => Ok(Self {
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(connector_customer_id),
)),
..item.data
}),
None => Err(
errors::ConnectorError::UnexpectedResponseError(bytes::Bytes::from(
"Missing customer profile id from Authorizedotnet".to_string(),
))
.into(),
),
},
ResultCode::Error => {
let error_message = item.response.messages.message.first();
if let Some(connector_customer_id) =
error_message.and_then(|error| extract_customer_id(&error.text))
{
Ok(Self {
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(
connector_customer_id,
),
)),
..item.data
})
} else {
let error_code = error_message.map(|error| error.code.clone());
let error_code = error_code.unwrap_or_else(|| {
hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()
});
let error_reason = item
.response
.messages
.message
.iter()
.map(|error: &ResponseMessage| error.text.clone())
.collect::<Vec<String>>()
.join(" ");
let response = Err(ErrorResponse {
code: error_code,
message: item.response.messages.result_code.to_string(),
reason: Some(error_reason),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
response,
status: enums::AttemptStatus::Failure,
..item.data
})
}
}
}
}
}
// zero dollar response
impl<F, T>
TryFrom<ResponseRouterData<F, AuthorizedotnetSetupMandateResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AuthorizedotnetSetupMandateResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let connector_customer_id = item.data.get_connector_customer_id()?;
if item.response.customer_profile_id.is_some() {
Ok(Self {
status: enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(Some(MandateReference {
connector_mandate_id: item
.response
.customer_payment_profile_id_list
.first()
.or(item.response.customer_payment_profile_id.as_ref())
.map(|payment_profile_id| {
format!("{connector_customer_id}-{payment_profile_id}")
}),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
} else {
let error_message = item.response.messages.message.first();
let error_code = error_message.map(|error| error.code.clone());
let error_code = error_code
.unwrap_or_else(|| hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string());
let error_reason = item
.response
.messages
.message
.iter()
.map(|error: &ResponseMessage| error.text.clone())
.collect::<Vec<String>>()
.join(" ");
let response = Err(ErrorResponse {
code: error_code,
message: item.response.messages.result_code.to_string(),
reason: Some(error_reason),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
response,
status: enums::AttemptStatus::Failure,
..item.data
})
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
// The connector enforces field ordering, it expects fields to be in the same order as in their API documentation
pub struct CreateTransactionRequest {
create_transaction_request: AuthorizedotnetPaymentsRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelOrCaptureTransactionRequest {
create_transaction_request: AuthorizedotnetPaymentCancelOrCaptureRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AuthorizationType {
Final,
Pre,
}
impl TryFrom<enums::CaptureMethod> for AuthorizationType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(capture_method: enums::CaptureMethod) -> Result<Self, Self::Error> {
match capture_method {
enums::CaptureMethod::Manual => Ok(Self::Pre),
enums::CaptureMethod::SequentialAutomatic | enums::CaptureMethod::Automatic => {
Ok(Self::Final)
}
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
utils::construct_not_supported_error_report(capture_method, "authorizedotnet"),
)?,
}
}
}
impl TryFrom<&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>>
for CreateTransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
let ref_id = if item.router_data.connector_request_reference_id.len() <= MAX_ID_LENGTH {
Some(item.router_data.connector_request_reference_id.clone())
} else {
None
};
let transaction_request = match item
.router_data
.request
.mandate_id
.clone()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id)
{
Some(api_models::payments::MandateReferenceId::NetworkMandateId(network_trans_id)) => {
TransactionRequest::try_from((item, network_trans_id))?
}
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_id,
)) => TransactionRequest::try_from((item, connector_mandate_id))?,
Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_))
| Some(api_models::payments::MandateReferenceId::CardWithLimitedData) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))?
}
None => {
match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(ccard) => TransactionRequest::try_from((item, ccard)),
PaymentMethodData::Wallet(wallet_data) => {
TransactionRequest::try_from((item, wallet_data))
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"authorizedotnet",
),
))?
}
}
}?,
};
Ok(Self {
create_transaction_request: AuthorizedotnetPaymentsRequest {
merchant_authentication,
ref_id,
transaction_request,
},
})
}
}
impl
TryFrom<(
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
String,
)> for TransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, network_trans_id): (
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
String,
),
) -> Result<Self, Self::Error> {
Ok(Self {
transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
amount: item.amount,
currency_code: item.router_data.request.currency,
payment: Some(match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => {
PaymentDetails::CreditCard(CreditCardDetails {
card_number: (*ccard.card_number).clone(),
expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
card_code: None,
})
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))?
}
}),
profile: None,
order: Order {
invoice_number: match &item.router_data.request.merchant_order_reference_id {
Some(merchant_order_reference_id) => {
if merchant_order_reference_id.len() <= MAX_ID_LENGTH {
merchant_order_reference_id.to_string()
} else {
get_random_string()
}
}
None => get_random_string(),
},
description: item.router_data.connector_request_reference_id.clone(),
},
customer: Some(CustomerDetails {
id: if item.router_data.payment_id.len() <= MAX_ID_LENGTH {
item.router_data.payment_id.clone()
} else {
get_random_string()
},
email: item.router_data.request.get_optional_email(),
}),
bill_to: item
.router_data
.get_optional_billing()
.and_then(|billing_address| billing_address.address.as_ref())
.map(|address| BillTo {
first_name: address.first_name.clone(),
last_name: address.last_name.clone(),
address: get_address_line(&address.line1, &address.line2, &address.line3),
city: address.city.clone(),
state: address.state.clone(),
zip: address.zip.clone(),
country: address.country,
}),
user_fields: match item.router_data.request.metadata.clone() {
Some(metadata) => Some(UserFields {
user_field: Vec::<UserField>::foreign_try_from(metadata)?,
}),
None => None,
},
processing_options: Some(ProcessingOptions {
is_subsequent_auth: true,
}),
subsequent_auth_information: Some(SubsequentAuthInformation {
original_network_trans_id: Secret::new(network_trans_id),
reason: Reason::Resubmission,
}),
})
}
}
fn get_address_line(
address_line1: &Option<Secret<String>>,
address_line2: &Option<Secret<String>>,
address_line3: &Option<Secret<String>>,
) -> Option<Secret<String>> {
for lines in [
vec![address_line1, address_line2, address_line3],
vec![address_line1, address_line2],
] {
let combined: String = lines
.into_iter()
.flatten()
.map(|s| s.clone().expose())
.collect::<Vec<_>>()
.join(" ");
if !combined.is_empty() && combined.len() <= ADDRESS_MAX_LENGTH {
return Some(Secret::new(combined));
}
}
address_line1.clone()
}
impl
TryFrom<(
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
api_models::payments::ConnectorMandateReferenceId,
)> for TransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, connector_mandate_id): (
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
api_models::payments::ConnectorMandateReferenceId,
),
) -> Result<Self, Self::Error> {
let mandate_id = connector_mandate_id
.get_connector_mandate_id()
.ok_or(errors::ConnectorError::MissingConnectorMandateID)?;
Ok(Self {
transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
amount: item.amount,
currency_code: item.router_data.request.currency,
payment: None,
profile: mandate_id
.split_once('-')
.map(|(customer_profile_id, payment_profile_id)| {
ProfileDetails::CustomerProfileDetails(CustomerProfileDetails {
customer_profile_id: Secret::from(customer_profile_id.to_string()),
payment_profile: PaymentProfileDetails {
payment_profile_id: Secret::from(payment_profile_id.to_string()),
},
})
}),
order: Order {
invoice_number: match &item.router_data.request.merchant_order_reference_id {
Some(merchant_order_reference_id) => {
if merchant_order_reference_id.len() <= MAX_ID_LENGTH {
merchant_order_reference_id.to_string()
} else {
get_random_string()
}
}
None => get_random_string(),
},
description: item.router_data.connector_request_reference_id.clone(),
},
customer: None,
bill_to: None,
user_fields: match item.router_data.request.metadata.clone() {
Some(metadata) => Some(UserFields {
user_field: Vec::<UserField>::foreign_try_from(metadata)?,
}),
None => None,
},
processing_options: Some(ProcessingOptions {
is_subsequent_auth: true,
}),
subsequent_auth_information: None,
})
}
}
impl
TryFrom<(
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
&Card,
)> for TransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, ccard): (
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
&Card,
),
) -> Result<Self, Self::Error> {
if item.router_data.is_three_ds() {
return Err(errors::ConnectorError::NotSupported {
message: "3DS flow".to_string(),
connector: "Authorizedotnet",
}
.into());
};
let profile = if item
.router_data
.request
.is_customer_initiated_mandate_payment()
{
let connector_customer_id =
Secret::new(item.router_data.connector_customer.clone().ok_or(
errors::ConnectorError::MissingConnectorRelatedTransactionID {
id: "connector_customer_id".to_string(),
},
)?);
Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails {
create_profile: true,
customer_profile_id: Some(connector_customer_id),
}))
} else {
None
};
let customer = if !item
.router_data
.request
.is_customer_initiated_mandate_payment()
{
item.router_data.customer_id.as_ref().and_then(|customer| {
let customer_id = customer.get_string_repr();
(customer_id.len() <= MAX_ID_LENGTH).then_some(CustomerDetails {
id: customer_id.to_string(),
email: item.router_data.request.get_optional_email(),
})
})
} else {
None
};
Ok(Self {
transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
amount: item.amount,
currency_code: item.router_data.request.currency,
payment: Some(PaymentDetails::CreditCard(CreditCardDetails {
card_number: (*ccard.card_number).clone(),
expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
card_code: Some(ccard.card_cvc.clone()),
})),
profile,
order: Order {
invoice_number: match &item.router_data.request.merchant_order_reference_id {
Some(merchant_order_reference_id) => {
if merchant_order_reference_id.len() <= MAX_ID_LENGTH {
merchant_order_reference_id.to_string()
} else {
get_random_string()
}
}
None => get_random_string(),
},
description: item.router_data.connector_request_reference_id.clone(),
},
customer,
bill_to: item
.router_data
.get_optional_billing()
.and_then(|billing_address| billing_address.address.as_ref())
.map(|address| BillTo {
first_name: address.first_name.clone(),
last_name: address.last_name.clone(),
address: get_address_line(&address.line1, &address.line2, &address.line3),
city: address.city.clone(),
state: address.state.clone(),
zip: address.zip.clone(),
country: address.country,
}),
user_fields: match item.router_data.request.metadata.clone() {
Some(metadata) => Some(UserFields {
user_field: Vec::<UserField>::foreign_try_from(metadata)?,
}),
None => None,
},
processing_options: None,
subsequent_auth_information: None,
})
}
}
impl
TryFrom<(
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
&WalletData,
)> for TransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, wallet_data): (
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
&WalletData,
),
) -> Result<Self, Self::Error> {
let profile = if item
.router_data
.request
.is_customer_initiated_mandate_payment()
{
let connector_customer_id =
Secret::new(item.router_data.connector_customer.clone().ok_or(
errors::ConnectorError::MissingConnectorRelatedTransactionID {
id: "connector_customer_id".to_string(),
},
)?);
Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails {
create_profile: true,
customer_profile_id: Some(connector_customer_id),
}))
} else {
None
};
let customer = if !item
.router_data
.request
.is_customer_initiated_mandate_payment()
{
item.router_data.customer_id.as_ref().and_then(|customer| {
let customer_id = customer.get_string_repr();
(customer_id.len() <= MAX_ID_LENGTH).then_some(CustomerDetails {
id: customer_id.to_string(),
email: item.router_data.request.get_optional_email(),
})
})
} else {
None
};
Ok(Self {
transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
amount: item.amount,
currency_code: item.router_data.request.currency,
payment: Some(get_wallet_data(
wallet_data,
&item.router_data.request.complete_authorize_url,
)?),
profile,
order: Order {
invoice_number: match &item.router_data.request.merchant_order_reference_id {
Some(merchant_order_reference_id) => {
if merchant_order_reference_id.len() <= MAX_ID_LENGTH {
merchant_order_reference_id.to_string()
} else {
get_random_string()
}
}
None => get_random_string(),
},
description: item.router_data.connector_request_reference_id.clone(),
},
customer,
bill_to: item
.router_data
.get_optional_billing()
.and_then(|billing_address| billing_address.address.as_ref())
.map(|address| BillTo {
first_name: address.first_name.clone(),
last_name: address.last_name.clone(),
address: get_address_line(&address.line1, &address.line2, &address.line3),
city: address.city.clone(),
state: address.state.clone(),
zip: address.zip.clone(),
country: address.country,
}),
user_fields: match item.router_data.request.metadata.clone() {
Some(metadata) => Some(UserFields {
user_field: Vec::<UserField>::foreign_try_from(metadata)?,
}),
None => None,
},
processing_options: None,
subsequent_auth_information: None,
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for CancelOrCaptureTransactionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let transaction_request = TransactionVoidOrCaptureRequest {
amount: None, //amount is not required for void
transaction_type: TransactionType::Void,
ref_trans_id: item.request.connector_transaction_id.to_string(),
};
let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
create_transaction_request: AuthorizedotnetPaymentCancelOrCaptureRequest {
merchant_authentication,
transaction_request,
},
})
}
}
impl TryFrom<&AuthorizedotnetRouterData<&PaymentsCaptureRouterData>>
for CancelOrCaptureTransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthorizedotnetRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let transaction_request = TransactionVoidOrCaptureRequest {
amount: Some(item.amount),
transaction_type: TransactionType::Capture,
ref_trans_id: item
.router_data
.request
.connector_transaction_id
.to_string(),
};
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
create_transaction_request: AuthorizedotnetPaymentCancelOrCaptureRequest {
merchant_authentication,
transaction_request,
},
})
}
}
#[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)]
pub enum AuthorizedotnetPaymentStatus {
#[serde(rename = "1")]
Approved,
#[serde(rename = "2")]
Declined,
#[serde(rename = "3")]
Error,
#[serde(rename = "4")]
#[default]
HeldForReview,
#[serde(rename = "5")]
RequiresAction,
}
#[derive(Debug, Clone, serde::Deserialize, Serialize)]
pub enum AuthorizedotnetRefundStatus {
#[serde(rename = "1")]
Approved,
#[serde(rename = "2")]
Declined,
#[serde(rename = "3")]
Error,
#[serde(rename = "4")]
HeldForReview,
}
fn get_payment_status(
(item, auto_capture): (AuthorizedotnetPaymentStatus, bool),
) -> enums::AttemptStatus {
match item {
AuthorizedotnetPaymentStatus::Approved => {
if auto_capture {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
AuthorizedotnetPaymentStatus::Declined | AuthorizedotnetPaymentStatus::Error => {
enums::AttemptStatus::Failure
}
AuthorizedotnetPaymentStatus::RequiresAction => enums::AttemptStatus::AuthenticationPending,
AuthorizedotnetPaymentStatus::HeldForReview => enums::AttemptStatus::Pending,
}
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Serialize)]
pub struct ResponseMessage {
code: String,
pub text: String,
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Serialize, strum::Display)]
enum ResultCode {
#[default]
Ok,
Error,
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResponseMessages {
result_code: ResultCode,
pub message: Vec<ResponseMessage>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorMessage {
pub error_code: String,
pub error_text: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum TransactionResponse {
AuthorizedotnetTransactionResponse(Box<AuthorizedotnetTransactionResponse>),
AuthorizedotnetTransactionResponseError(Box<AuthorizedotnetTransactionResponseError>),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct AuthorizedotnetTransactionResponseError {
_supplemental_data_qualification_indicator: i64,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetTransactionResponse {
response_code: AuthorizedotnetPaymentStatus,
#[serde(rename = "transId")]
transaction_id: String,
network_trans_id: Option<Secret<String>>,
pub(super) account_number: Option<Secret<String>>,
pub(super) errors: Option<Vec<ErrorMessage>>,
secure_acceptance: Option<SecureAcceptance>,
avs_result_code: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
response_code: AuthorizedotnetRefundStatus,
#[serde(rename = "transId")]
transaction_id: String,
#[allow(dead_code)]
network_trans_id: Option<Secret<String>>,
pub account_number: Option<Secret<String>>,
pub errors: Option<Vec<ErrorMessage>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct SecureAcceptance {
secure_acceptance_url: Option<url::Url>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetPaymentsResponse {
pub transaction_response: Option<TransactionResponse>,
pub profile_response: Option<AuthorizedotnetNonZeroMandateResponse>,
pub messages: ResponseMessages,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetNonZeroMandateResponse {
customer_profile_id: Option<String>,
customer_payment_profile_id_list: Option<Vec<String>>,
pub messages: ResponseMessages,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetVoidResponse {
pub transaction_response: Option<VoidResponse>,
pub messages: ResponseMessages,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoidResponse {
response_code: AuthorizedotnetVoidStatus,
#[serde(rename = "transId")]
transaction_id: String,
network_trans_id: Option<Secret<String>>,
pub account_number: Option<Secret<String>>,
pub errors: Option<Vec<ErrorMessage>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum AuthorizedotnetVoidStatus {
#[serde(rename = "1")]
Approved,
#[serde(rename = "2")]
Declined,
#[serde(rename = "3")]
Error,
#[serde(rename = "4")]
HeldForReview,
}
impl From<AuthorizedotnetVoidStatus> for enums::AttemptStatus {
fn from(item: AuthorizedotnetVoidStatus) -> Self {
match item {
AuthorizedotnetVoidStatus::Approved => Self::Voided,
AuthorizedotnetVoidStatus::Declined | AuthorizedotnetVoidStatus::Error => {
Self::VoidFailed
}
AuthorizedotnetVoidStatus::HeldForReview => Self::VoidInitiated,
}
}
}
fn get_avs_response_description(code: &str) -> Option<&'static str> {
match code {
"A" => Some("The street address matched, but the postal code did not."),
"B" => Some("No address information was provided."),
"E" => Some(
"AVS data provided is invalid or AVS is not allowed for the card type that was used.",
),
"G" => Some("The card was issued by a bank outside the U.S. and does not support AVS."),
"N" => Some("Neither the street address nor postal code matched."),
"P" => Some("AVS is not applicable for this transaction."),
"R" => Some("Retry — AVS was unavailable or timed out."),
"S" => Some("AVS is not supported by card issuer."),
"U" => Some("Address information is unavailable."),
"W" => Some("The US ZIP+4 code matches, but the street address does not."),
"X" => Some("Both the street address and the US ZIP+4 code matched."),
"Y" => Some("The street address and postal code matched."),
"Z" => Some("The postal code matched, but the street address did not."),
_ => None,
}
}
fn convert_to_additional_payment_method_connector_response(
transaction_response: &AuthorizedotnetTransactionResponse,
) -> Option<AdditionalPaymentMethodConnectorResponse> {
match transaction_response.avs_result_code.as_deref() {
Some("P") | None => None,
Some(code) => {
let description = get_avs_response_description(code);
let payment_checks = serde_json::json!({
"avs_result_code": code,
"description": description
});
Some(AdditionalPaymentMethodConnectorResponse::Card {
authentication_data: None,
payment_checks: Some(payment_checks),
card_network: None,
domestic_network: None,
auth_code: None,
})
}
}
}
impl<F, T>
ForeignTryFrom<(
ResponseRouterData<F, AuthorizedotnetPaymentsResponse, T, PaymentsResponseData>,
bool,
)> for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, is_auto_capture): (
ResponseRouterData<F, AuthorizedotnetPaymentsResponse, T, PaymentsResponseData>,
bool,
),
) -> Result<Self, Self::Error> {
match &item.response.transaction_response {
Some(TransactionResponse::AuthorizedotnetTransactionResponse(transaction_response)) => {
let status = get_payment_status((
transaction_response.response_code.clone(),
is_auto_capture,
));
let error = transaction_response.errors.as_ref().and_then(|errors| {
errors.iter().next().map(|error| ErrorResponse {
code: error.error_code.clone(),
message: error.error_text.clone(),
reason: Some(error.error_text.clone()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(transaction_response.transaction_id.clone()),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
});
let metadata = transaction_response
.account_number
.as_ref()
.map(|acc_no| {
construct_refund_payment_details(PaymentDetailAccountNumber::Masked(
acc_no.clone().expose(),
))
.encode_to_value()
})
.transpose()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "connector_metadata",
})?;
let connector_response_data =
convert_to_additional_payment_method_connector_response(transaction_response)
.map(ConnectorResponseData::with_additional_payment_method_data);
let url = transaction_response
.secure_acceptance
.as_ref()
.and_then(|x| x.secure_acceptance_url.to_owned());
let redirection_data = url.map(|url| RedirectForm::from((url, Method::Get)));
let mandate_reference = item.response.profile_response.map(|profile_response| {
let payment_profile_id = profile_response
.customer_payment_profile_id_list
.and_then(|customer_payment_profile_id_list| {
customer_payment_profile_id_list.first().cloned()
});
MandateReference {
connector_mandate_id: profile_response.customer_profile_id.and_then(
|customer_profile_id| {
payment_profile_id.map(|payment_profile_id| {
format!("{customer_profile_id}-{payment_profile_id}")
})
},
),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}
});
Ok(Self {
status,
response: match error {
Some(err) => Err(err),
None => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
transaction_response.transaction_id.clone(),
),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: metadata,
network_txn_id: transaction_response
.network_trans_id
.clone()
.map(|network_trans_id| network_trans_id.expose()),
connector_response_reference_id: Some(
transaction_response.transaction_id.clone(),
),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
},
connector_response: connector_response_data,
..item.data
})
}
Some(TransactionResponse::AuthorizedotnetTransactionResponseError(_)) | None => {
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(get_err_response(item.http_code, item.response.messages)?),
..item.data
})
}
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AuthorizedotnetVoidResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AuthorizedotnetVoidResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match &item.response.transaction_response {
Some(transaction_response) => {
let status = enums::AttemptStatus::from(transaction_response.response_code.clone());
let error = transaction_response.errors.as_ref().and_then(|errors| {
errors.iter().next().map(|error| ErrorResponse {
code: error.error_code.clone(),
message: error.error_text.clone(),
reason: Some(error.error_text.clone()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(transaction_response.transaction_id.clone()),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
});
let metadata = transaction_response
.account_number
.as_ref()
.map(|acc_no| {
construct_refund_payment_details(PaymentDetailAccountNumber::Masked(
acc_no.clone().expose(),
))
.encode_to_value()
})
.transpose()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "connector_metadata",
})?;
Ok(Self {
status,
response: match error {
Some(err) => Err(err),
None => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
transaction_response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: metadata,
network_txn_id: transaction_response
.network_trans_id
.clone()
.map(|network_trans_id| network_trans_id.expose()),
connector_response_reference_id: Some(
transaction_response.transaction_id.clone(),
),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
},
..item.data
})
}
None => Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(get_err_response(item.http_code, item.response.messages)?),
..item.data
}),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct RefundTransactionRequest {
transaction_type: TransactionType,
amount: FloatMajorUnit,
currency_code: String,
payment: PaymentDetails,
#[serde(rename = "refTransId")]
reference_transaction_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetRefundRequest {
merchant_authentication: AuthorizedotnetAuthType,
transaction_request: RefundTransactionRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
// The connector enforces field ordering, it expects fields to be in the same order as in their API documentation
pub struct CreateRefundRequest {
create_transaction_request: AuthorizedotnetRefundRequest,
}
impl<F> TryFrom<&AuthorizedotnetRouterData<&RefundsRouterData<F>>> for CreateRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthorizedotnetRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
let transaction_request = RefundTransactionRequest {
transaction_type: TransactionType::Refund,
amount: item.amount,
payment: get_refund_metadata(
&item.router_data.request.connector_metadata,
&item.router_data.request.additional_payment_method_data,
)?,
currency_code: item.router_data.request.currency.to_string(),
reference_transaction_id: item.router_data.request.connector_transaction_id.clone(),
};
Ok(Self {
create_transaction_request: AuthorizedotnetRefundRequest {
merchant_authentication,
transaction_request,
},
})
}
}
fn get_refund_metadata(
connector_metadata: &Option<Value>,
additional_payment_method: &Option<AdditionalPaymentData>,
) -> Result<PaymentDetails, error_stack::Report<errors::ConnectorError>> {
let payment_details_from_metadata = connector_metadata
.as_ref()
.get_required_value("connector_metadata")
.ok()
.and_then(|value| {
value
.clone()
.parse_value::<PaymentDetails>("PaymentDetails")
.ok()
});
let payment_details_from_additional_payment_method = match additional_payment_method {
Some(AdditionalPaymentData::Card(additional_card_info)) => {
additional_card_info.last4.clone().map(|last4| {
construct_refund_payment_details(PaymentDetailAccountNumber::UnMasked(
last4.to_string(),
))
})
}
_ => None,
};
match (
payment_details_from_metadata,
payment_details_from_additional_payment_method,
) {
(Some(payment_detail), _) => Ok(payment_detail),
(_, Some(payment_detail)) => Ok(payment_detail),
(None, None) => Err(errors::ConnectorError::MissingRequiredField {
field_name: "payment_details",
}
.into()),
}
}
impl From<AuthorizedotnetRefundStatus> for enums::RefundStatus {
fn from(item: AuthorizedotnetRefundStatus) -> Self {
match item {
AuthorizedotnetRefundStatus::Declined | AuthorizedotnetRefundStatus::Error => {
Self::Failure
}
AuthorizedotnetRefundStatus::Approved | AuthorizedotnetRefundStatus::HeldForReview => {
Self::Pending
}
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetRefundResponse {
pub transaction_response: RefundResponse,
pub messages: ResponseMessages,
}
impl<F> TryFrom<RefundsResponseRouterData<F, AuthorizedotnetRefundResponse>>
for RefundsRouterData<F>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<F, AuthorizedotnetRefundResponse>,
) -> Result<Self, Self::Error> {
let transaction_response = &item.response.transaction_response;
let refund_status = enums::RefundStatus::from(transaction_response.response_code.clone());
let error = transaction_response.errors.clone().and_then(|errors| {
errors.first().map(|error| ErrorResponse {
code: error.error_code.clone(),
message: error.error_text.clone(),
reason: Some(error.error_text.clone()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(transaction_response.transaction_id.clone()),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
});
Ok(Self {
response: match error {
Some(err) => Err(err),
None => Ok(RefundsResponseData {
connector_refund_id: transaction_response.transaction_id.clone(),
refund_status,
}),
},
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionDetails {
merchant_authentication: AuthorizedotnetAuthType,
#[serde(rename = "transId")]
transaction_id: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetCreateSyncRequest {
get_transaction_details_request: TransactionDetails,
}
impl<F> TryFrom<&AuthorizedotnetRouterData<&RefundsRouterData<F>>>
for AuthorizedotnetCreateSyncRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthorizedotnetRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let transaction_id = item.router_data.request.get_connector_refund_id()?;
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
let payload = Self {
get_transaction_details_request: TransactionDetails {
merchant_authentication,
transaction_id: Some(transaction_id),
},
};
Ok(payload)
}
}
impl TryFrom<&PaymentsSyncRouterData> for AuthorizedotnetCreateSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let transaction_id = Some(
item.request
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
);
let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
let payload = Self {
get_transaction_details_request: TransactionDetails {
merchant_authentication,
transaction_id,
},
};
Ok(payload)
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum SyncStatus {
RefundSettledSuccessfully,
RefundPendingSettlement,
AuthorizedPendingCapture,
CapturedPendingSettlement,
SettledSuccessfully,
Declined,
Voided,
CouldNotVoid,
GeneralError,
#[serde(rename = "FDSPendingReview")]
FDSPendingReview,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum RSyncStatus {
RefundSettledSuccessfully,
RefundPendingSettlement,
Declined,
GeneralError,
Voided,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SyncTransactionResponse {
#[serde(rename = "transId")]
transaction_id: String,
transaction_status: SyncStatus,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct AuthorizedotnetSyncResponse {
transaction: Option<SyncTransactionResponse>,
messages: ResponseMessages,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RSyncTransactionResponse {
#[serde(rename = "transId")]
transaction_id: String,
transaction_status: RSyncStatus,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct AuthorizedotnetRSyncResponse {
transaction: Option<RSyncTransactionResponse>,
messages: ResponseMessages,
}
impl From<SyncStatus> for enums::AttemptStatus {
fn from(transaction_status: SyncStatus) -> Self {
match transaction_status {
SyncStatus::SettledSuccessfully | SyncStatus::CapturedPendingSettlement => {
Self::Charged
}
SyncStatus::AuthorizedPendingCapture => Self::Authorized,
SyncStatus::Declined => Self::AuthenticationFailed,
SyncStatus::Voided => Self::Voided,
SyncStatus::CouldNotVoid => Self::VoidFailed,
SyncStatus::GeneralError => Self::Failure,
SyncStatus::RefundSettledSuccessfully
| SyncStatus::RefundPendingSettlement
| SyncStatus::FDSPendingReview => Self::Pending,
}
}
}
impl From<RSyncStatus> for enums::RefundStatus {
fn from(transaction_status: RSyncStatus) -> Self {
match transaction_status {
RSyncStatus::RefundSettledSuccessfully => Self::Success,
RSyncStatus::RefundPendingSettlement => Self::Pending,
RSyncStatus::Declined | RSyncStatus::GeneralError | RSyncStatus::Voided => {
Self::Failure
}
}
}
}
impl TryFrom<RefundsResponseRouterData<RSync, AuthorizedotnetRSyncResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, AuthorizedotnetRSyncResponse>,
) -> Result<Self, Self::Error> {
match item.response.transaction {
Some(transaction) => {
let refund_status = enums::RefundStatus::from(transaction.transaction_status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: transaction.transaction_id,
refund_status,
}),
..item.data
})
}
None => Ok(Self {
response: Err(get_err_response(item.http_code, item.response.messages)?),
..item.data
}),
}
}
}
impl<F, Req> TryFrom<ResponseRouterData<F, AuthorizedotnetSyncResponse, Req, PaymentsResponseData>>
for RouterData<F, Req, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AuthorizedotnetSyncResponse, Req, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.transaction {
Some(transaction) => {
let payment_status = enums::AttemptStatus::from(transaction.transaction_status);
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
transaction.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(transaction.transaction_id.clone()),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
status: payment_status,
..item.data
})
}
// E00053 indicates "server too busy"
// E00104 indicates "Server in maintenance"
// If the server is too busy or Server in maintenance, we return the already available data
None => match item
.response
.messages
.message
.iter()
.find(|msg| msg.code == "E00053" || msg.code == "E00104")
{
Some(_) => Ok(item.data),
None => Ok(Self {
response: Err(get_err_response(item.http_code, item.response.messages)?),
..item.data
}),
},
}
}
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct ErrorDetails {
pub code: Option<String>,
#[serde(rename = "type")]
pub error_type: Option<String>,
pub message: Option<String>,
pub param: Option<String>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct AuthorizedotnetErrorResponse {
pub error: ErrorDetails,
}
enum PaymentDetailAccountNumber {
Masked(String),
UnMasked(String),
}
fn construct_refund_payment_details(detail: PaymentDetailAccountNumber) -> PaymentDetails {
PaymentDetails::CreditCard(CreditCardDetails {
card_number: match detail {
PaymentDetailAccountNumber::Masked(masked) => masked.into(),
PaymentDetailAccountNumber::UnMasked(unmasked) => format!("XXXX{:}", unmasked).into(),
},
expiration_date: "XXXX".to_string().into(),
card_code: None,
})
}
impl TryFrom<Option<enums::CaptureMethod>> for TransactionType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(capture_method: Option<enums::CaptureMethod>) -> Result<Self, Self::Error> {
match capture_method {
Some(enums::CaptureMethod::Manual) => Ok(Self::Authorization),
Some(enums::CaptureMethod::SequentialAutomatic)
| Some(enums::CaptureMethod::Automatic)
| None => Ok(Self::Payment),
Some(enums::CaptureMethod::ManualMultiple) => {
Err(utils::construct_not_supported_error_report(
enums::CaptureMethod::ManualMultiple,
"authorizedotnet",
))?
}
Some(enums::CaptureMethod::Scheduled) => {
Err(utils::construct_not_supported_error_report(
enums::CaptureMethod::Scheduled,
"authorizedotnet",
))?
}
}
}
}
fn get_err_response(
status_code: u16,
message: ResponseMessages,
) -> Result<ErrorResponse, errors::ConnectorError> {
let response_message = message
.message
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
Ok(ErrorResponse {
code: response_message.code.clone(),
message: response_message.text.clone(),
reason: Some(response_message.text.clone()),
status_code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetWebhookObjectId {
pub webhook_id: String,
pub event_type: AuthorizedotnetWebhookEvent,
pub payload: AuthorizedotnetWebhookPayload,
}
#[derive(Debug, Deserialize)]
pub struct AuthorizedotnetWebhookPayload {
pub id: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetWebhookEventType {
pub event_type: AuthorizedotnetIncomingWebhookEventType,
}
#[derive(Debug, Deserialize)]
pub enum AuthorizedotnetWebhookEvent {
#[serde(rename = "net.authorize.payment.authorization.created")]
AuthorizationCreated,
#[serde(rename = "net.authorize.payment.priorAuthCapture.created")]
PriorAuthCapture,
#[serde(rename = "net.authorize.payment.authcapture.created")]
AuthCapCreated,
#[serde(rename = "net.authorize.payment.capture.created")]
CaptureCreated,
#[serde(rename = "net.authorize.payment.void.created")]
VoidCreated,
#[serde(rename = "net.authorize.payment.refund.created")]
RefundCreated,
}
///Including Unknown to map unknown webhook events
#[derive(Debug, Deserialize)]
pub enum AuthorizedotnetIncomingWebhookEventType {
#[serde(rename = "net.authorize.payment.authorization.created")]
AuthorizationCreated,
#[serde(rename = "net.authorize.payment.priorAuthCapture.created")]
PriorAuthCapture,
#[serde(rename = "net.authorize.payment.authcapture.created")]
AuthCapCreated,
#[serde(rename = "net.authorize.payment.capture.created")]
CaptureCreated,
#[serde(rename = "net.authorize.payment.void.created")]
VoidCreated,
#[serde(rename = "net.authorize.payment.refund.created")]
RefundCreated,
#[serde(other)]
Unknown,
}
impl From<AuthorizedotnetIncomingWebhookEventType> for IncomingWebhookEvent {
fn from(event_type: AuthorizedotnetIncomingWebhookEventType) -> Self {
match event_type {
AuthorizedotnetIncomingWebhookEventType::AuthorizationCreated
| AuthorizedotnetIncomingWebhookEventType::PriorAuthCapture
| AuthorizedotnetIncomingWebhookEventType::AuthCapCreated
| AuthorizedotnetIncomingWebhookEventType::CaptureCreated
| AuthorizedotnetIncomingWebhookEventType::VoidCreated => Self::PaymentIntentSuccess,
AuthorizedotnetIncomingWebhookEventType::RefundCreated => Self::RefundSuccess,
AuthorizedotnetIncomingWebhookEventType::Unknown => Self::EventNotSupported,
}
}
}
impl From<AuthorizedotnetWebhookEvent> for SyncStatus {
// status mapping reference https://developer.authorize.net/api/reference/features/webhooks.html#Event_Types_and_Payloads
fn from(event_type: AuthorizedotnetWebhookEvent) -> Self {
match event_type {
AuthorizedotnetWebhookEvent::AuthorizationCreated => Self::AuthorizedPendingCapture,
AuthorizedotnetWebhookEvent::CaptureCreated
| AuthorizedotnetWebhookEvent::AuthCapCreated => Self::CapturedPendingSettlement,
AuthorizedotnetWebhookEvent::PriorAuthCapture => Self::SettledSuccessfully,
AuthorizedotnetWebhookEvent::VoidCreated => Self::Voided,
AuthorizedotnetWebhookEvent::RefundCreated => Self::RefundSettledSuccessfully,
}
}
}
pub fn get_trans_id(
details: &AuthorizedotnetWebhookObjectId,
) -> Result<String, errors::ConnectorError> {
details
.payload
.id
.clone()
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)
}
impl TryFrom<AuthorizedotnetWebhookObjectId> for AuthorizedotnetSyncResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: AuthorizedotnetWebhookObjectId) -> Result<Self, Self::Error> {
Ok(Self {
transaction: Some(SyncTransactionResponse {
transaction_id: get_trans_id(&item)?,
transaction_status: SyncStatus::from(item.event_type),
}),
messages: ResponseMessages {
..Default::default()
},
})
}
}
fn get_wallet_data(
wallet_data: &WalletData,
return_url: &Option<String>,
) -> CustomResult<PaymentDetails, errors::ConnectorError> {
match wallet_data {
WalletData::GooglePay(_) => Ok(PaymentDetails::OpaqueData(WalletDetails {
data_descriptor: WalletMethod::Googlepay,
data_value: Secret::new(wallet_data.get_encoded_wallet_token()?),
})),
WalletData::ApplePay(applepay_token) => {
let apple_pay_encrypted_data = applepay_token
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
Ok(PaymentDetails::OpaqueData(WalletDetails {
data_descriptor: WalletMethod::Applepay,
data_value: Secret::new(apple_pay_encrypted_data.clone()),
}))
}
WalletData::PaypalRedirect(_) => Ok(PaymentDetails::PayPal(PayPalDetails {
success_url: return_url.to_owned(),
cancel_url: return_url.to_owned(),
})),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))?,
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetQueryParams {
payer_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaypalConfirmRequest {
create_transaction_request: PaypalConfirmTransactionRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaypalConfirmTransactionRequest {
merchant_authentication: AuthorizedotnetAuthType,
transaction_request: TransactionConfirmRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionConfirmRequest {
transaction_type: TransactionType,
payment: PaypalPaymentConfirm,
ref_trans_id: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaypalPaymentConfirm {
pay_pal: Paypal,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Paypal {
#[serde(rename = "payerID")]
payer_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaypalQueryParams {
#[serde(rename = "PayerID")]
payer_id: Option<Secret<String>>,
}
impl TryFrom<&AuthorizedotnetRouterData<&PaymentsCompleteAuthorizeRouterData>>
for PaypalConfirmRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthorizedotnetRouterData<&PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let params = item
.router_data
.request
.redirect_response
.as_ref()
.and_then(|redirect_response| redirect_response.params.as_ref())
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let query_params: PaypalQueryParams = serde_urlencoded::from_str(params.peek())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable("Failed to parse connector response")?;
let payer_id = query_params.payer_id;
let transaction_type = match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual) => Ok(TransactionType::ContinueAuthorization),
Some(enums::CaptureMethod::SequentialAutomatic)
| Some(enums::CaptureMethod::Automatic)
| None => Ok(TransactionType::ContinueCapture),
Some(enums::CaptureMethod::ManualMultiple) => {
Err(errors::ConnectorError::NotSupported {
message: enums::CaptureMethod::ManualMultiple.to_string(),
connector: "authorizedotnet",
})
}
Some(enums::CaptureMethod::Scheduled) => Err(errors::ConnectorError::NotSupported {
message: enums::CaptureMethod::Scheduled.to_string(),
connector: "authorizedotnet",
}),
}?;
let transaction_request = TransactionConfirmRequest {
transaction_type,
payment: PaypalPaymentConfirm {
pay_pal: Paypal { payer_id },
},
ref_trans_id: item.router_data.request.connector_transaction_id.clone(),
};
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
create_transaction_request: PaypalConfirmTransactionRequest {
merchant_authentication,
transaction_request,
},
})
}
}
|
crates__hyperswitch_connectors__src__connectors__bambora.rs
|
pub mod transformers;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
CompleteAuthorize,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{
self, PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType,
PaymentsSyncType, PaymentsVoidType, Response,
},
webhooks,
};
use lazy_static::lazy_static;
use masking::Mask;
use transformers as bambora;
use crate::{
connectors::bambora::transformers::BamboraRouterData,
constants::headers,
types::ResponseRouterData,
utils::{self, convert_amount, RefundsRequestData},
};
#[derive(Clone)]
pub struct Bambora {
amount_convertor: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Bambora {
pub fn new() -> &'static Self {
&Self {
amount_convertor: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Bambora {}
impl api::PaymentToken for Bambora {}
impl api::PaymentAuthorize for Bambora {}
impl api::PaymentVoid for Bambora {}
impl api::MandateSetup for Bambora {}
impl api::ConnectorAccessToken for Bambora {}
impl api::PaymentSync for Bambora {}
impl api::PaymentCapture for Bambora {}
impl api::PaymentSession for Bambora {}
impl api::Refund for Bambora {}
impl api::RefundExecute for Bambora {}
impl api::RefundSync for Bambora {}
impl api::PaymentsCompleteAuthorize for Bambora {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Bambora
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Bambora {
fn id(&self) -> &'static str {
"bambora"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.bambora.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = bambora::BamboraAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: bambora::BamboraErrorResponse = res
.response
.parse_struct("BamboraErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code.to_string(),
message: serde_json::to_string(&response.details)
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason: Some(response.message),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Bambora {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Bambora
{
// Not Implemented (R)
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Bambora {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Bambora {
//TODO: implement sessions flow
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Bambora {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Bambora".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Bambora {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "/v1/payments"))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = BamboraRouterData::try_from((amount, req))?;
let connector_req = bambora::BamboraPaymentsRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: bambora::BamboraResponse = res
.response
.parse_struct("PaymentIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Bambora
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let meta: bambora::BamboraMeta =
utils::to_connector_meta(req.request.connector_meta.clone())?;
Ok(format!(
"{}/v1/payments/{}{}",
self.base_url(connectors),
meta.three_d_session_data,
"/continue"
))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = bambora::BamboraThreedsContinueRequest::try_from(&req.request)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: bambora::BamboraPaymentsResponse = res
.response
.parse_struct("BamboraPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Bambora {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/v1/payments/{connector_payment_id}",
self.base_url(connectors),
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: bambora::BamboraPaymentsResponse = res
.response
.parse_struct("bambora PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Bambora {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/v1/payments/{}/completions",
self.base_url(connectors),
req.request.connector_transaction_id,
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = BamboraRouterData::try_from((amount, req))?;
let connector_req =
bambora::BamboraPaymentsCaptureRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: bambora::BamboraPaymentsResponse = res
.response
.parse_struct("Bambora PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Bambora {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/v1/payments/{}/void",
self.base_url(connectors),
connector_payment_id,
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let currency =
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "Currency",
})?;
let minor_amount =
req.request
.minor_amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "Amount",
})?;
let amount = convert_amount(self.amount_convertor, minor_amount, currency)?;
let connector_router_data = BamboraRouterData::try_from((amount, req))?;
let connector_req = bambora::BamboraVoidRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: bambora::BamboraPaymentsResponse = res
.response
.parse_struct("bambora PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorRedirectResponse for Bambora {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
action: enums::PaymentAction,
) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> {
match action {
enums::PaymentAction::PSync
| enums::PaymentAction::CompleteAuthorize
| enums::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
Ok(enums::CallConnectorAction::Trigger)
}
}
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Bambora {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/v1/payments/{}/returns",
self.base_url(connectors),
connector_payment_id,
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = BamboraRouterData::try_from((amount, req))?;
let connector_req = bambora::BamboraRefundRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: bambora::RefundResponse = res
.response
.parse_struct("bambora RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Bambora {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let _connector_payment_id = req.request.connector_transaction_id.clone();
let connector_refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}/v1/payments/{}",
self.base_url(connectors),
connector_refund_id
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: bambora::RefundResponse = res
.response
.parse_struct("bambora RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Bambora {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
lazy_static! {
static ref BAMBORA_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
let default_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
];
let mut bambora_supported_payment_methods = SupportedPaymentMethods::new();
bambora_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: default_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
bambora_supported_payment_methods
};
static ref BAMBORA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Bambora",
description: "Bambora is a leading online payment provider in Canada and United States.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static ref BAMBORA_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
}
impl ConnectorSpecifications for Bambora {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*BAMBORA_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*BAMBORA_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*BAMBORA_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__bambora__transformers.rs
|
use base64::Engine;
use common_enums::enums;
use common_utils::{
ext_traits::ValueExt,
pii::{Email, IpAddress},
types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{CompleteAuthorizeData, PaymentsAuthorizeData, ResponseId},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Deserializer, Serialize};
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
},
utils::{
self, AddressDetailsData, BrowserInformationData, CardData as _,
PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
PaymentsSyncRequestData, RouterData as _,
},
};
pub struct BamboraRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(FloatMajorUnit, T)> for BamboraRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (FloatMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct BamboraCard {
name: Secret<String>,
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvd: Secret<String>,
complete: bool,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "3d_secure")]
three_d_secure: Option<ThreeDSecure>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct ThreeDSecure {
browser: Option<BamboraBrowserInfo>, //Needed only in case of 3Ds 2.0. Need to update request for this.
enabled: bool,
version: Option<i64>,
auth_required: Option<bool>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct BamboraBrowserInfo {
accept_header: String,
java_enabled: bool,
language: String,
color_depth: u8,
screen_height: u32,
screen_width: u32,
time_zone: i32,
user_agent: String,
javascript_enabled: bool,
}
#[derive(Default, Debug, Serialize)]
pub struct BamboraPaymentsRequest {
order_number: String,
amount: FloatMajorUnit,
payment_method: PaymentMethod,
customer_ip: Option<Secret<String, IpAddress>>,
term_url: Option<String>,
card: BamboraCard,
billing: AddressData,
}
#[derive(Default, Debug, Serialize)]
pub struct BamboraVoidRequest {
amount: FloatMajorUnit,
}
fn get_browser_info(
item: &types::PaymentsAuthorizeRouterData,
) -> Result<Option<BamboraBrowserInfo>, error_stack::Report<errors::ConnectorError>> {
if matches!(item.auth_type, enums::AuthenticationType::ThreeDs) {
item.request
.browser_info
.as_ref()
.map(|info| {
Ok(BamboraBrowserInfo {
accept_header: info.get_accept_header()?,
java_enabled: info.get_java_enabled()?,
language: info.get_language()?,
screen_height: info.get_screen_height()?,
screen_width: info.get_screen_width()?,
color_depth: info.get_color_depth()?,
user_agent: info.get_user_agent()?,
time_zone: info.get_time_zone()?,
javascript_enabled: info.get_java_script_enabled()?,
})
})
.transpose()
} else {
Ok(None)
}
}
impl TryFrom<&CompleteAuthorizeData> for BamboraThreedsContinueRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &CompleteAuthorizeData) -> Result<Self, Self::Error> {
let card_response: CardResponse = value
.redirect_response
.as_ref()
.and_then(|f| f.payload.to_owned())
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response.payload",
})?
.parse_value("CardResponse")
.change_context(errors::ConnectorError::ParsingFailed)?;
let bambora_req = Self {
payment_method: "credit_card".to_string(),
card_response,
};
Ok(bambora_req)
}
}
impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for BamboraPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: BamboraRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let (three_ds, customer_ip) = match item.router_data.auth_type {
enums::AuthenticationType::ThreeDs => (
Some(ThreeDSecure {
enabled: true,
browser: get_browser_info(item.router_data)?,
version: Some(2),
auth_required: Some(true),
}),
Some(
item.router_data
.request
.get_browser_info()?
.get_ip_address()?,
),
),
enums::AuthenticationType::NoThreeDs => (None, None),
};
let card = BamboraCard {
name: item.router_data.get_billing_address()?.get_full_name()?,
expiry_year: req_card.get_card_expiry_year_2_digit()?,
number: req_card.card_number,
expiry_month: req_card.card_exp_month,
cvd: req_card.card_cvc,
three_d_secure: three_ds,
complete: item.router_data.request.is_auto_capture()?,
};
let (country, province) = match (
item.router_data.get_optional_billing_country(),
item.router_data.get_optional_billing_state_2_digit(),
) {
(Some(billing_country), Some(billing_state)) => {
(Some(billing_country), Some(billing_state))
}
_ => (None, None),
};
let billing = AddressData {
name: item.router_data.get_optional_billing_full_name(),
address_line1: item.router_data.get_optional_billing_line1(),
address_line2: item.router_data.get_optional_billing_line2(),
city: item.router_data.get_optional_billing_city(),
province,
country,
postal_code: item.router_data.get_optional_billing_zip(),
phone_number: item.router_data.get_optional_billing_phone_number(),
email_address: item.router_data.get_optional_billing_email(),
};
Ok(Self {
order_number: item.router_data.connector_request_reference_id.clone(),
amount: item.amount,
payment_method: PaymentMethod::Card,
card,
customer_ip,
term_url: item.router_data.request.complete_authorize_url.clone(),
billing,
})
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("bambora"),
)
.into())
}
}
}
}
impl TryFrom<BamboraRouterData<&types::PaymentsCancelRouterData>> for BamboraVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: BamboraRouterData<&types::PaymentsCancelRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
})
}
}
pub struct BamboraAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BamboraAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
let auth_key = format!("{}:{}", key1.peek(), api_key.peek());
let auth_header = format!(
"Passcode {}",
common_utils::consts::BASE64_ENGINE.encode(auth_key)
);
Ok(Self {
api_key: Secret::new(auth_header),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
fn str_or_i32<'de, D>(deserializer: D) -> Result<String, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum StrOrI32 {
Str(String),
I32(i32),
}
let value = StrOrI32::deserialize(deserializer)?;
let res = match value {
StrOrI32::Str(v) => v,
StrOrI32::I32(v) => v.to_string(),
};
Ok(res)
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BamboraResponse {
NormalTransaction(Box<BamboraPaymentsResponse>),
ThreeDsResponse(Box<Bambora3DsResponse>),
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct BamboraPaymentsResponse {
#[serde(deserialize_with = "str_or_i32")]
id: String,
authorizing_merchant_id: i32,
#[serde(deserialize_with = "str_or_i32")]
approved: String,
#[serde(deserialize_with = "str_or_i32")]
message_id: String,
message: String,
auth_code: String,
created: String,
amount: FloatMajorUnit,
order_number: String,
#[serde(rename = "type")]
payment_type: String,
comments: Option<String>,
batch_number: Option<String>,
total_refunds: Option<f32>,
total_completions: Option<f32>,
payment_method: String,
card: CardData,
billing: Option<AddressData>,
shipping: Option<AddressData>,
custom: CustomData,
adjusted_by: Option<Vec<AdjustedBy>>,
links: Vec<Links>,
risk_score: Option<f32>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Bambora3DsResponse {
#[serde(rename = "3d_session_data")]
three_d_session_data: Secret<String>,
contents: String,
}
#[derive(Debug, Serialize, Default, Deserialize)]
pub struct BamboraMeta {
pub three_d_session_data: String,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct BamboraThreedsContinueRequest {
pub(crate) payment_method: String,
pub card_response: CardResponse,
}
#[derive(Default, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct CardResponse {
pub(crate) cres: Option<common_utils::pii::SecretSerdeValue>,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct CardData {
name: Option<Secret<String>>,
expiry_month: Option<Secret<String>>,
expiry_year: Option<Secret<String>>,
card_type: String,
last_four: Secret<String>,
card_bin: Option<Secret<String>>,
avs_result: String,
cvd_result: String,
cavv_result: Option<String>,
address_match: Option<i32>,
postal_result: Option<i32>,
avs: Option<AvsObject>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AvsObject {
id: String,
message: String,
processed: bool,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AddressData {
name: Option<Secret<String>>,
address_line1: Option<Secret<String>>,
address_line2: Option<Secret<String>>,
city: Option<String>,
province: Option<Secret<String>>,
country: Option<enums::CountryAlpha2>,
postal_code: Option<Secret<String>>,
phone_number: Option<Secret<String>>,
email_address: Option<Email>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CustomData {
ref1: String,
ref2: String,
ref3: String,
ref4: String,
ref5: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AdjustedBy {
id: i32,
#[serde(rename = "type")]
adjusted_by_type: String,
approval: i32,
message: String,
amount: FloatMajorUnit,
created: String,
url: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Links {
rel: String,
href: String,
method: String,
}
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum PaymentMethod {
#[default]
Card,
Token,
PaymentProfile,
Cash,
Cheque,
Interac,
ApplePay,
AndroidPay,
#[serde(rename = "3d_secure")]
ThreeDSecure,
ProcessorToken,
}
// Capture
#[derive(Default, Debug, Clone, Serialize, PartialEq)]
pub struct BamboraPaymentsCaptureRequest {
amount: FloatMajorUnit,
payment_method: PaymentMethod,
}
impl TryFrom<BamboraRouterData<&types::PaymentsCaptureRouterData>>
for BamboraPaymentsCaptureRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: BamboraRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
payment_method: PaymentMethod::Card,
})
}
}
impl<F> TryFrom<ResponseRouterData<F, BamboraResponse, PaymentsAuthorizeData, PaymentsResponseData>>
for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BamboraResponse, PaymentsAuthorizeData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
BamboraResponse::NormalTransaction(pg_response) => Ok(Self {
status: if pg_response.approved.as_str() == "1" {
match item.data.request.is_auto_capture()? {
true => enums::AttemptStatus::Charged,
false => enums::AttemptStatus::Authorized,
}
} else {
match item.data.request.is_auto_capture()? {
true => enums::AttemptStatus::Failure,
false => enums::AttemptStatus::AuthorizationFailed,
}
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(pg_response.id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(pg_response.order_number.to_string()),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
}),
BamboraResponse::ThreeDsResponse(response) => {
let value = url::form_urlencoded::parse(response.contents.as_bytes())
.map(|(key, val)| [key, val].concat())
.collect();
let redirection_data = Some(RedirectForm::Html { html_data: value });
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(
serde_json::to_value(BamboraMeta {
three_d_session_data: response.three_d_session_data.expose(),
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)?,
),
network_txn_id: None,
connector_response_reference_id: Some(
item.data.connector_request_reference_id.to_string(),
),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
}
}
impl<F>
TryFrom<
ResponseRouterData<F, BamboraPaymentsResponse, CompleteAuthorizeData, PaymentsResponseData>,
> for RouterData<F, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BamboraPaymentsResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: if item.response.approved.as_str() == "1" {
match item.data.request.is_auto_capture()? {
true => enums::AttemptStatus::Charged,
false => enums::AttemptStatus::Authorized,
}
} else {
match item.data.request.is_auto_capture()? {
true => enums::AttemptStatus::Failure,
false => enums::AttemptStatus::AuthorizationFailed,
}
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<BamboraPaymentsResponse>>
for types::PaymentsSyncRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<BamboraPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: match item.data.request.is_auto_capture()? {
true => {
if item.response.approved.as_str() == "1" {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Failure
}
}
false => {
if item.response.approved.as_str() == "1" {
enums::AttemptStatus::Authorized
} else {
enums::AttemptStatus::AuthorizationFailed
}
}
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<BamboraPaymentsResponse>>
for types::PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<BamboraPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: if item.response.approved.as_str() == "1" {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Failure
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<PaymentsCancelResponseRouterData<BamboraPaymentsResponse>>
for types::PaymentsCancelRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<BamboraPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: if item.response.approved.as_str() == "1" {
enums::AttemptStatus::Voided
} else {
enums::AttemptStatus::VoidFailed
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct BamboraRefundRequest {
amount: FloatMajorUnit,
}
impl<F> TryFrom<BamboraRouterData<&types::RefundsRouterData<F>>> for BamboraRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: BamboraRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
#[serde(deserialize_with = "str_or_i32")]
pub id: String,
pub authorizing_merchant_id: i32,
#[serde(deserialize_with = "str_or_i32")]
pub approved: String,
#[serde(deserialize_with = "str_or_i32")]
pub message_id: String,
pub message: String,
pub auth_code: String,
pub created: String,
pub amount: FloatMajorUnit,
pub order_number: String,
#[serde(rename = "type")]
pub payment_type: String,
pub comments: Option<String>,
pub batch_number: Option<String>,
pub total_refunds: Option<f32>,
pub total_completions: Option<f32>,
pub payment_method: String,
pub card: CardData,
pub billing: Option<AddressData>,
pub shipping: Option<AddressData>,
pub custom: CustomData,
pub adjusted_by: Option<Vec<AdjustedBy>>,
pub links: Vec<Links>,
pub risk_score: Option<f32>,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = if item.response.approved.as_str() == "1" {
enums::RefundStatus::Success
} else {
enums::RefundStatus::Failure
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = if item.response.approved.as_str() == "1" {
enums::RefundStatus::Success
} else {
enums::RefundStatus::Failure
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status,
}),
..item.data
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct BamboraErrorResponse {
pub code: i32,
pub category: i32,
pub message: String,
pub reference: String,
pub details: Option<Vec<ErrorDetail>>,
pub validation: Option<CardValidation>,
pub card: Option<CardError>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CardError {
pub avs: AVSDetails,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AVSDetails {
pub message: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ErrorDetail {
field: String,
message: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CardValidation {
id: String,
approved: i32,
message_id: i32,
message: String,
auth_code: String,
trans_date: String,
order_number: String,
type_: String,
amount: f64,
cvd_id: i32,
}
|
crates__hyperswitch_connectors__src__connectors__bamboraapac.rs
|
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::{BytesExt, XmlExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundExecuteRouterData, RefundSyncRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},
};
use transformers as bamboraapac;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, convert_amount},
};
#[derive(Clone)]
pub struct Bamboraapac {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Bamboraapac {
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Bamboraapac {}
impl api::PaymentSession for Bamboraapac {}
impl api::ConnectorAccessToken for Bamboraapac {}
impl api::MandateSetup for Bamboraapac {}
impl api::PaymentAuthorize for Bamboraapac {}
impl api::PaymentSync for Bamboraapac {}
impl api::PaymentCapture for Bamboraapac {}
impl api::PaymentVoid for Bamboraapac {}
impl api::Refund for Bamboraapac {}
impl api::RefundExecute for Bamboraapac {}
impl api::RefundSync for Bamboraapac {}
impl api::PaymentToken for Bamboraapac {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Bamboraapac
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Bamboraapac
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
_req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
Ok(header)
}
}
impl ConnectorValidation for Bamboraapac {
fn validate_mandate_payment(
&self,
_pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let connector = self.id();
match pm_data {
PaymentMethodData::Card(_) => Ok(()),
_ => Err(errors::ConnectorError::NotSupported {
message: "mandate payment".to_string(),
connector,
}
.into()),
}
}
}
impl ConnectorCommon for Bamboraapac {
fn id(&self) -> &'static str {
"bamboraapac"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"text/xml"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.bamboraapac.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<
bamboraapac::BamboraapacErrorResponse,
Report<common_utils::errors::ParsingError>,
> = res.response.parse_struct("BamboraapacErrorResponse");
match response {
Ok(response_data) => {
event_builder.map(|i| i.set_error_response_body(&response_data));
router_env::logger::info!(connector_response=?response_data);
Ok(ErrorResponse {
status_code: res.status_code,
code: response_data
.declined_code
.unwrap_or(NO_ERROR_CODE.to_string()),
message: response_data
.declined_message
.clone()
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: response_data.declined_message,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Err(error_msg) => {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
router_env::logger::error!(deserialization_error =? error_msg);
utils::handle_json_response_deserialization_failure(res, "bamboaraapac")
}
}
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Bamboraapac {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Bamboraapac {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Bamboraapac
{
fn get_headers(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/sipp.asmx", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = bamboraapac::get_setup_mandate_body(req)?;
Ok(RequestContent::RawBytes(connector_req))
}
fn build_request(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::SetupMandateType::get_headers(self, req, connectors)?)
.set_body(types::SetupMandateType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
let response_data = html_to_xml_string_conversion(
String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?,
);
let response = response_data
.parse_xml::<bamboraapac::BamboraapacMandateResponse>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Bamboraapac {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/dts.asmx", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = bamboraapac::BamboraapacRouterData::try_from((amount, req))?;
let connector_req = bamboraapac::get_payment_body(&connector_router_data)?;
Ok(RequestContent::RawBytes(connector_req))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response_data = html_to_xml_string_conversion(
String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?,
);
let response = response_data
.parse_xml::<bamboraapac::BamboraapacPaymentsResponse>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Bamboraapac {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/dts.asmx", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = bamboraapac::get_payment_sync_body(req)?;
Ok(RequestContent::RawBytes(connector_req))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response_data = html_to_xml_string_conversion(
String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?,
);
let response = response_data
.parse_xml::<bamboraapac::BamboraapacSyncResponse>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Bamboraapac {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/dts.asmx", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = bamboraapac::BamboraapacRouterData::try_from((amount, req))?;
let connector_req = bamboraapac::get_capture_body(&connector_router_data)?;
Ok(RequestContent::RawBytes(connector_req))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response_data = html_to_xml_string_conversion(
String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?,
);
let response = response_data
.parse_xml::<bamboraapac::BamboraapacCaptureResponse>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Bamboraapac {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Bamboraapac {
fn get_headers(
&self,
req: &RefundExecuteRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundExecuteRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/dts.asmx", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundExecuteRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = bamboraapac::BamboraapacRouterData::try_from((amount, req))?;
let connector_req = bamboraapac::get_refund_body(&connector_router_data)?;
Ok(RequestContent::RawBytes(connector_req))
}
fn build_request(
&self,
req: &RefundExecuteRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundExecuteRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundExecuteRouterData, errors::ConnectorError> {
let response_data = html_to_xml_string_conversion(
String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?,
);
let response = response_data
.parse_xml::<bamboraapac::BamboraapacRefundsResponse>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Bamboraapac {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/dts.asmx", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = bamboraapac::get_refund_sync_body(req)?;
Ok(RequestContent::RawBytes(connector_req))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response_data = html_to_xml_string_conversion(
String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?,
);
let response = response_data
.parse_xml::<bamboraapac::BamboraapacSyncResponse>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Bamboraapac {
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
fn html_to_xml_string_conversion(res: String) -> String {
res.replace("<", "<").replace(">", ">")
}
static BAMBORAAPAC_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let default_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::UnionPay,
];
let mut bamboraapac_supported_payment_methods = SupportedPaymentMethods::new();
bamboraapac_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: default_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
bamboraapac_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: default_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
bamboraapac_supported_payment_methods
});
static BAMBORAAPAC_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Bambora Asia-Pacific",
description: "Bambora Asia-Pacific, provides comprehensive payment solutions, offering merchants smart and smooth payment processing capabilities.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static BAMBORAAPAC_SUPPORTED_WEBHOOK_FLOWS: [common_enums::EventClass; 0] = [];
impl ConnectorSpecifications for Bamboraapac {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&BAMBORAAPAC_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*BAMBORAAPAC_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&BAMBORAAPAC_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__bamboraapac__transformers.rs
|
use common_enums::enums;
use common_utils::types::MinorUnit;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::{RefundsData, ResponseId, SetupMandateRequestData},
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsCaptureResponseRouterData, PaymentsResponseRouterData,
PaymentsSyncResponseRouterData, ResponseRouterData,
},
utils::{self, CardData as _, PaymentsAuthorizeRequestData, RouterData as _},
};
type Error = error_stack::Report<errors::ConnectorError>;
pub struct BamboraapacRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for BamboraapacRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BamboraapacMeta {
pub authorize_id: String,
}
// request body in soap format
pub fn get_payment_body(
req: &BamboraapacRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Vec<u8>, Error> {
let transaction_data = get_transaction_body(req)?;
let body = format!(
r#"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Body>
<dts:SubmitSinglePayment>
<dts:trnXML>
<![CDATA[
{transaction_data}
]]>
</dts:trnXML>
</dts:SubmitSinglePayment>
</soapenv:Body>
</soapenv:Envelope>
"#,
);
Ok(body.as_bytes().to_vec())
}
fn get_transaction_body(
req: &BamboraapacRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<String, Error> {
let auth_details = BamboraapacAuthType::try_from(&req.router_data.connector_auth_type)?;
let transaction_type = get_transaction_type(req.router_data.request.capture_method)?;
let card_info = get_card_data(req.router_data)?;
let transaction_data = format!(
r#"
<Transaction>
<CustRef>{}</CustRef>
<Amount>{}</Amount>
<TrnType>{}</TrnType>
<AccountNumber>{}</AccountNumber>
{}
<Security>
<UserName>{}</UserName>
<Password>{}</Password>
</Security>
</Transaction>
"#,
req.router_data.connector_request_reference_id.to_owned(),
req.amount,
transaction_type,
auth_details.account_number.peek(),
card_info,
auth_details.username.peek(),
auth_details.password.peek(),
);
Ok(transaction_data)
}
fn get_card_data(req: &types::PaymentsAuthorizeRouterData) -> Result<String, Error> {
let card_data = match &req.request.payment_method_data {
PaymentMethodData::Card(card) => {
if req.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Cards 3DS".to_string(),
connector: "Bamboraapac",
})?
}
let card_holder_name = req.get_billing_full_name()?;
if req.request.setup_future_usage == Some(enums::FutureUsage::OffSession) {
format!(
r#"
<CreditCard Registered="False">
<TokeniseAlgorithmID>2</TokeniseAlgorithmID>
<CardNumber>{}</CardNumber>
<ExpM>{}</ExpM>
<ExpY>{}</ExpY>
<CVN>{}</CVN>
<CardHolderName>{}</CardHolderName>
</CreditCard>
"#,
card.card_number.get_card_no(),
card.card_exp_month.peek(),
card.get_expiry_year_4_digit().peek(),
card.card_cvc.peek(),
card_holder_name.peek(),
)
} else {
format!(
r#"
<CreditCard Registered="False">
<CardNumber>{}</CardNumber>
<ExpM>{}</ExpM>
<ExpY>{}</ExpY>
<CVN>{}</CVN>
<CardHolderName>{}</CardHolderName>
</CreditCard>
"#,
card.card_number.get_card_no(),
card.card_exp_month.peek(),
card.get_expiry_year_4_digit().peek(),
card.card_cvc.peek(),
card_holder_name.peek(),
)
}
}
PaymentMethodData::MandatePayment => {
format!(
r#"
<CreditCard>
<TokeniseAlgorithmID>2</TokeniseAlgorithmID>
<CardNumber>{}</CardNumber>
</CreditCard>
"#,
req.request.get_connector_mandate_id()?
)
}
_ => {
return Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Bambora APAC"),
))?
}
};
Ok(card_data)
}
fn get_transaction_type(capture_method: Option<enums::CaptureMethod>) -> Result<u8, Error> {
match capture_method {
Some(enums::CaptureMethod::Automatic) | None => Ok(1),
Some(enums::CaptureMethod::Manual) => Ok(2),
_ => Err(errors::ConnectorError::CaptureMethodNotSupported)?,
}
}
pub struct BamboraapacAuthType {
username: Secret<String>,
password: Secret<String>,
account_number: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BamboraapacAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
username: api_key.to_owned(),
password: api_secret.to_owned(),
account_number: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Envelope")]
#[serde(rename_all = "PascalCase")]
pub struct BamboraapacPaymentsResponse {
body: BodyResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct BodyResponse {
submit_single_payment_response: SubmitSinglePaymentResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSinglePaymentResponse {
submit_single_payment_result: SubmitSinglePaymentResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSinglePaymentResult {
response: PaymentResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PaymentResponse {
response_code: u8,
receipt: String,
credit_card_token: Option<String>,
declined_code: Option<String>,
declined_message: Option<String>,
}
fn get_attempt_status(
response_code: u8,
capture_method: Option<enums::CaptureMethod>,
) -> enums::AttemptStatus {
match response_code {
0 => match capture_method {
Some(enums::CaptureMethod::Automatic) | None => enums::AttemptStatus::Charged,
Some(enums::CaptureMethod::Manual) => enums::AttemptStatus::Authorized,
_ => enums::AttemptStatus::Pending,
},
1 => enums::AttemptStatus::Failure,
_ => enums::AttemptStatus::Pending,
}
}
impl TryFrom<PaymentsResponseRouterData<BamboraapacPaymentsResponse>>
for types::PaymentsAuthorizeRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<BamboraapacPaymentsResponse>,
) -> Result<Self, Self::Error> {
let response_code = item
.response
.body
.submit_single_payment_response
.submit_single_payment_result
.response
.response_code;
let connector_transaction_id = item
.response
.body
.submit_single_payment_response
.submit_single_payment_result
.response
.receipt;
let mandate_reference =
if item.data.request.setup_future_usage == Some(enums::FutureUsage::OffSession) {
let connector_mandate_id = item
.response
.body
.submit_single_payment_response
.submit_single_payment_result
.response
.credit_card_token;
Some(MandateReference {
connector_mandate_id,
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})
} else {
None
};
// transaction approved
if response_code == 0 {
Ok(Self {
status: get_attempt_status(response_code, item.data.request.capture_method),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
connector_transaction_id.to_owned(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(connector_transaction_id),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
// transaction failed
else {
let code = item
.response
.body
.submit_single_payment_response
.submit_single_payment_result
.response
.declined_code
.unwrap_or(NO_ERROR_CODE.to_string());
let declined_message = item
.response
.body
.submit_single_payment_response
.submit_single_payment_result
.response
.declined_message
.unwrap_or(NO_ERROR_MESSAGE.to_string());
Ok(Self {
status: get_attempt_status(response_code, item.data.request.capture_method),
response: Err(ErrorResponse {
status_code: item.http_code,
code,
message: declined_message.to_owned(),
reason: Some(declined_message),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
pub fn get_setup_mandate_body(req: &types::SetupMandateRouterData) -> Result<Vec<u8>, Error> {
let card_holder_name = req.get_billing_full_name()?;
let auth_details = BamboraapacAuthType::try_from(&req.connector_auth_type)?;
let body = match &req.request.payment_method_data {
PaymentMethodData::Card(card) => {
format!(
r#"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:sipp="http://www.ippayments.com.au/interface/api/sipp">
<soapenv:Header/>
<soapenv:Body>
<sipp:TokeniseCreditCard>
<sipp:tokeniseCreditCardXML>
<![CDATA[
<TokeniseCreditCard>
<CardNumber>{}</CardNumber>
<ExpM>{}</ExpM>
<ExpY>{}</ExpY>
<CardHolderName>{}</CardHolderName>
<TokeniseAlgorithmID>2</TokeniseAlgorithmID>
<UserName>{}</UserName>
<Password>{}</Password>
</TokeniseCreditCard>
]]>
</sipp:tokeniseCreditCardXML>
</sipp:TokeniseCreditCard>
</soapenv:Body>
</soapenv:Envelope>
"#,
card.card_number.get_card_no(),
card.card_exp_month.peek(),
card.get_expiry_year_4_digit().peek(),
card_holder_name.peek(),
auth_details.username.peek(),
auth_details.password.peek(),
)
}
_ => {
return Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Bambora APAC"),
))?;
}
};
Ok(body.as_bytes().to_vec())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Envelope")]
#[serde(rename_all = "PascalCase")]
pub struct BamboraapacMandateResponse {
body: MandateBodyResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct MandateBodyResponse {
tokenise_credit_card_response: TokeniseCreditCardResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct TokeniseCreditCardResponse {
tokenise_credit_card_result: TokeniseCreditCardResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct TokeniseCreditCardResult {
tokenise_credit_card_response: MandateResponseBody,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct MandateResponseBody {
return_value: u8,
token: Option<String>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BamboraapacMandateResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
> for RouterData<F, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BamboraapacMandateResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_code = item
.response
.body
.tokenise_credit_card_response
.tokenise_credit_card_result
.tokenise_credit_card_response
.return_value;
let connector_mandate_id = item
.response
.body
.tokenise_credit_card_response
.tokenise_credit_card_result
.tokenise_credit_card_response
.token
.ok_or(errors::ConnectorError::MissingConnectorMandateID)?;
// transaction approved
if response_code == 0 {
Ok(Self {
status: enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(Some(MandateReference {
connector_mandate_id: Some(connector_mandate_id),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
// transaction failed
else {
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
status_code: item.http_code,
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: None,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
// capture body in soap format
pub fn get_capture_body(
req: &BamboraapacRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Vec<u8>, Error> {
let receipt = req.router_data.request.connector_transaction_id.to_owned();
let auth_details = BamboraapacAuthType::try_from(&req.router_data.connector_auth_type)?;
let body = format!(
r#"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Body>
<dts:SubmitSingleCapture>
<dts:trnXML>
<![CDATA[
<Capture>
<Receipt>{}</Receipt>
<Amount>{}</Amount>
<Security>
<UserName>{}</UserName>
<Password>{}</Password>
</Security>
</Capture>
]]>
</dts:trnXML>
</dts:SubmitSingleCapture>
</soapenv:Body>
</soapenv:Envelope>
"#,
receipt,
req.amount,
auth_details.username.peek(),
auth_details.password.peek(),
);
Ok(body.as_bytes().to_vec())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Envelope")]
#[serde(rename_all = "PascalCase")]
pub struct BamboraapacCaptureResponse {
body: CaptureBodyResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CaptureBodyResponse {
submit_single_capture_response: SubmitSingleCaptureResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSingleCaptureResponse {
submit_single_capture_result: SubmitSingleCaptureResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSingleCaptureResult {
response: CaptureResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CaptureResponse {
response_code: u8,
receipt: String,
declined_code: Option<String>,
declined_message: Option<String>,
}
impl TryFrom<PaymentsCaptureResponseRouterData<BamboraapacCaptureResponse>>
for types::PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<BamboraapacCaptureResponse>,
) -> Result<Self, Self::Error> {
let response_code = item
.response
.body
.submit_single_capture_response
.submit_single_capture_result
.response
.response_code;
let connector_transaction_id = item
.response
.body
.submit_single_capture_response
.submit_single_capture_result
.response
.receipt;
// storing receipt_id of authorize to metadata for future usage
let connector_metadata = Some(serde_json::json!(BamboraapacMeta {
authorize_id: item.data.request.connector_transaction_id.to_owned()
}));
// transaction approved
if response_code == 0 {
Ok(Self {
status: enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
connector_transaction_id.to_owned(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(connector_transaction_id),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
// transaction failed
else {
let code = item
.response
.body
.submit_single_capture_response
.submit_single_capture_result
.response
.declined_code
.unwrap_or(NO_ERROR_CODE.to_string());
let declined_message = item
.response
.body
.submit_single_capture_response
.submit_single_capture_result
.response
.declined_message
.unwrap_or(NO_ERROR_MESSAGE.to_string());
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
status_code: item.http_code,
code,
message: declined_message.to_owned(),
reason: Some(declined_message),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
// refund body in soap format
pub fn get_refund_body(
req: &BamboraapacRouterData<&types::RefundExecuteRouterData>,
) -> Result<Vec<u8>, Error> {
let receipt = req.router_data.request.connector_transaction_id.to_owned();
let auth_details = BamboraapacAuthType::try_from(&req.router_data.connector_auth_type)?;
let body = format!(
r#"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Header/>
<soapenv:Body>
<dts:SubmitSingleRefund>
<dts:trnXML>
<![CDATA[
<Refund>
<CustRef>{}</CustRef>
<Receipt>{}</Receipt>
<Amount>{}</Amount>
<Security>
<UserName>{}</UserName>
<Password>{}</Password>
</Security>
</Refund>
]]>
</dts:trnXML>
</dts:SubmitSingleRefund>
</soapenv:Body>
</soapenv:Envelope>
"#,
req.router_data.request.refund_id.to_owned(),
receipt,
req.amount,
auth_details.username.peek(),
auth_details.password.peek(),
);
Ok(body.as_bytes().to_vec())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Envelope")]
#[serde(rename_all = "PascalCase")]
pub struct BamboraapacRefundsResponse {
body: RefundBodyResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct RefundBodyResponse {
submit_single_refund_response: SubmitSingleRefundResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSingleRefundResponse {
submit_single_refund_result: SubmitSingleRefundResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSingleRefundResult {
response: RefundResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct RefundResponse {
response_code: u8,
receipt: String,
declined_code: Option<String>,
declined_message: Option<String>,
}
fn get_status(item: u8) -> enums::RefundStatus {
match item {
0 => enums::RefundStatus::Success,
1 => enums::RefundStatus::Failure,
_ => enums::RefundStatus::Pending,
}
}
impl<F> TryFrom<ResponseRouterData<F, BamboraapacRefundsResponse, RefundsData, RefundsResponseData>>
for RouterData<F, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BamboraapacRefundsResponse, RefundsData, RefundsResponseData>,
) -> Result<Self, Self::Error> {
let response_code = item
.response
.body
.submit_single_refund_response
.submit_single_refund_result
.response
.response_code;
let connector_refund_id = item
.response
.body
.submit_single_refund_response
.submit_single_refund_result
.response
.receipt;
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: connector_refund_id.to_owned(),
refund_status: get_status(response_code),
}),
..item.data
})
}
}
pub fn get_payment_sync_body(req: &types::PaymentsSyncRouterData) -> Result<Vec<u8>, Error> {
let auth_details = BamboraapacAuthType::try_from(&req.connector_auth_type)?;
let connector_transaction_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
let body = format!(
r#"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Header/>
<soapenv:Body>
<dts:QueryTransaction>
<dts:queryXML>
<![CDATA[
<QueryTransaction>
<Criteria>
<AccountNumber>{}</AccountNumber>
<TrnStartTimestamp>2024-06-23 00:00:00</TrnStartTimestamp>
<TrnEndTimestamp>2099-12-31 23:59:59</TrnEndTimestamp>
<Receipt>{}</Receipt>
</Criteria>
<Security>
<UserName>{}</UserName>
<Password>{}</Password>
</Security>
</QueryTransaction>
]]>
</dts:queryXML>
</dts:QueryTransaction>
</soapenv:Body>
</soapenv:Envelope>
"#,
auth_details.account_number.peek(),
connector_transaction_id,
auth_details.username.peek(),
auth_details.password.peek(),
);
Ok(body.as_bytes().to_vec())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Envelope")]
#[serde(rename_all = "PascalCase")]
pub struct BamboraapacSyncResponse {
body: SyncBodyResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SyncBodyResponse {
query_transaction_response: QueryTransactionResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct QueryTransactionResponse {
query_transaction_result: QueryTransactionResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct QueryTransactionResult {
query_response: QueryResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct QueryResponse {
response: SyncResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SyncResponse {
response_code: u8,
receipt: String,
declined_code: Option<String>,
declined_message: Option<String>,
}
impl TryFrom<PaymentsSyncResponseRouterData<BamboraapacSyncResponse>>
for types::PaymentsSyncRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<BamboraapacSyncResponse>,
) -> Result<Self, Self::Error> {
let response_code = item
.response
.body
.query_transaction_response
.query_transaction_result
.query_response
.response
.response_code;
let connector_transaction_id = item
.response
.body
.query_transaction_response
.query_transaction_result
.query_response
.response
.receipt;
// transaction approved
if response_code == 0 {
Ok(Self {
status: get_attempt_status(response_code, item.data.request.capture_method),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
connector_transaction_id.to_owned(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(connector_transaction_id),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
// transaction failed
else {
let code = item
.response
.body
.query_transaction_response
.query_transaction_result
.query_response
.response
.declined_code
.unwrap_or(NO_ERROR_CODE.to_string());
let declined_message = item
.response
.body
.query_transaction_response
.query_transaction_result
.query_response
.response
.declined_message
.unwrap_or(NO_ERROR_MESSAGE.to_string());
Ok(Self {
status: get_attempt_status(response_code, item.data.request.capture_method),
response: Err(ErrorResponse {
status_code: item.http_code,
code,
message: declined_message.to_owned(),
reason: Some(declined_message),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
pub fn get_refund_sync_body(req: &types::RefundSyncRouterData) -> Result<Vec<u8>, Error> {
let auth_details = BamboraapacAuthType::try_from(&req.connector_auth_type)?;
let body = format!(
r#"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Header/>
<soapenv:Body>
<dts:QueryTransaction>
<dts:queryXML>
<![CDATA[
<QueryTransaction>
<Criteria>
<AccountNumber>{}</AccountNumber>
<TrnStartTimestamp>2024-06-23 00:00:00</TrnStartTimestamp>
<TrnEndTimestamp>2099-12-31 23:59:59</TrnEndTimestamp>
<CustRef>{}</CustRef>
</Criteria>
<Security>
<UserName>{}</UserName>
<Password>{}</Password>
</Security>
</QueryTransaction>
]]>
</dts:queryXML>
</dts:QueryTransaction>
</soapenv:Body>
</soapenv:Envelope>
"#,
auth_details.account_number.peek(),
req.request.refund_id,
auth_details.username.peek(),
auth_details.password.peek(),
);
Ok(body.as_bytes().to_vec())
}
impl<F> TryFrom<ResponseRouterData<F, BamboraapacSyncResponse, RefundsData, RefundsResponseData>>
for RouterData<F, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BamboraapacSyncResponse, RefundsData, RefundsResponseData>,
) -> Result<Self, Self::Error> {
let response_code = item
.response
.body
.query_transaction_response
.query_transaction_result
.query_response
.response
.response_code;
let connector_refund_id = item
.response
.body
.query_transaction_response
.query_transaction_result
.query_response
.response
.receipt;
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: connector_refund_id.to_owned(),
refund_status: get_status(response_code),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct BamboraapacErrorResponse {
pub declined_code: Option<String>,
pub declined_message: Option<String>,
}
|
crates__hyperswitch_connectors__src__connectors__bankofamerica.rs
|
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{
PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, PaymentsVoidType,
RefundExecuteType, RefundSyncType, Response, SetupMandateType,
},
webhooks,
};
use masking::{ExposeInterface, Mask, Maskable, PeekInterface};
use ring::{digest, hmac};
use time::OffsetDateTime;
use transformers as bankofamerica;
use url::Url;
use crate::{
connectors::bankofamerica::transformers::BankOfAmericaRouterData,
constants::{self, headers},
types::ResponseRouterData,
utils::{self, convert_amount, PaymentMethodDataType, RefundsRequestData},
};
pub const V_C_MERCHANT_ID: &str = "v-c-merchant-id";
#[derive(Clone)]
pub struct Bankofamerica {
amount_convertor: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Bankofamerica {
pub fn new() -> &'static Self {
&Self {
amount_convertor: &StringMajorUnitForConnector,
}
}
}
impl api::Payment for Bankofamerica {}
impl api::PaymentSession for Bankofamerica {}
impl api::ConnectorAccessToken for Bankofamerica {}
impl api::MandateSetup for Bankofamerica {}
impl api::PaymentAuthorize for Bankofamerica {}
impl api::PaymentSync for Bankofamerica {}
impl api::PaymentCapture for Bankofamerica {}
impl api::PaymentVoid for Bankofamerica {}
impl api::Refund for Bankofamerica {}
impl api::RefundExecute for Bankofamerica {}
impl api::RefundSync for Bankofamerica {}
impl api::PaymentToken for Bankofamerica {}
impl Bankofamerica {
pub fn generate_digest(&self, payload: &[u8]) -> String {
let payload_digest = digest::digest(&digest::SHA256, payload);
consts::BASE64_ENGINE.encode(payload_digest)
}
pub fn generate_signature(
&self,
auth: bankofamerica::BankOfAmericaAuthType,
host: String,
resource: &str,
payload: &String,
date: OffsetDateTime,
http_method: Method,
) -> CustomResult<String, errors::ConnectorError> {
let bankofamerica::BankOfAmericaAuthType {
api_key,
merchant_account,
api_secret,
} = auth;
let is_post_method = matches!(http_method, Method::Post);
let digest_str = if is_post_method { "digest " } else { "" };
let headers = format!("host date (request-target) {digest_str}{V_C_MERCHANT_ID}");
let request_target = if is_post_method {
format!("(request-target): post {resource}\ndigest: SHA-256={payload}\n")
} else {
format!("(request-target): get {resource}\n")
};
let signature_string = format!(
"host: {host}\ndate: {date}\n{request_target}{V_C_MERCHANT_ID}: {}",
merchant_account.peek()
);
let key_value = consts::BASE64_ENGINE
.decode(api_secret.expose())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "connector_account_details.api_secret",
})?;
let key = hmac::Key::new(hmac::HMAC_SHA256, &key_value);
let signature_value =
consts::BASE64_ENGINE.encode(hmac::sign(&key, signature_string.as_bytes()).as_ref());
let signature_header = format!(
r#"keyid="{}", algorithm="HmacSHA256", headers="{headers}", signature="{signature_value}""#,
api_key.peek()
);
Ok(signature_header)
}
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Bankofamerica
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Bankofamerica
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let date = OffsetDateTime::now_utc();
let boa_req = self.get_request_body(req, connectors)?;
let http_method = self.get_http_method();
let auth = bankofamerica::BankOfAmericaAuthType::try_from(&req.connector_auth_type)?;
let merchant_account = auth.merchant_account.clone();
let base_url = connectors.bankofamerica.base_url.as_str();
let boa_host =
Url::parse(base_url).change_context(errors::ConnectorError::RequestEncodingFailed)?;
let host = boa_host
.host_str()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
let path: String = self
.get_url(req, connectors)?
.chars()
.skip(base_url.len() - 1)
.collect();
let sha256 = self.generate_digest(boa_req.get_inner_value().expose().as_bytes());
let signature = self.generate_signature(
auth,
host.to_string(),
path.as_str(),
&sha256,
date,
http_method,
)?;
let mut headers = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
headers::ACCEPT.to_string(),
"application/hal+json;charset=utf-8".to_string().into(),
),
(V_C_MERCHANT_ID.to_string(), merchant_account.into_masked()),
("Date".to_string(), date.to_string().into()),
("Host".to_string(), host.to_string().into()),
("Signature".to_string(), signature.into_masked()),
];
if matches!(http_method, Method::Post | Method::Put) {
headers.push((
"Digest".to_string(),
format!("SHA-256={sha256}").into_masked(),
));
}
Ok(headers)
}
}
impl ConnectorCommon for Bankofamerica {
fn id(&self) -> &'static str {
"bankofamerica"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json;charset=utf-8"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.bankofamerica.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaErrorResponse = res
.response
.parse_struct("BankOfAmerica ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_message = if res.status_code == 401 {
constants::CONNECTOR_UNAUTHORIZED_ERROR
} else {
hyperswitch_interfaces::consts::NO_ERROR_MESSAGE
};
match response {
transformers::BankOfAmericaErrorResponse::StandardError(response) => {
let (code, message, reason) = match response.error_information {
Some(ref error_info) => {
let detailed_error_info = error_info.details.as_ref().map(|details| {
details
.iter()
.map(|det| format!("{} : {}", det.field, det.reason))
.collect::<Vec<_>>()
.join(", ")
});
(
error_info.reason.clone(),
error_info.reason.clone(),
transformers::get_error_reason(
Some(error_info.message.clone()),
detailed_error_info,
None,
),
)
}
None => {
let detailed_error_info = response.details.map(|details| {
details
.iter()
.map(|det| format!("{} : {}", det.field, det.reason))
.collect::<Vec<_>>()
.join(", ")
});
(
response.reason.clone().map_or(
hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
|reason| reason.to_string(),
),
response
.reason
.map_or(error_message.to_string(), |reason| reason.to_string()),
transformers::get_error_reason(
response.message,
detailed_error_info,
None,
),
)
}
};
Ok(ErrorResponse {
status_code: res.status_code,
code,
message,
reason,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
transformers::BankOfAmericaErrorResponse::AuthenticationError(response) => {
Ok(ErrorResponse {
status_code: res.status_code,
code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: response.response.rmsg.clone(),
reason: Some(response.response.rmsg),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
}
}
impl ConnectorValidation for Bankofamerica {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::ApplePay,
PaymentMethodDataType::GooglePay,
]);
utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Bankofamerica {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Bankofamerica {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Bankofamerica
{
fn get_headers(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}pts/v2/payments/", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = bankofamerica::BankOfAmericaPaymentsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(SetupMandateType::get_headers(self, req, connectors)?)
.set_body(SetupMandateType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaSetupMandatesResponse = res
.response
.parse_struct("BankOfAmericaSetupMandatesResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaServerErrorResponse = res
.response
.parse_struct("BankOfAmericaServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
let attempt_status = match response.reason {
Some(reason) => match reason {
transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),
transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None,
},
None => None,
};
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for Bankofamerica
{
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}pts/v2/payments/",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = BankOfAmericaRouterData::try_from((amount, req))?;
let connector_req =
bankofamerica::BankOfAmericaPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaPaymentsResponse = res
.response
.parse_struct("Bankofamerica PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaServerErrorResponse = res
.response
.parse_struct("BankOfAmericaServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
let attempt_status = match response.reason {
Some(reason) => match reason {
transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),
transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None,
},
None => None,
};
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Bankofamerica {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}tss/v2/transactions/{connector_payment_id}",
self.base_url(connectors)
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaTransactionResponse = res
.response
.parse_struct("BankOfAmerica PaymentSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Bankofamerica {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}pts/v2/payments/{connector_payment_id}/captures",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = BankOfAmericaRouterData::try_from((amount, req))?;
let connector_req =
bankofamerica::BankOfAmericaCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
.set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaPaymentsResponse = res
.response
.parse_struct("BankOfAmerica PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaServerErrorResponse = res
.response
.parse_struct("BankOfAmericaServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Bankofamerica {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}pts/v2/payments/{connector_payment_id}/reversals",
self.base_url(connectors)
))
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let minor_amount =
req.request
.minor_amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "Amount",
})?;
let currency =
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "Currency",
})?;
let amount = convert_amount(self.amount_convertor, minor_amount, currency)?;
let connector_router_data = BankOfAmericaRouterData::try_from((amount, req))?;
let connector_req =
bankofamerica::BankOfAmericaVoidRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaPaymentsResponse = res
.response
.parse_struct("BankOfAmerica PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaServerErrorResponse = res
.response
.parse_struct("BankOfAmericaServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Bankofamerica {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}pts/v2/payments/{connector_payment_id}/refunds",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = BankOfAmericaRouterData::try_from((amount, req))?;
let connector_req =
bankofamerica::BankOfAmericaRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaRefundResponse = res
.response
.parse_struct("bankofamerica RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Bankofamerica {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}tss/v2/transactions/{refund_id}",
self.base_url(connectors)
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaRsyncResponse = res
.response
.parse_struct("bankofamerica RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Bankofamerica {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static BANKOFAMERICA_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Maestro,
common_enums::CardNetwork::Interac,
];
let mut bankofamerica_supported_payment_methods = SupportedPaymentMethods::new();
bankofamerica_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
bankofamerica_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
bankofamerica_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::SamsungPay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
bankofamerica_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
bankofamerica_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
bankofamerica_supported_payment_methods
});
static BANKOFAMERICA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Bank Of America",
description:
"It is the second-largest banking institution in the United States and the second-largest bank in the world by market capitalization ",
connector_type: enums::HyperswitchConnectorCategory::BankAcquirer,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static BANKOFAMERICA_SUPPORTED_WEBHOOK_FLOWS: [common_enums::EventClass; 0] = [];
impl ConnectorSpecifications for Bankofamerica {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&BANKOFAMERICA_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*BANKOFAMERICA_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&BANKOFAMERICA_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__bankofamerica__transformers.rs
|
use base64::Engine;
use common_enums::{enums, FutureUsage};
use common_types::payments::ApplePayPredecryptData;
use common_utils::{consts, ext_traits::OptionExt, pii, types::StringMajorUnit};
use hyperswitch_domain_models::{
payment_method_data::{
ApplePayWalletData, GooglePayWalletData, PaymentMethodData, SamsungPayWalletData,
WalletData,
},
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ErrorResponse, PaymentMethodToken, RouterData,
},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{api, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
constants,
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
ResponseRouterData,
},
unimplemented_payment_method,
utils::{
self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData,
PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RecurringMandateData,
RouterData as OtherRouterData,
},
};
pub struct BankOfAmericaAuthType {
pub(super) api_key: Secret<String>,
pub(super) merchant_account: Secret<String>,
pub(super) api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BankOfAmericaAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = auth_type
{
Ok(Self {
api_key: api_key.to_owned(),
merchant_account: key1.to_owned(),
api_secret: api_secret.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
pub struct BankOfAmericaRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(StringMajorUnit, T)> for BankOfAmericaRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (StringMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaPaymentsRequest {
processing_information: ProcessingInformation,
payment_information: PaymentInformation,
order_information: OrderInformationWithBill,
client_reference_information: ClientReferenceInformation,
#[serde(skip_serializing_if = "Option::is_none")]
consumer_authentication_information: Option<BankOfAmericaConsumerAuthInformation>,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_defined_information: Option<Vec<MerchantDefinedInformation>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingInformation {
action_list: Option<Vec<BankOfAmericaActionsList>>,
action_token_types: Option<Vec<BankOfAmericaActionsTokenType>>,
authorization_options: Option<BankOfAmericaAuthorizationOptions>,
commerce_indicator: String,
capture: Option<bool>,
capture_options: Option<CaptureOptions>,
payment_solution: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BankOfAmericaActionsList {
TokenCreate,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum BankOfAmericaActionsTokenType {
PaymentInstrument,
Customer,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaAuthorizationOptions {
initiator: Option<BankOfAmericaPaymentInitiator>,
merchant_initiated_transaction: Option<MerchantInitiatedTransaction>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaPaymentInitiator {
#[serde(rename = "type")]
initiator_type: Option<BankOfAmericaPaymentInitiatorTypes>,
credential_stored_on_file: Option<bool>,
stored_credential_used: Option<bool>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum BankOfAmericaPaymentInitiatorTypes {
Customer,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantInitiatedTransaction {
reason: Option<String>,
//Required for recurring mandates payment
original_authorized_amount: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantDefinedInformation {
key: u8,
value: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaConsumerAuthInformation {
ucaf_collection_indicator: Option<String>,
cavv: Option<String>,
ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
directory_server_transaction_id: Option<Secret<String>>,
specification_version: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureOptions {
capture_sequence_number: u32,
total_capture_count: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BankOfAmericaPaymentInstrument {
id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardPaymentInformation {
card: Card,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayPaymentInformation {
fluid_data: FluidData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayTokenizedCard {
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayTokenPaymentInformation {
fluid_data: FluidData,
tokenized_card: ApplePayTokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayPaymentInformation {
tokenized_card: TokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymentInformation {
Cards(Box<CardPaymentInformation>),
GooglePay(Box<GooglePayPaymentInformation>),
ApplePay(Box<ApplePayPaymentInformation>),
ApplePayToken(Box<ApplePayTokenPaymentInformation>),
MandatePayment(Box<MandatePaymentInformation>),
SamsungPay(Box<SamsungPayPaymentInformation>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MandatePaymentInformation {
payment_instrument: BankOfAmericaPaymentInstrument,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
number: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
security_code: Secret<String>,
#[serde(rename = "type")]
card_type: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCard {
number: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
cryptogram: Secret<String>,
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FluidData {
value: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
descriptor: Option<String>,
}
pub const FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY: &str = "FID=COMMON.SAMSUNG.INAPP.PAYMENT";
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderInformationWithBill {
amount_details: Amount,
bill_to: Option<BillTo>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
total_amount: StringMajorUnit,
currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BillTo {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address1: Option<Secret<String>>,
locality: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
administrative_area: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
postal_code: Option<Secret<String>>,
country: Option<enums::CountryAlpha2>,
email: pii::Email,
}
impl TryFrom<&SetupMandateRouterData> for BankOfAmericaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(card_data) => Self::try_from((item, card_data)),
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::ApplePay(apple_pay_data) => Self::try_from((item, apple_pay_data)),
WalletData::GooglePay(google_pay_data) => Self::try_from((item, google_pay_data)),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::AmazonPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("BankOfAmerica"),
))?,
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("BankOfAmerica"),
))?
}
}
}
}
impl<F, T>
TryFrom<ResponseRouterData<F, BankOfAmericaSetupMandatesResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BankOfAmericaSetupMandatesResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
BankOfAmericaSetupMandatesResponse::ClientReferenceInformation(info_response) => {
let mandate_reference =
info_response
.token_information
.clone()
.map(|token_info| MandateReference {
connector_mandate_id: token_info
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
let mut mandate_status =
map_boa_attempt_status((info_response.status.clone(), false));
if matches!(mandate_status, enums::AttemptStatus::Authorized) {
//In case of zero auth mandates we want to make the payment reach the terminal status so we are converting the authorized status to charged as well.
mandate_status = enums::AttemptStatus::Charged
}
let error_response =
get_error_response_if_failure((&info_response, mandate_status, item.http_code));
let connector_response = match item.data.payment_method {
common_enums::PaymentMethod::Card => info_response
.processor_information
.as_ref()
.and_then(|processor_information| {
info_response
.consumer_authentication_information
.as_ref()
.map(|consumer_auth_information| {
convert_to_additional_payment_method_connector_response(
processor_information,
consumer_auth_information,
)
})
})
.map(ConnectorResponseData::with_additional_payment_method_data),
common_enums::PaymentMethod::CardRedirect
| common_enums::PaymentMethod::PayLater
| common_enums::PaymentMethod::Wallet
| common_enums::PaymentMethod::BankRedirect
| common_enums::PaymentMethod::BankTransfer
| common_enums::PaymentMethod::Crypto
| common_enums::PaymentMethod::BankDebit
| common_enums::PaymentMethod::Reward
| common_enums::PaymentMethod::RealTimePayment
| common_enums::PaymentMethod::MobilePayment
| common_enums::PaymentMethod::Upi
| common_enums::PaymentMethod::Voucher
| common_enums::PaymentMethod::OpenBanking
| common_enums::PaymentMethod::GiftCard
| common_enums::PaymentMethod::NetworkToken => None,
};
Ok(Self {
status: mandate_status,
response: match error_response {
Some(error) => Err(error),
None => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
info_response.id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
info_response
.client_reference_information
.code
.clone()
.unwrap_or(info_response.id),
),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
},
connector_response,
..item.data
})
}
BankOfAmericaSetupMandatesResponse::ErrorInformation(error_response) => {
let response = Err(convert_to_error_response_from_error_info(
&error_response,
item.http_code,
));
Ok(Self {
response,
status: enums::AttemptStatus::Failure,
..item.data
})
}
}
}
}
// for bankofamerica each item in Billing is mandatory
// fn build_bill_to(
// address_details: &payments::Address,
// email: pii::Email,
// ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> {
// let address = address_details
// .address
// .as_ref()
// .ok_or_else(utils::missing_field_err("billing.address"))?;
// let country = address.get_country()?.to_owned();
// let first_name = address.get_first_name()?;
// let (administrative_area, postal_code) =
// if country == api_enums::CountryAlpha2::US || country == api_enums::CountryAlpha2::CA {
// let mut state = address.to_state_code()?.peek().clone();
// state.truncate(20);
// (
// Some(Secret::from(state)),
// Some(address.get_zip()?.to_owned()),
// )
// } else {
// let zip = address.zip.clone();
// let mut_state = address.state.clone().map(|state| state.expose());
// match mut_state {
// Some(mut state) => {
// state.truncate(20);
// (Some(Secret::from(state)), zip)
// }
// None => (None, zip),
// }
// };
// Ok(BillTo {
// first_name: first_name.clone(),
// last_name: address.get_last_name().unwrap_or(first_name).clone(),
// address1: address.get_line1()?.to_owned(),
// locality: Secret::new(address.get_city()?.to_owned()),
// administrative_area,
// postal_code,
// country,
// email,
// })
// }
fn build_bill_to(
address_details: Option<&hyperswitch_domain_models::address::Address>,
email: pii::Email,
) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> {
let default_address = BillTo {
first_name: None,
last_name: None,
address1: None,
locality: None,
administrative_area: None,
postal_code: None,
country: None,
email: email.clone(),
};
Ok(address_details
.and_then(|addr| {
addr.address.as_ref().map(|addr| {
let administrative_area = addr.to_state_code_as_optional().unwrap_or_else(|_| {
addr.state
.clone()
.map(|state| Secret::new(format!("{:.20}", state.expose())))
});
BillTo {
first_name: addr.first_name.clone(),
last_name: addr.last_name.clone(),
address1: addr.line1.clone(),
locality: addr.city.clone(),
administrative_area,
postal_code: addr.zip.clone(),
country: addr.country,
email,
}
})
})
.unwrap_or(default_address))
}
fn get_boa_card_type(card_network: common_enums::CardNetwork) -> Option<&'static str> {
match card_network {
common_enums::CardNetwork::Visa => Some("001"),
common_enums::CardNetwork::Mastercard => Some("002"),
common_enums::CardNetwork::AmericanExpress => Some("003"),
common_enums::CardNetwork::JCB => Some("007"),
common_enums::CardNetwork::DinersClub => Some("005"),
common_enums::CardNetwork::Discover => Some("004"),
common_enums::CardNetwork::CartesBancaires => Some("006"),
common_enums::CardNetwork::UnionPay => Some("062"),
//"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024"
common_enums::CardNetwork::Maestro => Some("042"),
common_enums::CardNetwork::Interac
| common_enums::CardNetwork::RuPay
| common_enums::CardNetwork::Star
| common_enums::CardNetwork::Accel
| common_enums::CardNetwork::Pulse
| common_enums::CardNetwork::Nyce => None,
}
}
#[derive(Debug, Serialize)]
pub enum PaymentSolution {
ApplePay,
GooglePay,
SamsungPay,
}
impl From<PaymentSolution> for String {
fn from(solution: PaymentSolution) -> Self {
let payment_solution = match solution {
PaymentSolution::ApplePay => "001",
PaymentSolution::GooglePay => "012",
PaymentSolution::SamsungPay => "008",
};
payment_solution.to_string()
}
}
#[derive(Debug, Serialize)]
pub enum TransactionType {
#[serde(rename = "1")]
ApplePay,
#[serde(rename = "1")]
SamsungPay,
}
impl
From<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Option<BillTo>,
)> for OrderInformationWithBill
{
fn from(
(item, bill_to): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Option<BillTo>,
),
) -> Self {
Self {
amount_details: Amount {
total_amount: item.amount.to_owned(),
currency: item.router_data.request.currency,
},
bill_to,
}
}
}
impl
TryFrom<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
)> for ProcessingInformation
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, solution, network): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
),
) -> Result<Self, Self::Error> {
let (action_list, action_token_types, authorization_options) =
if item.router_data.request.setup_future_usage == Some(FutureUsage::OffSession)
&& (item.router_data.request.customer_acceptance.is_some()
|| item
.router_data
.request
.setup_mandate_details
.clone()
.is_some_and(|mandate_details| {
mandate_details.customer_acceptance.is_some()
}))
{
get_boa_mandate_action_details()
} else if item.router_data.request.connector_mandate_id().is_some() {
let original_amount = item
.router_data
.get_recurring_mandate_payment_data()?
.get_original_payment_amount()?;
let original_currency = item
.router_data
.get_recurring_mandate_payment_data()?
.get_original_payment_currency()?;
(
None,
None,
Some(BankOfAmericaAuthorizationOptions {
initiator: None,
merchant_initiated_transaction: Some(MerchantInitiatedTransaction {
reason: None,
original_authorized_amount: Some(utils::get_amount_as_string(
&api::CurrencyUnit::Base,
original_amount,
original_currency,
)?),
}),
}),
)
} else {
(None, None, None)
};
let commerce_indicator = get_commerce_indicator(network);
Ok(Self {
capture: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
)),
payment_solution: solution.map(String::from),
action_list,
action_token_types,
authorization_options,
capture_options: None,
commerce_indicator,
})
}
}
impl From<&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>> for ClientReferenceInformation {
fn from(item: &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>) -> Self {
Self {
code: Some(item.router_data.connector_request_reference_id.clone()),
}
}
}
impl From<&SetupMandateRouterData> for ClientReferenceInformation {
fn from(item: &SetupMandateRouterData) -> Self {
Self {
code: Some(item.connector_request_reference_id.clone()),
}
}
}
fn convert_metadata_to_merchant_defined_info(metadata: Value) -> Vec<MerchantDefinedInformation> {
let hashmap: std::collections::BTreeMap<String, Value> =
serde_json::from_str(&metadata.to_string()).unwrap_or(std::collections::BTreeMap::new());
let mut vector = Vec::new();
let mut iter = 1;
for (key, value) in hashmap {
vector.push(MerchantDefinedInformation {
key: iter,
value: format!("{key}={value}"),
});
iter += 1;
}
vector
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientReferenceInformation {
code: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientProcessorInformation {
avs: Option<Avs>,
card_verification: Option<CardVerification>,
processor: Option<ProcessorResponse>,
network_transaction_id: Option<Secret<String>>,
approval_code: Option<String>,
merchant_advice: Option<MerchantAdvice>,
response_code: Option<String>,
ach_verification: Option<AchVerification>,
system_trace_audit_number: Option<String>,
event_status: Option<String>,
retrieval_reference_number: Option<String>,
consumer_authentication_response: Option<ConsumerAuthenticationResponse>,
response_details: Option<String>,
transaction_id: Option<Secret<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantAdvice {
code: Option<String>,
code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConsumerAuthenticationResponse {
code: Option<String>,
code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AchVerification {
result_code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessorResponse {
name: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardVerification {
result_code: Option<String>,
result_code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientRiskInformation {
rules: Option<Vec<ClientRiskInformationRules>>,
profile: Option<Profile>,
score: Option<Score>,
info_codes: Option<InfoCodes>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InfoCodes {
address: Option<Vec<String>>,
identity_change: Option<Vec<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Score {
factor_codes: Option<Vec<String>>,
result: Option<RiskResult>,
model_used: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum RiskResult {
StringVariant(String),
IntVariant(u64),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Profile {
early_decision: Option<String>,
name: Option<String>,
decision: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ClientRiskInformationRules {
name: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Avs {
code: Option<String>,
code_raw: Option<String>,
}
impl
TryFrom<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
hyperswitch_domain_models::payment_method_data::Card,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, ccard): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
hyperswitch_domain_models::payment_method_data::Card,
),
) -> Result<Self, Self::Error> {
if item.router_data.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Card 3DS".to_string(),
connector: "BankOfAmerica",
})?
};
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?;
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
let payment_information = PaymentInformation::try_from(&ccard)?;
let processing_information = ProcessingInformation::try_from((item, None, None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information: None,
})
}
}
impl
TryFrom<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
ApplePayWalletData,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, apple_pay_data, apple_pay_wallet_data): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
ApplePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?;
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
let processing_information = ProcessingInformation::try_from((
item,
Some(PaymentSolution::ApplePay),
Some(apple_pay_wallet_data.payment_method.network.clone()),
))?;
let client_reference_information = ClientReferenceInformation::from(item);
let payment_information = PaymentInformation::try_from(&apple_pay_data)?;
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
let ucaf_collection_indicator = match apple_pay_wallet_data
.payment_method
.network
.to_lowercase()
.as_str()
{
"mastercard" => Some("2".to_string()),
_ => None,
};
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information: Some(BankOfAmericaConsumerAuthInformation {
ucaf_collection_indicator,
cavv: None,
ucaf_authentication_data: None,
xid: None,
directory_server_transaction_id: None,
specification_version: None,
}),
})
}
}
impl
TryFrom<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
GooglePayWalletData,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, google_pay_data): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
GooglePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?;
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
let payment_information = PaymentInformation::try_from(&google_pay_data)?;
let processing_information =
ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay), None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information: None,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SamsungPayTokenizedCard {
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SamsungPayPaymentInformation {
fluid_data: FluidData,
tokenized_card: SamsungPayTokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SamsungPayFluidDataValue {
public_key_hash: Secret<String>,
version: String,
data: Secret<String>,
}
impl TryFrom<&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>>
for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.connector_mandate_id() {
Some(connector_mandate_id) => Self::try_from((item, connector_mandate_id)),
None => {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)),
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::ApplePay(apple_pay_data) => {
match item.router_data.payment_method_token.clone() {
Some(payment_method_token) => match payment_method_token {
PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
Self::try_from((item, decrypt_data, apple_pay_data))
}
PaymentMethodToken::Token(_) => {
Err(unimplemented_payment_method!(
"Apple Pay",
"Manual",
"Bank Of America"
))?
}
PaymentMethodToken::PazeDecrypt(_) => Err(
unimplemented_payment_method!("Paze", "Bank Of America"),
)?,
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!(
"Google Pay",
"Bank Of America"
))?
}
},
None => {
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(
item.router_data.get_optional_billing(),
email,
)?;
let order_information: OrderInformationWithBill =
OrderInformationWithBill::from((item, Some(bill_to)));
let processing_information =
ProcessingInformation::try_from((
item,
Some(PaymentSolution::ApplePay),
Some(apple_pay_data.payment_method.network.clone()),
))?;
let client_reference_information =
ClientReferenceInformation::from(item);
let payment_information =
PaymentInformation::try_from(&apple_pay_data)?;
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
let ucaf_collection_indicator = match apple_pay_data
.payment_method
.network
.to_lowercase()
.as_str()
{
"mastercard" => Some("2".to_string()),
_ => None,
};
Ok(Self {
processing_information,
payment_information,
order_information,
merchant_defined_information,
client_reference_information,
consumer_authentication_information: Some(
BankOfAmericaConsumerAuthInformation {
ucaf_collection_indicator,
cavv: None,
ucaf_authentication_data: None,
xid: None,
directory_server_transaction_id: None,
specification_version: None,
},
),
})
}
}
}
WalletData::GooglePay(google_pay_data) => {
Self::try_from((item, google_pay_data))
}
WalletData::SamsungPay(samsung_pay_data) => {
Self::try_from((item, samsung_pay_data))
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::AmazonPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"Bank of America",
),
)
.into()),
},
// If connector_mandate_id is present MandatePayment will be the PMD, the case will be handled in the first `if` clause.
// This is a fallback implementation in the event of catastrophe.
PaymentMethodData::MandatePayment => {
let connector_mandate_id =
item.router_data.request.connector_mandate_id().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
},
)?;
Self::try_from((item, connector_mandate_id))
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"Bank of America",
),
)
.into())
}
}
}
}
}
}
fn get_samsung_pay_fluid_data_value(
samsung_pay_token_data: &hyperswitch_domain_models::payment_method_data::SamsungPayTokenData,
) -> Result<SamsungPayFluidDataValue, error_stack::Report<errors::ConnectorError>> {
let samsung_pay_header =
josekit::jwt::decode_header(samsung_pay_token_data.data.clone().peek())
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to decode samsung pay header")?;
let samsung_pay_kid_optional = samsung_pay_header.claim("kid").and_then(|kid| kid.as_str());
let samsung_pay_fluid_data_value = SamsungPayFluidDataValue {
public_key_hash: Secret::new(
samsung_pay_kid_optional
.get_required_value("samsung pay public_key_hash")
.change_context(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
),
version: samsung_pay_token_data.version.clone(),
data: Secret::new(consts::BASE64_ENGINE.encode(samsung_pay_token_data.data.peek())),
};
Ok(samsung_pay_fluid_data_value)
}
use error_stack::ResultExt;
impl
TryFrom<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Box<SamsungPayWalletData>,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, samsung_pay_data): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Box<SamsungPayWalletData>,
),
) -> Result<Self, Self::Error> {
let email = item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?;
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
let samsung_pay_fluid_data_value =
get_samsung_pay_fluid_data_value(&samsung_pay_data.payment_credential.token_data)?;
let samsung_pay_fluid_data_str = serde_json::to_string(&samsung_pay_fluid_data_value)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to serialize samsung pay fluid data")?;
let payment_information =
PaymentInformation::SamsungPay(Box::new(SamsungPayPaymentInformation {
fluid_data: FluidData {
value: Secret::new(consts::BASE64_ENGINE.encode(samsung_pay_fluid_data_str)),
descriptor: Some(
consts::BASE64_ENGINE.encode(FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY),
),
},
tokenized_card: SamsungPayTokenizedCard {
transaction_type: TransactionType::SamsungPay,
},
}));
let processing_information = ProcessingInformation::try_from((
item,
Some(PaymentSolution::SamsungPay),
Some(samsung_pay_data.payment_credential.card_brand.to_string()),
))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
consumer_authentication_information: None,
merchant_defined_information,
})
}
}
impl
TryFrom<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
String,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, connector_mandate_id): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
String,
),
) -> Result<Self, Self::Error> {
let processing_information = ProcessingInformation::try_from((item, None, None))?;
let payment_instrument = BankOfAmericaPaymentInstrument {
id: connector_mandate_id.into(),
};
let bill_to =
item.router_data.request.get_email().ok().and_then(|email| {
build_bill_to(item.router_data.get_optional_billing(), email).ok()
});
let order_information = OrderInformationWithBill::from((item, bill_to));
let payment_information =
PaymentInformation::MandatePayment(Box::new(MandatePaymentInformation {
payment_instrument,
}));
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information: None,
})
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BankofamericaPaymentStatus {
Authorized,
Succeeded,
Failed,
Voided,
Reversed,
Pending,
Declined,
Rejected,
Challenge,
AuthorizedPendingReview,
AuthorizedRiskDeclined,
Transmitted,
InvalidRequest,
ServerError,
PendingAuthentication,
PendingReview,
Accepted,
Cancelled,
//PartialAuthorized, not being consumed yet.
}
fn map_boa_attempt_status(
(status, auto_capture): (BankofamericaPaymentStatus, bool),
) -> enums::AttemptStatus {
match status {
BankofamericaPaymentStatus::Authorized
| BankofamericaPaymentStatus::AuthorizedPendingReview => {
if auto_capture {
// Because BankOfAmerica will return Payment Status as Authorized even in AutoCapture Payment
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
BankofamericaPaymentStatus::Pending => {
if auto_capture {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Pending
}
}
BankofamericaPaymentStatus::Succeeded | BankofamericaPaymentStatus::Transmitted => {
enums::AttemptStatus::Charged
}
BankofamericaPaymentStatus::Voided
| BankofamericaPaymentStatus::Reversed
| BankofamericaPaymentStatus::Cancelled => enums::AttemptStatus::Voided,
BankofamericaPaymentStatus::Failed
| BankofamericaPaymentStatus::Declined
| BankofamericaPaymentStatus::AuthorizedRiskDeclined
| BankofamericaPaymentStatus::InvalidRequest
| BankofamericaPaymentStatus::Rejected
| BankofamericaPaymentStatus::ServerError => enums::AttemptStatus::Failure,
BankofamericaPaymentStatus::PendingAuthentication => {
enums::AttemptStatus::AuthenticationPending
}
BankofamericaPaymentStatus::PendingReview
| BankofamericaPaymentStatus::Challenge
| BankofamericaPaymentStatus::Accepted => enums::AttemptStatus::Pending,
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BankOfAmericaPaymentsResponse {
ClientReferenceInformation(Box<BankOfAmericaClientReferenceResponse>),
ErrorInformation(Box<BankOfAmericaErrorInformationResponse>),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BankOfAmericaSetupMandatesResponse {
ClientReferenceInformation(Box<BankOfAmericaClientReferenceResponse>),
ErrorInformation(Box<BankOfAmericaErrorInformationResponse>),
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaClientReferenceResponse {
id: String,
status: BankofamericaPaymentStatus,
client_reference_information: ClientReferenceInformation,
processor_information: Option<ClientProcessorInformation>,
processing_information: Option<ProcessingInformationResponse>,
payment_information: Option<PaymentInformationResponse>,
payment_insights_information: Option<PaymentInsightsInformation>,
risk_information: Option<ClientRiskInformation>,
token_information: Option<BankOfAmericaTokenInformation>,
error_information: Option<BankOfAmericaErrorInformation>,
issuer_information: Option<IssuerInformation>,
sender_information: Option<SenderInformation>,
payment_account_information: Option<PaymentAccountInformation>,
reconciliation_id: Option<String>,
consumer_authentication_information: Option<ConsumerAuthenticationInformation>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConsumerAuthenticationInformation {
eci_raw: Option<String>,
eci: Option<String>,
acs_transaction_id: Option<String>,
cavv: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SenderInformation {
payment_information: Option<PaymentInformationResponse>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInsightsInformation {
response_insights: Option<ResponseInsights>,
rule_results: Option<RuleResults>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResponseInsights {
category_code: Option<String>,
category: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RuleResults {
id: Option<String>,
decision: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInformationResponse {
tokenized_card: Option<CardResponseObject>,
customer: Option<CustomerResponseObject>,
card: Option<CardResponseObject>,
scheme: Option<String>,
bin: Option<String>,
account_type: Option<String>,
issuer: Option<String>,
bin_country: Option<enums::CountryAlpha2>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomerResponseObject {
customer_id: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentAccountInformation {
card: Option<PaymentAccountCardInformation>,
features: Option<PaymentAccountFeatureInformation>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentAccountFeatureInformation {
health_card: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentAccountCardInformation {
#[serde(rename = "type")]
card_type: Option<String>,
hashed_number: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingInformationResponse {
payment_solution: Option<String>,
commerce_indicator: Option<String>,
commerce_indicator_label: Option<String>,
authorization_options: Option<AuthorizationOptions>,
ecommerce_indicator: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizationOptions {
auth_type: Option<String>,
initiator: Option<Initiator>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Initiator {
merchant_initiated_transaction: Option<MerchantInitiatedTransactionResponse>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantInitiatedTransactionResponse {
agreement_id: Option<String>,
previous_transaction_id: Option<String>,
original_authorized_amount: Option<StringMajorUnit>,
reason: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaTokenInformation {
payment_instrument: Option<BankOfAmericaPaymentInstrument>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IssuerInformation {
country: Option<enums::CountryAlpha2>,
discretionary_data: Option<String>,
country_specific_discretionary_data: Option<String>,
response_code: Option<String>,
pin_request_indicator: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardResponseObject {
suffix: Option<String>,
prefix: Option<String>,
expiration_month: Option<Secret<String>>,
expiration_year: Option<Secret<String>>,
#[serde(rename = "type")]
card_type: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaErrorInformationResponse {
id: String,
error_information: BankOfAmericaErrorInformation,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct BankOfAmericaErrorInformation {
reason: Option<String>,
message: Option<String>,
details: Option<Vec<Details>>,
}
fn map_error_response<F, T>(
error_response: &BankOfAmericaErrorInformationResponse,
item: ResponseRouterData<F, BankOfAmericaPaymentsResponse, T, PaymentsResponseData>,
transaction_status: Option<enums::AttemptStatus>,
) -> RouterData<F, T, PaymentsResponseData> {
let detailed_error_info = error_response
.error_information
.details
.as_ref()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message.clone(),
detailed_error_info,
None,
);
let response = Err(ErrorResponse {
code: error_response
.error_information
.reason
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_response
.error_information
.reason
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
match transaction_status {
Some(status) => RouterData {
response,
status,
..item.data
},
None => RouterData {
response,
..item.data
},
}
}
fn get_error_response_if_failure(
(info_response, status, http_code): (
&BankOfAmericaClientReferenceResponse,
enums::AttemptStatus,
u16,
),
) -> Option<ErrorResponse> {
if utils::is_payment_failure(status) {
Some(get_error_response(
&info_response.error_information,
&info_response.processor_information,
&info_response.risk_information,
Some(status),
http_code,
info_response.id.clone(),
))
} else {
None
}
}
fn get_payment_response(
(info_response, status, http_code): (
&BankOfAmericaClientReferenceResponse,
enums::AttemptStatus,
u16,
),
) -> Result<PaymentsResponseData, Box<ErrorResponse>> {
let error_response = get_error_response_if_failure((info_response, status, http_code));
match error_response {
Some(error) => Err(Box::new(error)),
None => {
let mandate_reference =
info_response
.token_information
.clone()
.map(|token_info| MandateReference {
connector_mandate_id: token_info
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(info_response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
info_response
.client_reference_information
.code
.clone()
.unwrap_or(info_response.id.clone()),
),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
}
}
}
impl TryFrom<PaymentsResponseRouterData<BankOfAmericaPaymentsResponse>>
for PaymentsAuthorizeRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<BankOfAmericaPaymentsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => {
let status = map_boa_attempt_status((
info_response.status.clone(),
item.data.request.is_auto_capture()?,
));
let response = get_payment_response((&info_response, status, item.http_code))
.map_err(|err| *err);
let connector_response = match item.data.payment_method {
common_enums::PaymentMethod::Card => info_response
.processor_information
.as_ref()
.and_then(|processor_information| {
info_response
.consumer_authentication_information
.as_ref()
.map(|consumer_auth_information| {
convert_to_additional_payment_method_connector_response(
processor_information,
consumer_auth_information,
)
})
})
.map(ConnectorResponseData::with_additional_payment_method_data),
common_enums::PaymentMethod::CardRedirect
| common_enums::PaymentMethod::PayLater
| common_enums::PaymentMethod::Wallet
| common_enums::PaymentMethod::BankRedirect
| common_enums::PaymentMethod::BankTransfer
| common_enums::PaymentMethod::Crypto
| common_enums::PaymentMethod::BankDebit
| common_enums::PaymentMethod::Reward
| common_enums::PaymentMethod::RealTimePayment
| common_enums::PaymentMethod::MobilePayment
| common_enums::PaymentMethod::Upi
| common_enums::PaymentMethod::Voucher
| common_enums::PaymentMethod::OpenBanking
| common_enums::PaymentMethod::GiftCard
| common_enums::PaymentMethod::NetworkToken => None,
};
Ok(Self {
status,
response,
connector_response,
..item.data
})
}
BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => {
Ok(map_error_response(
&error_response.clone(),
item,
Some(enums::AttemptStatus::Failure),
))
}
}
}
}
fn convert_to_additional_payment_method_connector_response(
processor_information: &ClientProcessorInformation,
consumer_authentication_information: &ConsumerAuthenticationInformation,
) -> AdditionalPaymentMethodConnectorResponse {
let payment_checks = Some(serde_json::json!({
"avs_response": processor_information.avs,
"card_verification": processor_information.card_verification,
"approval_code": processor_information.approval_code,
"consumer_authentication_response": processor_information.consumer_authentication_response,
"cavv": consumer_authentication_information.cavv,
"eci": consumer_authentication_information.eci,
"eci_raw": consumer_authentication_information.eci_raw,
}));
let authentication_data = Some(serde_json::json!({
"retrieval_reference_number": processor_information.retrieval_reference_number,
"acs_transaction_id": consumer_authentication_information.acs_transaction_id,
"system_trace_audit_number": processor_information.system_trace_audit_number,
}));
AdditionalPaymentMethodConnectorResponse::Card {
authentication_data,
payment_checks,
card_network: None,
domestic_network: None,
auth_code: None,
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<BankOfAmericaPaymentsResponse>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<BankOfAmericaPaymentsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => {
let status = map_boa_attempt_status((info_response.status.clone(), true));
let response = get_payment_response((&info_response, status, item.http_code))
.map_err(|err| *err);
Ok(Self {
status,
response,
..item.data
})
}
BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => {
Ok(map_error_response(&error_response.clone(), item, None))
}
}
}
}
impl TryFrom<PaymentsCancelResponseRouterData<BankOfAmericaPaymentsResponse>>
for PaymentsCancelRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<BankOfAmericaPaymentsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => {
let status = map_boa_attempt_status((info_response.status.clone(), false));
let response = get_payment_response((&info_response, status, item.http_code))
.map_err(|err| *err);
Ok(Self {
status,
response,
..item.data
})
}
BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => {
Ok(map_error_response(&error_response.clone(), item, None))
}
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaTransactionResponse {
id: String,
application_information: ApplicationInformation,
client_reference_information: Option<ClientReferenceInformation>,
processor_information: Option<ClientProcessorInformation>,
processing_information: Option<ProcessingInformationResponse>,
payment_information: Option<PaymentInformationResponse>,
payment_insights_information: Option<PaymentInsightsInformation>,
error_information: Option<BankOfAmericaErrorInformation>,
fraud_marking_information: Option<FraudMarkingInformation>,
risk_information: Option<ClientRiskInformation>,
token_information: Option<BankOfAmericaTokenInformation>,
reconciliation_id: Option<String>,
consumer_authentication_information: Option<ConsumerAuthenticationInformation>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FraudMarkingInformation {
reason: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplicationInformation {
status: Option<BankofamericaPaymentStatus>,
}
impl TryFrom<PaymentsSyncResponseRouterData<BankOfAmericaTransactionResponse>>
for PaymentsSyncRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<BankOfAmericaTransactionResponse>,
) -> Result<Self, Self::Error> {
match item.response.application_information.status {
Some(app_status) => {
let status =
map_boa_attempt_status((app_status, item.data.request.is_auto_capture()?));
let connector_response = match item.data.payment_method {
common_enums::PaymentMethod::Card => item
.response
.processor_information
.as_ref()
.and_then(|processor_information| {
item.response
.consumer_authentication_information
.as_ref()
.map(|consumer_auth_information| {
convert_to_additional_payment_method_connector_response(
processor_information,
consumer_auth_information,
)
})
})
.map(ConnectorResponseData::with_additional_payment_method_data),
common_enums::PaymentMethod::CardRedirect
| common_enums::PaymentMethod::PayLater
| common_enums::PaymentMethod::Wallet
| common_enums::PaymentMethod::BankRedirect
| common_enums::PaymentMethod::BankTransfer
| common_enums::PaymentMethod::Crypto
| common_enums::PaymentMethod::BankDebit
| common_enums::PaymentMethod::Reward
| common_enums::PaymentMethod::RealTimePayment
| common_enums::PaymentMethod::MobilePayment
| common_enums::PaymentMethod::Upi
| common_enums::PaymentMethod::Voucher
| common_enums::PaymentMethod::OpenBanking
| common_enums::PaymentMethod::GiftCard
| common_enums::PaymentMethod::NetworkToken => None,
};
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
Ok(Self {
response: Err(get_error_response(
&item.response.error_information,
&item.response.processor_information,
&risk_info,
Some(status),
item.http_code,
item.response.id.clone(),
)),
status: enums::AttemptStatus::Failure,
connector_response,
..item.data
})
} else {
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
.response
.client_reference_information
.map(|cref| cref.code)
.unwrap_or(Some(item.response.id)),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
connector_response,
..item.data
})
}
}
None => Ok(Self {
status: item.data.status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
}),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderInformation {
amount_details: Amount,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaCaptureRequest {
order_information: OrderInformation,
client_reference_information: ClientReferenceInformation,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_defined_information: Option<Vec<MerchantDefinedInformation>>,
}
impl TryFrom<&BankOfAmericaRouterData<&PaymentsCaptureRouterData>> for BankOfAmericaCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: &BankOfAmericaRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let merchant_defined_information = value
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
order_information: OrderInformation {
amount_details: Amount {
total_amount: value.amount.to_owned(),
currency: value.router_data.request.currency,
},
},
client_reference_information: ClientReferenceInformation {
code: Some(value.router_data.connector_request_reference_id.clone()),
},
merchant_defined_information,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaVoidRequest {
client_reference_information: ClientReferenceInformation,
reversal_information: ReversalInformation,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_defined_information: Option<Vec<MerchantDefinedInformation>>,
// The connector documentation does not mention the merchantDefinedInformation field for Void requests. But this has been still added because it works!
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReversalInformation {
amount_details: Amount,
reason: String,
}
impl TryFrom<&BankOfAmericaRouterData<&PaymentsCancelRouterData>> for BankOfAmericaVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: &BankOfAmericaRouterData<&PaymentsCancelRouterData>,
) -> Result<Self, Self::Error> {
let merchant_defined_information = value
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
client_reference_information: ClientReferenceInformation {
code: Some(value.router_data.connector_request_reference_id.clone()),
},
reversal_information: ReversalInformation {
amount_details: Amount {
total_amount: value.amount.to_owned(),
currency: value.router_data.request.currency.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "Currency",
},
)?,
},
reason: value
.router_data
.request
.cancellation_reason
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "Cancellation Reason",
})?,
},
merchant_defined_information,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaRefundRequest {
order_information: OrderInformation,
client_reference_information: ClientReferenceInformation,
}
impl<F> TryFrom<&BankOfAmericaRouterData<&RefundsRouterData<F>>> for BankOfAmericaRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BankOfAmericaRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
order_information: OrderInformation {
amount_details: Amount {
total_amount: item.amount.clone(),
currency: item.router_data.request.currency,
},
},
client_reference_information: ClientReferenceInformation {
code: Some(item.router_data.request.refund_id.clone()),
},
})
}
}
impl From<BankOfAmericaRefundResponse> for enums::RefundStatus {
fn from(item: BankOfAmericaRefundResponse) -> Self {
let error_reason = item
.error_information
.and_then(|error_info| error_info.reason);
match item.status {
BankofamericaRefundStatus::Succeeded | BankofamericaRefundStatus::Transmitted => {
Self::Success
}
BankofamericaRefundStatus::Cancelled
| BankofamericaRefundStatus::Failed
| BankofamericaRefundStatus::Voided => Self::Failure,
BankofamericaRefundStatus::Pending => Self::Pending,
BankofamericaRefundStatus::TwoZeroOne => {
if error_reason == Some("PROCESSOR_DECLINED".to_string()) {
Self::Failure
} else {
Self::Pending
}
}
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaRefundResponse {
id: String,
status: BankofamericaRefundStatus,
error_information: Option<BankOfAmericaErrorInformation>,
}
impl TryFrom<RefundsResponseRouterData<Execute, BankOfAmericaRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, BankOfAmericaRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.clone());
let response = if utils::is_refund_failure(refund_status) {
Err(get_error_response(
&item.response.error_information,
&None,
&None,
None,
item.http_code,
item.response.id,
))
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BankofamericaRefundStatus {
Succeeded,
Transmitted,
Failed,
Pending,
Voided,
Cancelled,
#[serde(rename = "201")]
TwoZeroOne,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RsyncApplicationInformation {
status: Option<BankofamericaRefundStatus>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaRsyncResponse {
id: String,
application_information: Option<RsyncApplicationInformation>,
error_information: Option<BankOfAmericaErrorInformation>,
}
impl TryFrom<RefundsResponseRouterData<RSync, BankOfAmericaRsyncResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, BankOfAmericaRsyncResponse>,
) -> Result<Self, Self::Error> {
let response = match item
.response
.application_information
.and_then(|application_information| application_information.status)
{
Some(status) => {
let error_reason = item
.response
.error_information
.clone()
.and_then(|error_info| error_info.reason);
let refund_status = match status {
BankofamericaRefundStatus::Succeeded
| BankofamericaRefundStatus::Transmitted => enums::RefundStatus::Success,
BankofamericaRefundStatus::Cancelled
| BankofamericaRefundStatus::Failed
| BankofamericaRefundStatus::Voided => enums::RefundStatus::Failure,
BankofamericaRefundStatus::Pending => enums::RefundStatus::Pending,
BankofamericaRefundStatus::TwoZeroOne => {
if error_reason == Some("PROCESSOR_DECLINED".to_string()) {
enums::RefundStatus::Failure
} else {
enums::RefundStatus::Pending
}
}
};
if utils::is_refund_failure(refund_status) {
if status == BankofamericaRefundStatus::Voided {
Err(get_error_response(
&Some(BankOfAmericaErrorInformation {
message: Some(constants::REFUND_VOIDED.to_string()),
reason: Some(constants::REFUND_VOIDED.to_string()),
details: None,
}),
&None,
&None,
None,
item.http_code,
item.response.id.clone(),
))
} else {
Err(get_error_response(
&item.response.error_information,
&None,
&None,
None,
item.http_code,
item.response.id.clone(),
))
}
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
})
}
}
None => Ok(RefundsResponseData {
connector_refund_id: item.response.id.clone(),
refund_status: match item.data.response {
Ok(response) => response.refund_status,
Err(_) => common_enums::RefundStatus::Pending,
},
}),
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaStandardErrorResponse {
pub error_information: Option<ErrorInformation>,
pub status: Option<String>,
pub message: Option<String>,
pub reason: Option<String>,
pub details: Option<Vec<Details>>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaServerErrorResponse {
pub status: Option<String>,
pub message: Option<String>,
pub reason: Option<Reason>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Reason {
SystemError,
ServerTimeout,
ServiceTimeout,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct BankOfAmericaAuthenticationErrorResponse {
pub response: AuthenticationErrorInformation,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BankOfAmericaErrorResponse {
AuthenticationError(BankOfAmericaAuthenticationErrorResponse),
StandardError(BankOfAmericaStandardErrorResponse),
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Details {
pub field: String,
pub reason: String,
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct ErrorInformation {
pub message: String,
pub reason: String,
pub details: Option<Vec<Details>>,
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct AuthenticationErrorInformation {
pub rmsg: String,
}
fn get_error_response(
error_data: &Option<BankOfAmericaErrorInformation>,
processor_information: &Option<ClientProcessorInformation>,
risk_information: &Option<ClientRiskInformation>,
attempt_status: Option<enums::AttemptStatus>,
status_code: u16,
transaction_id: String,
) -> ErrorResponse {
let avs_message = risk_information
.clone()
.map(|client_risk_information| {
client_risk_information.rules.map(|rules| {
rules
.iter()
.map(|risk_info| {
risk_info.name.clone().map_or("".to_string(), |name| {
format!(" , {}", name.clone().expose())
})
})
.collect::<Vec<String>>()
.join("")
})
})
.unwrap_or(Some("".to_string()));
let detailed_error_info = error_data.to_owned().and_then(|error_info| {
error_info.details.map(|error_details| {
error_details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
})
});
let network_decline_code = processor_information
.as_ref()
.and_then(|info| info.response_code.clone());
let network_advice_code = processor_information.as_ref().and_then(|info| {
info.merchant_advice
.as_ref()
.and_then(|merchant_advice| merchant_advice.code_raw.clone())
});
let reason = get_error_reason(
error_data
.clone()
.and_then(|error_details| error_details.message),
detailed_error_info,
avs_message,
);
let error_message = error_data
.clone()
.and_then(|error_details| error_details.reason);
ErrorResponse {
code: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code,
attempt_status,
connector_transaction_id: Some(transaction_id.clone()),
connector_response_reference_id: None,
network_advice_code,
network_decline_code,
network_error_message: None,
connector_metadata: None,
}
}
impl
TryFrom<(
&SetupMandateRouterData,
hyperswitch_domain_models::payment_method_data::Card,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, ccard): (
&SetupMandateRouterData,
hyperswitch_domain_models::payment_method_data::Card,
),
) -> Result<Self, Self::Error> {
if item.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Card 3DS".to_string(),
connector: "BankOfAmerica",
})?
};
let order_information = OrderInformationWithBill::try_from(item)?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information =
item.request.metadata.clone().map(|metadata| {
convert_metadata_to_merchant_defined_info(metadata.peek().to_owned())
});
let payment_information = PaymentInformation::try_from(&ccard)?;
let processing_information = ProcessingInformation::try_from((None, None))?;
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
consumer_authentication_information: None,
merchant_defined_information,
})
}
}
impl TryFrom<(&SetupMandateRouterData, ApplePayWalletData)> for BankOfAmericaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, apple_pay_data): (&SetupMandateRouterData, ApplePayWalletData),
) -> Result<Self, Self::Error> {
let order_information = OrderInformationWithBill::try_from(item)?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information =
item.request.metadata.clone().map(|metadata| {
convert_metadata_to_merchant_defined_info(metadata.peek().to_owned())
});
let payment_information = match item.payment_method_token.clone() {
Some(payment_method_token) => match payment_method_token {
PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
PaymentInformation::try_from(&decrypt_data)?
}
PaymentMethodToken::Token(_) => Err(unimplemented_payment_method!(
"Apple Pay",
"Manual",
"Bank Of America"
))?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Bank Of America"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => Err(unimplemented_payment_method!(
"Google Pay",
"Bank Of America"
))?,
},
None => PaymentInformation::try_from(&apple_pay_data)?,
};
let processing_information = ProcessingInformation::try_from((
Some(PaymentSolution::ApplePay),
Some(apple_pay_data.payment_method.network.clone()),
))?;
let ucaf_collection_indicator = match apple_pay_data
.payment_method
.network
.to_lowercase()
.as_str()
{
"mastercard" => Some("2".to_string()),
_ => None,
};
let consumer_authentication_information = Some(BankOfAmericaConsumerAuthInformation {
ucaf_collection_indicator,
cavv: None,
ucaf_authentication_data: None,
xid: None,
directory_server_transaction_id: None,
specification_version: None,
});
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information,
})
}
}
impl TryFrom<(&SetupMandateRouterData, GooglePayWalletData)> for BankOfAmericaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, google_pay_data): (&SetupMandateRouterData, GooglePayWalletData),
) -> Result<Self, Self::Error> {
let order_information = OrderInformationWithBill::try_from(item)?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information =
item.request.metadata.clone().map(|metadata| {
convert_metadata_to_merchant_defined_info(metadata.peek().to_owned())
});
let payment_information = PaymentInformation::try_from(&google_pay_data)?;
let processing_information =
ProcessingInformation::try_from((Some(PaymentSolution::GooglePay), None))?;
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information: None,
})
}
}
// specific for setupMandate flow
impl TryFrom<(Option<PaymentSolution>, Option<String>)> for ProcessingInformation {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(solution, network): (Option<PaymentSolution>, Option<String>),
) -> Result<Self, Self::Error> {
let (action_list, action_token_types, authorization_options) =
get_boa_mandate_action_details();
let commerce_indicator = get_commerce_indicator(network);
Ok(Self {
capture: Some(false),
capture_options: None,
action_list,
action_token_types,
authorization_options,
commerce_indicator,
payment_solution: solution.map(String::from),
})
}
}
impl TryFrom<&SetupMandateRouterData> for OrderInformationWithBill {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
let email = item.request.get_email()?;
let bill_to = build_bill_to(item.get_optional_billing(), email)?;
Ok(Self {
amount_details: Amount {
total_amount: StringMajorUnit::zero(),
currency: item.request.currency,
},
bill_to: Some(bill_to),
})
}
}
impl TryFrom<&hyperswitch_domain_models::payment_method_data::Card> for PaymentInformation {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
ccard: &hyperswitch_domain_models::payment_method_data::Card,
) -> Result<Self, Self::Error> {
let card_type = match ccard.card_network.clone().and_then(get_boa_card_type) {
Some(card_network) => Some(card_network.to_string()),
None => ccard.get_card_issuer().ok().map(String::from),
};
Ok(Self::Cards(Box::new(CardPaymentInformation {
card: Card {
number: ccard.card_number.clone(),
expiration_month: ccard.card_exp_month.clone(),
expiration_year: ccard.card_exp_year.clone(),
security_code: ccard.card_cvc.clone(),
card_type,
},
})))
}
}
impl TryFrom<&Box<ApplePayPredecryptData>> for PaymentInformation {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(apple_pay_data: &Box<ApplePayPredecryptData>) -> Result<Self, Self::Error> {
let expiration_month = apple_pay_data.get_expiry_month().change_context(
errors::ConnectorError::InvalidDataFormat {
field_name: "expiration_month",
},
)?;
let expiration_year = apple_pay_data.get_four_digit_expiry_year();
Ok(Self::ApplePay(Box::new(ApplePayPaymentInformation {
tokenized_card: TokenizedCard {
number: apple_pay_data.application_primary_account_number.clone(),
cryptogram: apple_pay_data
.payment_data
.online_payment_cryptogram
.clone(),
transaction_type: TransactionType::ApplePay,
expiration_year,
expiration_month,
},
})))
}
}
impl TryFrom<&ApplePayWalletData> for PaymentInformation {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(apple_pay_data: &ApplePayWalletData) -> Result<Self, Self::Error> {
let apple_pay_encrypted_data = apple_pay_data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
Ok(Self::ApplePayToken(Box::new(
ApplePayTokenPaymentInformation {
fluid_data: FluidData {
value: Secret::from(apple_pay_encrypted_data.clone()),
descriptor: None,
},
tokenized_card: ApplePayTokenizedCard {
transaction_type: TransactionType::ApplePay,
},
},
)))
}
}
impl TryFrom<&GooglePayWalletData> for PaymentInformation {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(google_pay_data: &GooglePayWalletData) -> Result<Self, Self::Error> {
Ok(Self::GooglePay(Box::new(GooglePayPaymentInformation {
fluid_data: FluidData {
value: Secret::from(
consts::BASE64_ENGINE.encode(
google_pay_data
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?
.clone(),
),
),
descriptor: None,
},
})))
}
}
fn convert_to_error_response_from_error_info(
error_response: &BankOfAmericaErrorInformationResponse,
status_code: u16,
) -> ErrorResponse {
let detailed_error_info =
error_response
.error_information
.to_owned()
.details
.map(|error_details| {
error_details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message.to_owned(),
detailed_error_info,
None,
);
ErrorResponse {
code: error_response
.error_information
.reason
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_response
.error_information
.reason
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
fn get_boa_mandate_action_details() -> (
Option<Vec<BankOfAmericaActionsList>>,
Option<Vec<BankOfAmericaActionsTokenType>>,
Option<BankOfAmericaAuthorizationOptions>,
) {
(
Some(vec![BankOfAmericaActionsList::TokenCreate]),
Some(vec![
BankOfAmericaActionsTokenType::PaymentInstrument,
BankOfAmericaActionsTokenType::Customer,
]),
Some(BankOfAmericaAuthorizationOptions {
initiator: Some(BankOfAmericaPaymentInitiator {
initiator_type: Some(BankOfAmericaPaymentInitiatorTypes::Customer),
credential_stored_on_file: Some(true),
stored_credential_used: None,
}),
merchant_initiated_transaction: None,
}),
)
}
fn get_commerce_indicator(network: Option<String>) -> String {
match network {
Some(card_network) => match card_network.to_lowercase().as_str() {
"amex" => "aesk",
"discover" => "dipb",
"mastercard" => "spa",
"visa" => "internet",
_ => "internet",
},
None => "internet",
}
.to_string()
}
pub fn get_error_reason(
error_info: Option<String>,
detailed_error_info: Option<String>,
avs_error_info: Option<String>,
) -> Option<String> {
match (error_info, detailed_error_info, avs_error_info) {
(Some(message), Some(details), Some(avs_message)) => Some(format!(
"{message}, detailed_error_information: {details}, avs_message: {avs_message}",
)),
(Some(message), Some(details), None) => {
Some(format!("{message}, detailed_error_information: {details}"))
}
(Some(message), None, Some(avs_message)) => {
Some(format!("{message}, avs_message: {avs_message}"))
}
(None, Some(details), Some(avs_message)) => {
Some(format!("{details}, avs_message: {avs_message}"))
}
(Some(message), None, None) => Some(message),
(None, Some(details), None) => Some(details),
(None, None, Some(avs_message)) => Some(avs_message),
(None, None, None) => None,
}
}
|
crates__hyperswitch_connectors__src__connectors__barclaycard.rs
|
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{
Authorize, Capture, CompleteAuthorize, PSync, PaymentMethodToken, PreProcessing,
Session, SetupMandate, Void,
},
refunds::{Execute, RSync},
Authenticate, PostAuthenticate, PreAuthenticate,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
PaymentsPostAuthenticateData, PaymentsPreAuthenticateData, PaymentsPreProcessingData,
PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthenticateRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData,
PaymentsPostAuthenticateRouterData, PaymentsPreAuthenticateRouterData,
PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{
self, PaymentsAuthenticateType, PaymentsPostAuthenticateType, PaymentsPreAuthenticateType,
PaymentsVoidType, Response,
},
webhooks,
};
use masking::{ExposeInterface, Mask, Maskable, PeekInterface};
use ring::{digest, hmac};
use time::OffsetDateTime;
use transformers as barclaycard;
use url::Url;
use crate::{
constants::{self, headers},
types::ResponseRouterData,
utils::{
convert_amount, PaymentsAuthorizeRequestData, PaymentsPreAuthenticateRequestData,
RefundsRequestData, RouterData as OtherRouterData,
},
};
pub const V_C_MERCHANT_ID: &str = "v-c-merchant-id";
#[derive(Clone)]
pub struct Barclaycard {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Barclaycard {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl Barclaycard {
pub fn generate_digest(&self, payload: &[u8]) -> String {
let payload_digest = digest::digest(&digest::SHA256, payload);
consts::BASE64_ENGINE.encode(payload_digest)
}
pub fn generate_signature(
&self,
auth: barclaycard::BarclaycardAuthType,
host: String,
resource: &str,
payload: &String,
date: OffsetDateTime,
http_method: Method,
) -> CustomResult<String, errors::ConnectorError> {
let barclaycard::BarclaycardAuthType {
api_key,
merchant_account,
api_secret,
} = auth;
let is_post_method = matches!(http_method, Method::Post);
let digest_str = if is_post_method { "digest " } else { "" };
let headers = format!("host date (request-target) {digest_str}{V_C_MERCHANT_ID}");
let request_target = if is_post_method {
format!("(request-target): post {resource}\ndigest: SHA-256={payload}\n")
} else {
format!("(request-target): get {resource}\n")
};
let signature_string = format!(
"host: {host}\ndate: {date}\n{request_target}{V_C_MERCHANT_ID}: {}",
merchant_account.peek()
);
let key_value = consts::BASE64_ENGINE
.decode(api_secret.expose())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "connector_account_details.api_secret",
})?;
let key = hmac::Key::new(hmac::HMAC_SHA256, &key_value);
let signature_value =
consts::BASE64_ENGINE.encode(hmac::sign(&key, signature_string.as_bytes()).as_ref());
let signature_header = format!(
r#"keyid="{}", algorithm="HmacSHA256", headers="{headers}", signature="{signature_value}""#,
api_key.peek()
);
Ok(signature_header)
}
}
impl api::Payment for Barclaycard {}
impl api::PaymentsAuthenticate for Barclaycard {}
impl api::PaymentsPreAuthenticate for Barclaycard {}
impl api::PaymentsPostAuthenticate for Barclaycard {}
impl api::PaymentSession for Barclaycard {}
impl api::PaymentsPreProcessing for Barclaycard {}
impl api::ConnectorAccessToken for Barclaycard {}
impl api::MandateSetup for Barclaycard {}
impl api::PaymentAuthorize for Barclaycard {}
impl api::PaymentSync for Barclaycard {}
impl api::PaymentCapture for Barclaycard {}
impl api::PaymentsCompleteAuthorize for Barclaycard {}
impl api::PaymentVoid for Barclaycard {}
impl api::Refund for Barclaycard {}
impl api::RefundExecute for Barclaycard {}
impl api::RefundSync for Barclaycard {}
impl api::PaymentToken for Barclaycard {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Barclaycard
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Barclaycard
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let date = OffsetDateTime::now_utc();
let barclaycard_req = self.get_request_body(req, connectors)?;
let http_method = self.get_http_method();
let auth = barclaycard::BarclaycardAuthType::try_from(&req.connector_auth_type)?;
let merchant_account = auth.merchant_account.clone();
let base_url = connectors.barclaycard.base_url.as_str();
let barclaycard_host =
Url::parse(base_url).change_context(errors::ConnectorError::RequestEncodingFailed)?;
let host = barclaycard_host
.host_str()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
let path: String = self
.get_url(req, connectors)?
.chars()
.skip(base_url.len() - 1)
.collect();
let sha256 = self.generate_digest(barclaycard_req.get_inner_value().expose().as_bytes());
let signature = self.generate_signature(
auth,
host.to_string(),
path.as_str(),
&sha256,
date,
http_method,
)?;
let mut headers = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
headers::ACCEPT.to_string(),
"application/hal+json;charset=utf-8".to_string().into(),
),
(V_C_MERCHANT_ID.to_string(), merchant_account.into_masked()),
("Date".to_string(), date.to_string().into()),
("Host".to_string(), host.to_string().into()),
("Signature".to_string(), signature.into_masked()),
];
if matches!(http_method, Method::Post | Method::Put) {
headers.push((
"Digest".to_string(),
format!("SHA-256={sha256}").into_masked(),
));
}
Ok(headers)
}
}
impl ConnectorCommon for Barclaycard {
fn id(&self) -> &'static str {
"barclaycard"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.barclaycard.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = barclaycard::BarclaycardAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.expose().into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: barclaycard::BarclaycardErrorResponse = res
.response
.parse_struct("BarclaycardErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_message = if res.status_code == 401 {
constants::CONNECTOR_UNAUTHORIZED_ERROR
} else {
hyperswitch_interfaces::consts::NO_ERROR_MESSAGE
};
match response {
transformers::BarclaycardErrorResponse::StandardError(response) => {
let (code, message, reason) = match response.error_information {
Some(ref error_info) => {
let detailed_error_info = error_info.details.as_ref().map(|details| {
details
.iter()
.map(|det| format!("{} : {}", det.field, det.reason))
.collect::<Vec<_>>()
.join(", ")
});
(
error_info.reason.clone(),
error_info.reason.clone(),
transformers::get_error_reason(
Some(error_info.message.clone()),
detailed_error_info,
None,
),
)
}
None => {
let detailed_error_info = response.details.map(|details| {
details
.iter()
.map(|det| format!("{} : {}", det.field, det.reason))
.collect::<Vec<_>>()
.join(", ")
});
(
response.reason.clone().map_or(
hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
|reason| reason.to_string(),
),
response
.reason
.map_or(error_message.to_string(), |reason| reason.to_string()),
transformers::get_error_reason(
response.message,
detailed_error_info,
None,
),
)
}
};
Ok(ErrorResponse {
status_code: res.status_code,
code,
message,
reason,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
transformers::BarclaycardErrorResponse::AuthenticationError(response) => {
Ok(ErrorResponse {
status_code: res.status_code,
code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: response.response.rmsg.clone(),
reason: Some(response.response.rmsg),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
}
}
impl ConnectorValidation for Barclaycard {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Barclaycard {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Barclaycard {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Barclaycard
{
}
impl ConnectorIntegration<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>
for Barclaycard
{
fn get_headers(
&self,
req: &PaymentsPreAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsPreAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}risk/v1/authentication-setups",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsPreAuthenticateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let minor_amount = req.request.get_minor_amount();
let currency = req.request.get_currency()?;
let amount = convert_amount(self.amount_converter, minor_amount, currency)?;
let connector_router_data = barclaycard::BarclaycardRouterData::try_from((amount, req))?;
let connector_req =
barclaycard::BarclaycardAuthSetupRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsPreAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsPreAuthenticateType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(PaymentsPreAuthenticateType::get_headers(
self, req, connectors,
)?)
.set_body(self.get_request_body(req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsPreAuthenticateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsPreAuthenticateRouterData, errors::ConnectorError> {
let response: barclaycard::BarclaycardAuthSetupResponse = res
.response
.parse_struct("Barclaycard AuthSetupResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
PaymentsPreAuthenticateRouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authenticate, PaymentsAuthenticateData, PaymentsResponseData>
for Barclaycard
{
fn get_headers(
&self,
req: &PaymentsAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}risk/v1/authentications",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsAuthenticateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let minor_amount =
req.request
.minor_amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "minor_amount",
})?;
let currency =
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?;
let amount = convert_amount(self.amount_converter, minor_amount, currency)?;
let connector_router_data = barclaycard::BarclaycardRouterData::try_from((amount, req))?;
let connector_req =
barclaycard::BarclaycardAuthEnrollmentRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthenticateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthenticateType::get_headers(
self, req, connectors,
)?)
.set_body(PaymentsAuthenticateType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthenticateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthenticateRouterData, errors::ConnectorError> {
let response: barclaycard::BarclaycardAuthenticationResponse = res
.response
.parse_struct("Barclaycard AuthEnrollmentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData>
for Barclaycard
{
fn get_headers(
&self,
req: &PaymentsPostAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsPostAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}risk/v1/authentication-results",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsPostAuthenticateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let minor_amount =
req.request
.minor_amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "minor_amount",
})?;
let currency =
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?;
let amount = convert_amount(self.amount_converter, minor_amount, currency)?;
let connector_router_data = barclaycard::BarclaycardRouterData::try_from((amount, req))?;
let connector_req =
barclaycard::BarclaycardAuthValidateRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsPostAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsPostAuthenticateType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(PaymentsPostAuthenticateType::get_headers(
self, req, connectors,
)?)
.set_body(PaymentsPostAuthenticateType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsPostAuthenticateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsPostAuthenticateRouterData, errors::ConnectorError> {
let response: barclaycard::BarclaycardAuthenticationResponse = res
.response
.parse_struct("Barclaycard AuthEnrollmentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
for Barclaycard
{
fn get_headers(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let redirect_response = req.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
match redirect_response.params {
Some(param) if !param.clone().peek().is_empty() => Ok(format!(
"{}risk/v1/authentications",
self.base_url(connectors)
)),
Some(_) | None => Ok(format!(
"{}risk/v1/authentication-results",
self.base_url(connectors)
)),
}
}
fn get_request_body(
&self,
req: &PaymentsPreProcessingRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_in_minor_unit = MinorUnit::new(req.request.amount);
let amount = convert_amount(
self.amount_converter,
amount_in_minor_unit,
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?,
)?;
let connector_router_data = barclaycard::BarclaycardRouterData::try_from((amount, req))?;
let connector_req =
barclaycard::BarclaycardPreProcessingRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsPreProcessingType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsPreProcessingType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsPreProcessingType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsPreProcessingRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: barclaycard::BarclaycardPreProcessingResponse = res
.response
.parse_struct("Barclaycard AuthEnrollmentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Barclaycard {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
if req.is_three_ds() && req.request.is_card() {
Ok(format!(
"{}risk/v1/authentication-setups",
ConnectorCommon::base_url(self, connectors)
))
} else {
Ok(format!(
"{}pts/v2/payments/",
ConnectorCommon::base_url(self, connectors)
))
}
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_in_minor_unit = MinorUnit::new(req.request.amount);
let amount = convert_amount(
self.amount_converter,
amount_in_minor_unit,
req.request.currency,
)?;
let connector_router_data = barclaycard::BarclaycardRouterData::try_from((amount, req))?;
if req.is_three_ds() && req.request.is_card() {
let connector_req =
barclaycard::BarclaycardAuthSetupRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
} else {
let connector_req =
barclaycard::BarclaycardPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
if data.is_three_ds() && data.request.is_card() {
let response: barclaycard::BarclaycardAuthSetupResponse = res
.response
.parse_struct("Barclaycard AuthSetupResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
} else {
let response: barclaycard::BarclaycardPaymentsResponse = res
.response
.parse_struct("Barclaycard PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: barclaycard::BarclaycardServerErrorResponse = res
.response
.parse_struct("BarclaycardServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
let attempt_status = match response.reason {
Some(reason) => match reason {
transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),
transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None,
},
None => None,
};
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Barclaycard {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}tss/v2/transactions/{connector_payment_id}",
self.base_url(connectors)
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: barclaycard::BarclaycardTransactionResponse = res
.response
.parse_struct("Barclaycard PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Barclaycard {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}pts/v2/payments/{connector_payment_id}/captures",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_in_minor_unit = MinorUnit::new(req.request.amount_to_capture);
let amount = convert_amount(
self.amount_converter,
amount_in_minor_unit,
req.request.currency,
)?;
let connector_router_data = barclaycard::BarclaycardRouterData::try_from((amount, req))?;
let connector_req =
barclaycard::BarclaycardCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: barclaycard::BarclaycardPaymentsResponse = res
.response
.parse_struct("Barclaycard PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: barclaycard::BarclaycardServerErrorResponse = res
.response
.parse_struct("BarclaycardServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Barclaycard {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}pts/v2/payments/{connector_payment_id}/reversals",
self.base_url(connectors)
))
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_in_minor_unit = MinorUnit::new(req.request.amount.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "amount",
},
)?);
let amount = convert_amount(
self.amount_converter,
amount_in_minor_unit,
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?,
)?;
let connector_router_data = barclaycard::BarclaycardRouterData::try_from((amount, req))?;
let connector_req = barclaycard::BarclaycardVoidRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: barclaycard::BarclaycardPaymentsResponse = res
.response
.parse_struct("Barclaycard PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: barclaycard::BarclaycardServerErrorResponse = res
.response
.parse_struct("BarclaycardServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Barclaycard {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}pts/v2/payments/{connector_payment_id}/refunds",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_in_minor_unit = MinorUnit::new(req.request.refund_amount);
let amount = convert_amount(
self.amount_converter,
amount_in_minor_unit,
req.request.currency,
)?;
let connector_router_data = barclaycard::BarclaycardRouterData::try_from((amount, req))?;
let connector_req =
barclaycard::BarclaycardRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: barclaycard::BarclaycardRefundResponse = res
.response
.parse_struct("barclaycard RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Barclaycard {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}tss/v2/transactions/{refund_id}",
self.base_url(connectors)
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: barclaycard::BarclaycardRsyncResponse = res
.response
.parse_struct("barclaycard RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Barclaycard
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}pts/v2/payments/",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_in_minor_unit = MinorUnit::new(req.request.amount);
let amount = convert_amount(
self.amount_converter,
amount_in_minor_unit,
req.request.currency,
)?;
let connector_router_data = barclaycard::BarclaycardRouterData::try_from((amount, req))?;
let connector_req =
barclaycard::BarclaycardPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: barclaycard::BarclaycardPaymentsResponse = res
.response
.parse_struct("Barclaycard PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: barclaycard::BarclaycardServerErrorResponse = res
.response
.parse_struct("BarclaycardServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
let attempt_status = match response.reason {
Some(reason) => match reason {
transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),
transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None,
},
None => None,
};
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Barclaycard {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static BARCLAYCARD_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::Maestro,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::UnionPay,
];
let mut barclaycard_supported_payment_methods = SupportedPaymentMethods::new();
barclaycard_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
barclaycard_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
barclaycard_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
barclaycard_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
barclaycard_supported_payment_methods
});
static BARCLAYCARD_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "BarclayCard SmartPay Fuse",
description: "Barclaycard, part of Barclays Bank UK PLC, is a leading global payment business that helps consumers, retailers and businesses to make and take payments flexibly, and to access short-term credit and point of sale finance.",
connector_type: enums::HyperswitchConnectorCategory::BankAcquirer,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static BARCLAYCARD_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Barclaycard {
fn is_pre_authentication_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool {
match current_flow {
api::CurrentFlowInfo::Authorize {
request_data,
auth_type,
} => *auth_type == common_enums::AuthenticationType::ThreeDs && request_data.is_card(),
// No alternate flow for complete authorize
api::CurrentFlowInfo::CompleteAuthorize { .. } => false,
api::CurrentFlowInfo::SetupMandate { .. } => false,
}
}
/// Check if authentication flow is required
fn is_authentication_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool {
match current_flow {
api::CurrentFlowInfo::Authorize { .. } => {
// during authorize flow, there is no post_authentication call needed
false
}
api::CurrentFlowInfo::CompleteAuthorize {
request_data,
payment_method: _,
..
} => {
// TODO: add logic before deciding the pre processing flow Authenticate or PostAuthenticate
let redirection_params = request_data
.redirect_response
.as_ref()
.and_then(|redirect_response| redirect_response.params.as_ref());
match redirection_params {
Some(param) if !param.peek().is_empty() => true,
Some(_) | None => false,
}
}
api::CurrentFlowInfo::SetupMandate { .. } => false,
}
}
/// Check if post-authentication flow is required
fn is_post_authentication_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool {
match current_flow {
api::CurrentFlowInfo::Authorize { .. } => {
// during authorize flow, there is no post_authentication call needed
false
}
api::CurrentFlowInfo::CompleteAuthorize {
request_data,
payment_method: _,
..
} => {
// TODO: add logic before deciding the pre processing flow Authenticate or PostAuthenticate
let redirection_params = request_data
.redirect_response
.as_ref()
.and_then(|redirect_response| redirect_response.params.as_ref());
match redirection_params {
Some(param) if !param.peek().is_empty() => false,
Some(_) | None => true,
}
}
api::CurrentFlowInfo::SetupMandate { .. } => false,
}
}
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&BARCLAYCARD_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*BARCLAYCARD_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&BARCLAYCARD_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__barclaycard__transformers.rs
|
use base64::Engine;
use common_enums::enums;
use common_types::payments::ApplePayPredecryptData;
use common_utils::{
consts, date_time,
ext_traits::ValueExt,
pii,
types::{SemanticVersion, StringMajorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{ApplePayWalletData, GooglePayWalletData, PaymentMethodData, WalletData},
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ErrorResponse, PaymentMethodToken, RouterData,
},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{
authentication::MessageExtensionAttribute, CompleteAuthorizeData, ResponseId,
UcsAuthenticationData,
},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{
PaymentsAuthenticateRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData,
PaymentsPostAuthenticateRouterData, PaymentsPreAuthenticateRouterData,
PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
constants,
types::{
PaymentsAuthenticateResponseRouterData, PaymentsCancelResponseRouterData,
PaymentsCaptureResponseRouterData, PaymentsPostAuthenticateResponseRouterData,
PaymentsPreAuthenticateResponseRouterData, PaymentsPreprocessingResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
ResponseRouterData,
},
unimplemented_payment_method,
utils::{
self, AddressDetailsData, CardData, ForeignTryFrom, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData,
PaymentsSyncRequestData, RouterData as OtherRouterData,
},
};
pub struct BarclaycardAuthType {
pub(super) api_key: Secret<String>,
pub(super) merchant_account: Secret<String>,
pub(super) api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BarclaycardAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = auth_type
{
Ok(Self {
api_key: api_key.to_owned(),
merchant_account: key1.to_owned(),
api_secret: api_secret.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
pub struct BarclaycardRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(StringMajorUnit, T)> for BarclaycardRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (StringMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardPaymentsRequest {
processing_information: ProcessingInformation,
payment_information: PaymentInformation,
order_information: OrderInformationWithBill,
client_reference_information: ClientReferenceInformation,
#[serde(skip_serializing_if = "Option::is_none")]
consumer_authentication_information: Option<BarclaycardConsumerAuthInformation>,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_defined_information: Option<Vec<MerchantDefinedInformation>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingInformation {
commerce_indicator: String,
capture: Option<bool>,
payment_solution: Option<String>,
cavv_algorithm: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantDefinedInformation {
key: u8,
value: String,
}
#[derive(Debug, Serialize)]
pub enum BarclaycardParesStatus {
#[serde(rename = "Y")]
AuthenticationSuccessful,
#[serde(rename = "A")]
AuthenticationAttempted,
#[serde(rename = "N")]
AuthenticationFailed,
#[serde(rename = "U")]
AuthenticationNotCompleted,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardConsumerAuthInformation {
ucaf_collection_indicator: Option<String>,
cavv: Option<Secret<String>>,
ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
directory_server_transaction_id: Option<Secret<String>>,
specification_version: Option<SemanticVersion>,
/// This field specifies the 3ds version
pa_specification_version: Option<SemanticVersion>,
/// Verification response enrollment status.
///
/// This field is supported only on Asia, Middle East, and Africa Gateway.
///
/// For external authentication, this field will always be "Y"
veres_enrolled: Option<String>,
/// Raw electronic commerce indicator (ECI)
eci_raw: Option<String>,
/// This field is supported only on Asia, Middle East, and Africa Gateway
/// Also needed for Credit Mutuel-CIC in France and Mastercard Identity Check transactions
/// This field is only applicable for Mastercard and Visa Transactions
pares_status: Option<BarclaycardParesStatus>,
//This field is used to send the authentication date in yyyyMMDDHHMMSS format
authentication_date: Option<String>,
/// This field indicates the 3D Secure transaction flow. It is only supported for secure transactions in France.
/// The possible values are - CH (Challenge), FD (Frictionless with delegation), FR (Frictionless)
effective_authentication_type: Option<EffectiveAuthenticationType>,
/// This field indicates the authentication type or challenge presented to the cardholder at checkout.
challenge_code: Option<String>,
/// This field indicates the reason for payer authentication response status. It is only supported for secure transactions in France.
pares_status_reason: Option<String>,
/// This field indicates the reason why strong authentication was cancelled. It is only supported for secure transactions in France.
challenge_cancel_code: Option<String>,
/// This field indicates the score calculated by the 3D Securing platform. It is only supported for secure transactions in France.
network_score: Option<u32>,
/// This is the transaction ID generated by the access control server. This field is supported only for secure transactions in France.
acs_transaction_id: Option<String>,
}
#[derive(Debug, Serialize)]
pub enum EffectiveAuthenticationType {
CH,
FR,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardPaymentInformation {
card: Card,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayPaymentInformation {
fluid_data: FluidData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCard {
number: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
cryptogram: Option<Secret<String>>,
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayTokenizedCard {
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayTokenPaymentInformation {
fluid_data: FluidData,
tokenized_card: ApplePayTokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayPaymentInformation {
tokenized_card: TokenizedCard,
}
pub const FLUID_DATA_DESCRIPTOR: &str = "RklEPUNPTU1PTi5BUFBMRS5JTkFQUC5QQVlNRU5U";
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymentInformation {
Cards(Box<CardPaymentInformation>),
GooglePay(Box<GooglePayPaymentInformation>),
ApplePay(Box<ApplePayPaymentInformation>),
ApplePayToken(Box<ApplePayTokenPaymentInformation>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
number: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
security_code: Secret<String>,
#[serde(rename = "type")]
card_type: Option<String>,
type_selection_indicator: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FluidData {
value: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
descriptor: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderInformationWithBill {
amount_details: Amount,
bill_to: Option<BillTo>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
total_amount: StringMajorUnit,
currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BillTo {
first_name: Secret<String>,
last_name: Secret<String>,
address1: Secret<String>,
locality: String,
administrative_area: Secret<String>,
postal_code: Secret<String>,
country: enums::CountryAlpha2,
email: pii::Email,
}
fn truncate_string(state: &Secret<String>, max_len: usize) -> Secret<String> {
let exposed = state.clone().expose();
let truncated = exposed.get(..max_len).unwrap_or(&exposed);
Secret::new(truncated.to_string())
}
fn build_bill_to(
address_details: &hyperswitch_domain_models::address::AddressDetails,
email: pii::Email,
) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> {
let administrative_area = address_details
.to_state_code_as_optional()
.unwrap_or_else(|_| {
address_details
.get_state()
.ok()
.map(|state| truncate_string(state, 20))
})
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "billing_address.state",
})?;
Ok(BillTo {
first_name: address_details.get_first_name()?.clone(),
last_name: address_details.get_last_name()?.clone(),
address1: address_details.get_line1()?.clone(),
locality: address_details.get_city()?.clone(),
administrative_area,
postal_code: address_details.get_zip()?.clone(),
country: address_details.get_country()?.to_owned(),
email,
})
}
fn get_barclaycard_card_type(card_network: common_enums::CardNetwork) -> Option<&'static str> {
match card_network {
common_enums::CardNetwork::Visa => Some("001"),
common_enums::CardNetwork::Mastercard => Some("002"),
common_enums::CardNetwork::AmericanExpress => Some("003"),
common_enums::CardNetwork::JCB => Some("007"),
common_enums::CardNetwork::DinersClub => Some("005"),
common_enums::CardNetwork::Discover => Some("004"),
common_enums::CardNetwork::CartesBancaires => Some("006"),
common_enums::CardNetwork::UnionPay => Some("062"),
//"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024"
common_enums::CardNetwork::Maestro => Some("042"),
common_enums::CardNetwork::Interac
| common_enums::CardNetwork::RuPay
| common_enums::CardNetwork::Star
| common_enums::CardNetwork::Accel
| common_enums::CardNetwork::Pulse
| common_enums::CardNetwork::Nyce => None,
}
}
#[derive(Debug, Serialize)]
pub enum PaymentSolution {
GooglePay,
ApplePay,
}
#[derive(Debug, Serialize)]
pub enum TransactionType {
#[serde(rename = "1")]
InApp,
}
impl From<PaymentSolution> for String {
fn from(solution: PaymentSolution) -> Self {
let payment_solution = match solution {
PaymentSolution::GooglePay => "012",
PaymentSolution::ApplePay => "001",
};
payment_solution.to_string()
}
}
impl
From<(
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
Option<BillTo>,
)> for OrderInformationWithBill
{
fn from(
(item, bill_to): (
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
Option<BillTo>,
),
) -> Self {
Self {
amount_details: Amount {
total_amount: item.amount.clone(),
currency: item.router_data.request.currency,
},
bill_to,
}
}
}
impl
TryFrom<(
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
)> for ProcessingInformation
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, solution, network): (
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
),
) -> Result<Self, Self::Error> {
let commerce_indicator = solution
.as_ref()
.map(|pm_solution| match pm_solution {
PaymentSolution::ApplePay => network
.as_ref()
.map(|card_network| match card_network.to_lowercase().as_str() {
"amex" => "internet",
"discover" => "internet",
"mastercard" => "spa",
"visa" => "internet",
_ => "internet",
})
.unwrap_or("internet"),
PaymentSolution::GooglePay => "internet",
})
.unwrap_or("internet")
.to_string();
let cavv_algorithm = Some("2".to_string());
Ok(Self {
capture: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
)),
payment_solution: solution.map(String::from),
commerce_indicator,
cavv_algorithm,
})
}
}
impl
TryFrom<(
&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
)> for ProcessingInformation
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, solution, network): (
&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
),
) -> Result<Self, Self::Error> {
let commerce_indicator = get_commerce_indicator(network);
let cavv_algorithm = Some("2".to_string());
Ok(Self {
capture: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
)),
payment_solution: solution.map(String::from),
commerce_indicator,
cavv_algorithm,
})
}
}
impl From<&BarclaycardRouterData<&PaymentsPreAuthenticateRouterData>>
for ClientReferenceInformation
{
fn from(item: &BarclaycardRouterData<&PaymentsPreAuthenticateRouterData>) -> Self {
Self {
code: Some(item.router_data.connector_request_reference_id.clone()),
}
}
}
impl From<&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>>
for ClientReferenceInformation
{
fn from(item: &BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>) -> Self {
Self {
code: Some(item.router_data.connector_request_reference_id.clone()),
}
}
}
impl From<&BarclaycardRouterData<&PaymentsAuthorizeRouterData>> for ClientReferenceInformation {
fn from(item: &BarclaycardRouterData<&PaymentsAuthorizeRouterData>) -> Self {
Self {
code: Some(item.router_data.connector_request_reference_id.clone()),
}
}
}
impl
From<(
&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>,
BillTo,
)> for OrderInformationWithBill
{
fn from(
(item, bill_to): (
&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>,
BillTo,
),
) -> Self {
Self {
amount_details: Amount {
total_amount: item.amount.clone(),
currency: item.router_data.request.currency,
},
bill_to: Some(bill_to),
}
}
}
impl From<BarclaycardAuthEnrollmentStatus> for enums::AttemptStatus {
fn from(item: BarclaycardAuthEnrollmentStatus) -> Self {
match item {
BarclaycardAuthEnrollmentStatus::PendingAuthentication => Self::AuthenticationPending,
BarclaycardAuthEnrollmentStatus::AuthenticationSuccessful => {
Self::AuthenticationSuccessful
}
BarclaycardAuthEnrollmentStatus::AuthenticationFailed => Self::AuthenticationFailed,
}
}
}
impl From<common_enums::DecoupledAuthenticationType> for EffectiveAuthenticationType {
fn from(auth_type: common_enums::DecoupledAuthenticationType) -> Self {
match auth_type {
common_enums::DecoupledAuthenticationType::Challenge => Self::CH,
common_enums::DecoupledAuthenticationType::Frictionless => Self::FR,
}
}
}
fn convert_metadata_to_merchant_defined_info(metadata: Value) -> Vec<MerchantDefinedInformation> {
let hashmap: std::collections::BTreeMap<String, Value> =
serde_json::from_str(&metadata.to_string()).unwrap_or(std::collections::BTreeMap::new());
let mut vector = Vec::new();
let mut iter = 1;
for (key, value) in hashmap {
vector.push(MerchantDefinedInformation {
key: iter,
value: format!("{key}={value}"),
});
iter += 1;
}
vector
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientReferenceInformation {
code: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientProcessorInformation {
avs: Option<Avs>,
card_verification: Option<CardVerification>,
processor: Option<ProcessorResponse>,
network_transaction_id: Option<Secret<String>>,
approval_code: Option<String>,
merchant_advice: Option<MerchantAdvice>,
response_code: Option<String>,
ach_verification: Option<AchVerification>,
system_trace_audit_number: Option<String>,
event_status: Option<String>,
retrieval_reference_number: Option<String>,
consumer_authentication_response: Option<ConsumerAuthenticationResponse>,
response_details: Option<String>,
transaction_id: Option<Secret<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantAdvice {
code: Option<String>,
code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConsumerAuthenticationResponse {
code: Option<String>,
code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AchVerification {
result_code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessorResponse {
name: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardVerification {
result_code: Option<String>,
result_code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientRiskInformation {
rules: Option<Vec<ClientRiskInformationRules>>,
profile: Option<Profile>,
score: Option<Score>,
info_codes: Option<InfoCodes>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InfoCodes {
address: Option<Vec<String>>,
identity_change: Option<Vec<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Score {
factor_codes: Option<Vec<String>>,
result: Option<RiskResult>,
model_used: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum RiskResult {
StringVariant(String),
IntVariant(u64),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Profile {
early_decision: Option<String>,
name: Option<String>,
decision: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ClientRiskInformationRules {
name: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Avs {
code: Option<String>,
code_raw: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardConsumerAuthValidateResponse {
ucaf_collection_indicator: Option<String>,
cavv: Option<Secret<String>>,
ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
specification_version: Option<SemanticVersion>,
directory_server_transaction_id: Option<Secret<String>>,
indicator: Option<String>,
}
impl ForeignTryFrom<&BarclaycardConsumerAuthValidateResponse> for UcsAuthenticationData {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
value: &BarclaycardConsumerAuthValidateResponse,
) -> Result<Self, Self::Error> {
Ok(Self {
eci: value.indicator.clone(),
cavv: value.cavv.clone(),
threeds_server_transaction_id: None,
message_version: value.specification_version.clone(),
ds_trans_id: value
.directory_server_transaction_id
.as_ref()
.map(|id| id.clone().expose()),
acs_trans_id: None,
trans_status: None,
transaction_id: value.xid.clone(),
ucaf_collection_indicator: value.ucaf_collection_indicator.clone(),
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct BarclaycardThreeDSMetadata {
three_ds_data: BarclaycardConsumerAuthValidateResponse,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardConsumerAuthInformationEnrollmentResponse {
access_token: Option<Secret<String>>,
step_up_url: Option<String>,
//Added to segregate the three_ds_data in a separate struct
#[serde(flatten)]
validate_response: BarclaycardConsumerAuthValidateResponse,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BarclaycardAuthEnrollmentStatus {
PendingAuthentication,
AuthenticationSuccessful,
AuthenticationFailed,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientAuthCheckInfoResponse {
id: String,
client_reference_information: ClientReferenceInformation,
consumer_authentication_information: BarclaycardConsumerAuthInformationEnrollmentResponse,
status: BarclaycardAuthEnrollmentStatus,
error_information: Option<BarclaycardErrorInformation>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardConsumerAuthInformationValidateRequest {
authentication_transaction_id: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BarclaycardPreProcessingResponse {
ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>),
ErrorInformation(Box<BarclaycardErrorInformationResponse>),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BarclaycardAuthenticationResponse {
ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>),
ErrorInformation(Box<BarclaycardErrorInformationResponse>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardAuthSetupRequest {
payment_information: PaymentInformation,
client_reference_information: ClientReferenceInformation,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardAuthValidateRequest {
payment_information: PaymentInformation,
client_reference_information: ClientReferenceInformation,
consumer_authentication_information: BarclaycardConsumerAuthInformationValidateRequest,
order_information: OrderInformation,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardAuthEnrollmentRequest {
payment_information: PaymentInformation,
client_reference_information: ClientReferenceInformation,
consumer_authentication_information: BarclaycardConsumerAuthInformationRequest,
order_information: OrderInformationWithBill,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct BarclaycardRedirectionAuthResponse {
pub transaction_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardConsumerAuthInformationRequest {
return_url: String,
reference_id: String,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum BarclaycardPreProcessingRequest {
AuthEnrollment(Box<BarclaycardAuthEnrollmentRequest>),
AuthValidate(Box<BarclaycardAuthValidateRequest>),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardConsumerAuthInformationResponse {
access_token: String,
device_data_collection_url: String,
reference_id: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientAuthSetupInfoResponse {
id: String,
client_reference_information: ClientReferenceInformation,
consumer_authentication_information: BarclaycardConsumerAuthInformationResponse,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BarclaycardAuthSetupResponse {
ClientAuthSetupInfo(Box<ClientAuthSetupInfoResponse>),
ErrorInformation(Box<BarclaycardErrorInformationResponse>),
}
impl TryFrom<&BarclaycardRouterData<&PaymentsAuthenticateRouterData>>
for BarclaycardAuthEnrollmentRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BarclaycardRouterData<&PaymentsAuthenticateRouterData>,
) -> Result<Self, Self::Error> {
let client_reference_information = ClientReferenceInformation {
code: Some(item.router_data.connector_request_reference_id.clone()),
};
let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "payment_method_data",
},
)?;
let payment_information = match payment_method_data {
PaymentMethodData::Card(ccard) => {
let card_type = match ccard
.card_network
.clone()
.and_then(get_barclaycard_card_type)
{
Some(card_network) => Some(card_network.to_string()),
None => ccard.get_card_issuer().ok().map(String::from),
};
Ok(PaymentInformation::Cards(Box::new(
CardPaymentInformation {
card: Card {
number: ccard.card_number,
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
security_code: ccard.card_cvc,
card_type,
type_selection_indicator: Some("1".to_owned()),
},
},
)))
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Barclaycard"),
))
}
}?;
let redirect_response = item.router_data.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let amount_details = Amount {
total_amount: item.amount.clone(),
currency: item.router_data.request.currency.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "currency",
},
)?,
};
let reference_id = redirect_response
.params
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response.params",
})?
.clone()
.peek()
.split_once('=')
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.params.reference_id",
})?
.1
.to_string();
let email = item
.router_data
.get_billing_email()
.ok()
.or(item.router_data.request.email.clone())
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "email",
})?;
let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?;
let order_information = OrderInformationWithBill {
amount_details,
bill_to: Some(bill_to),
};
let complete_authorize_url = item
.router_data
.request
.complete_authorize_url
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "complete_authorize_url",
})?;
Ok(Self {
payment_information,
client_reference_information,
consumer_authentication_information: BarclaycardConsumerAuthInformationRequest {
return_url: complete_authorize_url,
reference_id,
},
order_information,
})
}
}
impl TryFrom<&BarclaycardRouterData<&PaymentsPostAuthenticateRouterData>>
for BarclaycardAuthValidateRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BarclaycardRouterData<&PaymentsPostAuthenticateRouterData>,
) -> Result<Self, Self::Error> {
let client_reference_information = ClientReferenceInformation {
code: Some(item.router_data.connector_request_reference_id.clone()),
};
let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "payment_method_data",
},
)?;
let payment_information = match payment_method_data {
PaymentMethodData::Card(ccard) => {
let card_type = match ccard
.card_network
.clone()
.and_then(get_barclaycard_card_type)
{
Some(card_network) => Some(card_network.to_string()),
None => ccard.get_card_issuer().ok().map(String::from),
};
Ok(PaymentInformation::Cards(Box::new(
CardPaymentInformation {
card: Card {
number: ccard.card_number,
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
security_code: ccard.card_cvc,
card_type,
type_selection_indicator: Some("1".to_owned()),
},
},
)))
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Barclaycard"),
))
}
}?;
let redirect_response = item.router_data.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let amount_details = Amount {
total_amount: item.amount.clone(),
currency: item.router_data.request.currency.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "currency",
},
)?,
};
let redirect_payload: BarclaycardRedirectionAuthResponse = redirect_response
.payload
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
})?
.peek()
.clone()
.parse_value("BarclaycardRedirectionAuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let order_information = OrderInformation { amount_details };
Ok(Self {
payment_information,
client_reference_information,
consumer_authentication_information:
BarclaycardConsumerAuthInformationValidateRequest {
authentication_transaction_id: redirect_payload.transaction_id,
},
order_information,
})
}
}
impl TryFrom<&BarclaycardRouterData<&PaymentsPreProcessingRouterData>>
for BarclaycardPreProcessingRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BarclaycardRouterData<&PaymentsPreProcessingRouterData>,
) -> Result<Self, Self::Error> {
let client_reference_information = ClientReferenceInformation {
code: Some(item.router_data.connector_request_reference_id.clone()),
};
let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "payment_method_data",
},
)?;
let payment_information = match payment_method_data {
PaymentMethodData::Card(ccard) => {
let card_type = match ccard
.card_network
.clone()
.and_then(get_barclaycard_card_type)
{
Some(card_network) => Some(card_network.to_string()),
None => ccard.get_card_issuer().ok().map(String::from),
};
Ok(PaymentInformation::Cards(Box::new(
CardPaymentInformation {
card: Card {
number: ccard.card_number,
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
security_code: ccard.card_cvc,
card_type,
type_selection_indicator: Some("1".to_owned()),
},
},
)))
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Barclaycard"),
))
}
}?;
let redirect_response = item.router_data.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let amount_details = Amount {
total_amount: item.amount.clone(),
currency: item.router_data.request.currency.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "currency",
},
)?,
};
match redirect_response.params {
Some(param) if !param.clone().peek().is_empty() => {
let reference_id = param
.clone()
.peek()
.split_once('=')
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.params.reference_id",
})?
.1
.to_string();
let email = item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?;
let order_information = OrderInformationWithBill {
amount_details,
bill_to: Some(bill_to),
};
Ok(Self::AuthEnrollment(Box::new(
BarclaycardAuthEnrollmentRequest {
payment_information,
client_reference_information,
consumer_authentication_information:
BarclaycardConsumerAuthInformationRequest {
return_url: item
.router_data
.request
.get_complete_authorize_url()?,
reference_id,
},
order_information,
},
)))
}
Some(_) | None => {
let redirect_payload: BarclaycardRedirectionAuthResponse = redirect_response
.payload
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
})?
.peek()
.clone()
.parse_value("BarclaycardRedirectionAuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let order_information = OrderInformation { amount_details };
Ok(Self::AuthValidate(Box::new(
BarclaycardAuthValidateRequest {
payment_information,
client_reference_information,
consumer_authentication_information:
BarclaycardConsumerAuthInformationValidateRequest {
authentication_transaction_id: redirect_payload.transaction_id,
},
order_information,
},
)))
}
}
}
}
impl TryFrom<PaymentsPreAuthenticateResponseRouterData<BarclaycardPreProcessingResponse>>
for PaymentsPreAuthenticateRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsPreAuthenticateResponseRouterData<BarclaycardPreProcessingResponse>,
) -> Result<Self, Self::Error> {
match item.response {
BarclaycardPreProcessingResponse::ClientAuthCheckInfo(info_response) => {
let status = enums::AttemptStatus::from(info_response.status);
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
let response = Err(get_error_response(
&info_response.error_information,
&None,
&risk_info,
Some(status),
item.http_code,
info_response.id.clone(),
));
Ok(Self {
status,
response,
..item.data
})
} else {
let connector_response_reference_id = Some(
info_response
.client_reference_information
.code
.unwrap_or(info_response.id.clone()),
);
let redirection_data = match (
info_response
.consumer_authentication_information
.access_token,
info_response
.consumer_authentication_information
.step_up_url,
) {
(Some(token), Some(step_up_url)) => {
Some(RedirectForm::BarclaycardConsumerAuth {
access_token: token.expose(),
step_up_url,
})
}
_ => None,
};
let validate_response = &info_response
.consumer_authentication_information
.validate_response;
let three_ds_data = serde_json::to_value(validate_response)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let authentication_data =
UcsAuthenticationData::foreign_try_from(validate_response)
.ok()
.map(Box::new);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!({
"three_ds_data": three_ds_data
})),
network_txn_id: None,
connector_response_reference_id,
incremental_authorization_allowed: None,
authentication_data,
charges: None,
}),
..item.data
})
}
}
BarclaycardPreProcessingResponse::ErrorInformation(error_response) => {
let detailed_error_info =
error_response
.error_information
.details
.to_owned()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message,
detailed_error_info,
None,
);
let error_message = error_response.error_information.reason.to_owned();
let response = Err(ErrorResponse {
code: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code: item.http_code,
connector_response_reference_id: None,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
response,
status: enums::AttemptStatus::AuthenticationFailed,
..item.data
})
}
}
}
}
impl TryFrom<PaymentsAuthenticateResponseRouterData<BarclaycardAuthenticationResponse>>
for PaymentsAuthenticateRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsAuthenticateResponseRouterData<BarclaycardAuthenticationResponse>,
) -> Result<Self, Self::Error> {
match item.response {
BarclaycardAuthenticationResponse::ClientAuthCheckInfo(info_response) => {
let status = enums::AttemptStatus::from(info_response.status);
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
let response = Err(get_error_response(
&info_response.error_information,
&None,
&risk_info,
Some(status),
item.http_code,
info_response.id.clone(),
));
Ok(Self {
status,
response,
..item.data
})
} else {
let connector_response_reference_id = Some(
info_response
.client_reference_information
.code
.unwrap_or(info_response.id.clone()),
);
let redirection_data = match (
info_response
.consumer_authentication_information
.access_token,
info_response
.consumer_authentication_information
.step_up_url,
) {
(Some(token), Some(step_up_url)) => {
Some(RedirectForm::BarclaycardConsumerAuth {
access_token: token.expose(),
step_up_url,
})
}
_ => None,
};
let validate_response = &info_response
.consumer_authentication_information
.validate_response;
let three_ds_data = serde_json::to_value(validate_response)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let authentication_data =
UcsAuthenticationData::foreign_try_from(validate_response)
.ok()
.map(Box::new);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!({
"three_ds_data": three_ds_data
})),
network_txn_id: None,
connector_response_reference_id,
incremental_authorization_allowed: None,
authentication_data,
charges: None,
}),
..item.data
})
}
}
BarclaycardAuthenticationResponse::ErrorInformation(error_response) => {
let detailed_error_info =
error_response
.error_information
.details
.to_owned()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message,
detailed_error_info,
None,
);
let error_message = error_response.error_information.reason.to_owned();
let response = Err(ErrorResponse {
code: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code: item.http_code,
connector_response_reference_id: None,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
response,
status: enums::AttemptStatus::AuthenticationFailed,
..item.data
})
}
}
}
}
impl TryFrom<PaymentsPostAuthenticateResponseRouterData<BarclaycardAuthenticationResponse>>
for PaymentsPostAuthenticateRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsPostAuthenticateResponseRouterData<BarclaycardAuthenticationResponse>,
) -> Result<Self, Self::Error> {
match item.response {
BarclaycardAuthenticationResponse::ClientAuthCheckInfo(info_response) => {
let status = enums::AttemptStatus::from(info_response.status);
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
let response = Err(get_error_response(
&info_response.error_information,
&None,
&risk_info,
Some(status),
item.http_code,
info_response.id.clone(),
));
Ok(Self {
status,
response,
..item.data
})
} else {
let connector_response_reference_id = Some(
info_response
.client_reference_information
.code
.unwrap_or(info_response.id.clone()),
);
let redirection_data = match (
info_response
.consumer_authentication_information
.access_token,
info_response
.consumer_authentication_information
.step_up_url,
) {
(Some(token), Some(step_up_url)) => {
Some(RedirectForm::BarclaycardConsumerAuth {
access_token: token.expose(),
step_up_url,
})
}
_ => None,
};
let validate_response = &info_response
.consumer_authentication_information
.validate_response;
let three_ds_data = serde_json::to_value(validate_response)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let authentication_data =
UcsAuthenticationData::foreign_try_from(validate_response)
.ok()
.map(Box::new);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!({
"three_ds_data": three_ds_data
})),
network_txn_id: None,
connector_response_reference_id,
incremental_authorization_allowed: None,
authentication_data,
charges: None,
}),
..item.data
})
}
}
BarclaycardAuthenticationResponse::ErrorInformation(error_response) => {
let detailed_error_info =
error_response
.error_information
.details
.to_owned()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message,
detailed_error_info,
None,
);
let error_message = error_response.error_information.reason.to_owned();
let response = Err(ErrorResponse {
code: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code: item.http_code,
connector_response_reference_id: None,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
response,
status: enums::AttemptStatus::AuthenticationFailed,
..item.data
})
}
}
}
}
impl TryFrom<PaymentsPreprocessingResponseRouterData<BarclaycardPreProcessingResponse>>
for PaymentsPreProcessingRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsPreprocessingResponseRouterData<BarclaycardPreProcessingResponse>,
) -> Result<Self, Self::Error> {
match item.response {
BarclaycardPreProcessingResponse::ClientAuthCheckInfo(info_response) => {
let status = enums::AttemptStatus::from(info_response.status);
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
let response = Err(get_error_response(
&info_response.error_information,
&None,
&risk_info,
Some(status),
item.http_code,
info_response.id.clone(),
));
Ok(Self {
status,
response,
..item.data
})
} else {
let connector_response_reference_id = Some(
info_response
.client_reference_information
.code
.unwrap_or(info_response.id.clone()),
);
let redirection_data = match (
info_response
.consumer_authentication_information
.access_token,
info_response
.consumer_authentication_information
.step_up_url,
) {
(Some(token), Some(step_up_url)) => {
Some(RedirectForm::BarclaycardConsumerAuth {
access_token: token.expose(),
step_up_url,
})
}
_ => None,
};
let validate_response = &info_response
.consumer_authentication_information
.validate_response;
let three_ds_data = serde_json::to_value(validate_response)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let authentication_data =
UcsAuthenticationData::foreign_try_from(validate_response)
.ok()
.map(Box::new);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!({
"three_ds_data": three_ds_data
})),
network_txn_id: None,
connector_response_reference_id,
incremental_authorization_allowed: None,
authentication_data,
charges: None,
}),
..item.data
})
}
}
BarclaycardPreProcessingResponse::ErrorInformation(error_response) => {
let detailed_error_info =
error_response
.error_information
.details
.to_owned()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message,
detailed_error_info,
None,
);
let error_message = error_response.error_information.reason.to_owned();
let response = Err(ErrorResponse {
code: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
response,
status: enums::AttemptStatus::AuthenticationFailed,
..item.data
})
}
}
}
}
fn extract_score_id(message_extensions: &[MessageExtensionAttribute]) -> Option<u32> {
message_extensions.iter().find_map(|attr| {
attr.id
.ends_with("CB-SCORE")
.then(|| {
attr.id
.split('_')
.next()
.and_then(|p| p.strip_prefix('A'))
.and_then(|s| {
s.parse::<u32>().map(Some).unwrap_or_else(|err| {
router_env::logger::error!(
"Failed to parse score_id from '{}': {}",
s,
err
);
None
})
})
.or_else(|| {
router_env::logger::error!("Unexpected prefix format in id: {}", attr.id);
None
})
})
.flatten()
})
}
impl TryFrom<&BarclaycardRouterData<&PaymentsPreAuthenticateRouterData>>
for BarclaycardAuthSetupRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BarclaycardRouterData<&PaymentsPreAuthenticateRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => {
let card_type = match ccard
.card_network
.clone()
.and_then(get_barclaycard_card_type)
{
Some(card_network) => Some(card_network.to_string()),
None => ccard.get_card_issuer().ok().map(String::from),
};
let payment_information =
PaymentInformation::Cards(Box::new(CardPaymentInformation {
card: Card {
number: ccard.card_number,
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
security_code: ccard.card_cvc,
card_type,
type_selection_indicator: Some("1".to_owned()),
},
}));
let client_reference_information = ClientReferenceInformation::from(item);
Ok(Self {
payment_information,
client_reference_information,
})
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Barclaycard"),
)
.into())
}
}
}
}
impl TryFrom<&BarclaycardRouterData<&PaymentsAuthorizeRouterData>> for BarclaycardAuthSetupRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => {
let card_type = match ccard
.card_network
.clone()
.and_then(get_barclaycard_card_type)
{
Some(card_network) => Some(card_network.to_string()),
None => ccard.get_card_issuer().ok().map(String::from),
};
let payment_information =
PaymentInformation::Cards(Box::new(CardPaymentInformation {
card: Card {
number: ccard.card_number,
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
security_code: ccard.card_cvc,
card_type,
type_selection_indicator: Some("1".to_owned()),
},
}));
let client_reference_information = ClientReferenceInformation::from(item);
Ok(Self {
payment_information,
client_reference_information,
})
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Barclaycard"),
)
.into())
}
}
}
}
impl
TryFrom<(
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
hyperswitch_domain_models::payment_method_data::Card,
)> for BarclaycardPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, ccard): (
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
hyperswitch_domain_models::payment_method_data::Card,
),
) -> Result<Self, Self::Error> {
let email = item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?;
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
let payment_information = PaymentInformation::try_from(&ccard)?;
let processing_information = ProcessingInformation::try_from((item, None, None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
let pares_status = Some(BarclaycardParesStatus::AuthenticationSuccessful);
let consumer_authentication_information = item
.router_data
.request
.authentication_data
.as_ref()
.map(|authn_data| {
let (ucaf_authentication_data, cavv, ucaf_collection_indicator) =
if ccard.card_network == Some(common_enums::CardNetwork::Mastercard) {
(Some(authn_data.cavv.clone()), None, Some("2".to_string()))
} else {
(None, Some(authn_data.cavv.clone()), None)
};
let authentication_date = date_time::format_date(
authn_data.created_at,
date_time::DateFormat::YYYYMMDDHHmmss,
)
.ok();
let effective_authentication_type = authn_data.authentication_type.map(Into::into);
let network_score: Option<u32> =
if ccard.card_network == Some(common_enums::CardNetwork::CartesBancaires) {
match authn_data.message_extension.as_ref() {
Some(secret) => {
let exposed_value = secret.clone().expose();
match serde_json::from_value::<Vec<MessageExtensionAttribute>>(
exposed_value,
) {
Ok(exts) => extract_score_id(&exts),
Err(err) => {
router_env::logger::error!(
"Failed to deserialize message_extension: {:?}",
err
);
None
}
}
}
None => None,
}
} else {
None
};
BarclaycardConsumerAuthInformation {
pares_status,
ucaf_collection_indicator,
cavv,
ucaf_authentication_data,
xid: None,
directory_server_transaction_id: authn_data
.ds_trans_id
.clone()
.map(Secret::new),
specification_version: authn_data.message_version.clone(),
pa_specification_version: authn_data.message_version.clone(),
veres_enrolled: Some("Y".to_string()),
eci_raw: authn_data.eci.clone(),
authentication_date,
effective_authentication_type,
challenge_code: authn_data.challenge_code.clone(),
pares_status_reason: authn_data.challenge_code_reason.clone(),
challenge_cancel_code: authn_data.challenge_cancel.clone(),
network_score,
acs_transaction_id: authn_data.acs_trans_id.clone(),
}
});
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information,
})
}
}
impl
TryFrom<(
&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>,
hyperswitch_domain_models::payment_method_data::Card,
)> for BarclaycardPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, ccard): (
&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>,
hyperswitch_domain_models::payment_method_data::Card,
),
) -> Result<Self, Self::Error> {
let email = item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?;
let order_information = OrderInformationWithBill::from((item, bill_to));
let payment_information = PaymentInformation::try_from(&ccard)?;
let processing_information = ProcessingInformation::try_from((item, None, None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
let pares_status = Some(BarclaycardParesStatus::AuthenticationSuccessful);
let three_ds_info: BarclaycardThreeDSMetadata = item
.router_data
.request
.connector_meta
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "connector_meta",
})?
.parse_value("BarclaycardThreeDSMetadata")
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
let consumer_authentication_information = Some(BarclaycardConsumerAuthInformation {
pares_status,
ucaf_collection_indicator: three_ds_info.three_ds_data.ucaf_collection_indicator,
cavv: three_ds_info.three_ds_data.cavv,
ucaf_authentication_data: three_ds_info.three_ds_data.ucaf_authentication_data,
xid: three_ds_info.three_ds_data.xid,
directory_server_transaction_id: three_ds_info
.three_ds_data
.directory_server_transaction_id,
specification_version: three_ds_info.three_ds_data.specification_version.clone(),
pa_specification_version: three_ds_info.three_ds_data.specification_version.clone(),
veres_enrolled: None,
eci_raw: None,
authentication_date: None,
effective_authentication_type: None,
challenge_code: None,
pares_status_reason: None,
challenge_cancel_code: None,
network_score: None,
acs_transaction_id: None,
});
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information,
})
}
}
impl
TryFrom<(
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
GooglePayWalletData,
)> for BarclaycardPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, google_pay_data): (
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
GooglePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?;
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
let payment_information = PaymentInformation::try_from(&google_pay_data)?;
let processing_information =
ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay), None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information: None,
})
}
}
impl
TryFrom<(
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
ApplePayWalletData,
)> for BarclaycardPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, apple_pay_data, apple_pay_wallet_data): (
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
ApplePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?;
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
let processing_information =
ProcessingInformation::try_from((item, Some(PaymentSolution::ApplePay), None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let expiration_month = apple_pay_data.get_expiry_month().change_context(
errors::ConnectorError::InvalidDataFormat {
field_name: "expiration_month",
},
)?;
let expiration_year = apple_pay_data.get_four_digit_expiry_year();
let payment_information =
PaymentInformation::ApplePay(Box::new(ApplePayPaymentInformation {
tokenized_card: TokenizedCard {
number: apple_pay_data.application_primary_account_number,
cryptogram: Some(apple_pay_data.payment_data.online_payment_cryptogram),
transaction_type: TransactionType::InApp,
expiration_year,
expiration_month,
},
}));
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
let ucaf_collection_indicator = match apple_pay_wallet_data
.payment_method
.network
.to_lowercase()
.as_str()
{
"mastercard" => Some("2".to_string()),
_ => None,
};
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
consumer_authentication_information: Some(BarclaycardConsumerAuthInformation {
ucaf_collection_indicator,
cavv: None,
ucaf_authentication_data: None,
xid: None,
directory_server_transaction_id: None,
specification_version: None,
pa_specification_version: None,
veres_enrolled: None,
eci_raw: None,
pares_status: None,
authentication_date: None,
effective_authentication_type: None,
challenge_code: None,
pares_status_reason: None,
challenge_cancel_code: None,
network_score: None,
acs_transaction_id: None,
}),
merchant_defined_information,
})
}
}
impl TryFrom<&BarclaycardRouterData<&PaymentsAuthorizeRouterData>> for BarclaycardPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)),
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::GooglePay(google_pay_data) => Self::try_from((item, google_pay_data)),
WalletData::ApplePay(apple_pay_data) => {
match item.router_data.payment_method_token.clone() {
Some(payment_method_token) => match payment_method_token {
PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
Self::try_from((item, decrypt_data, apple_pay_data))
}
PaymentMethodToken::Token(_) => Err(unimplemented_payment_method!(
"Apple Pay",
"Manual",
"Cybersource"
))?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Cybersource"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Cybersource"))?
}
},
None => {
let transaction_type = TransactionType::InApp;
let email = item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to =
build_bill_to(item.router_data.get_billing_address()?, email)?;
let order_information =
OrderInformationWithBill::from((item, Some(bill_to)));
let processing_information = ProcessingInformation::try_from((
item,
Some(PaymentSolution::ApplePay),
Some(apple_pay_data.payment_method.network.clone()),
))?;
let client_reference_information =
ClientReferenceInformation::from(item);
let apple_pay_encrypted_data = apple_pay_data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
let payment_information = PaymentInformation::ApplePayToken(Box::new(
ApplePayTokenPaymentInformation {
fluid_data: FluidData {
value: Secret::from(apple_pay_encrypted_data.clone()),
descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()),
},
tokenized_card: ApplePayTokenizedCard { transaction_type },
},
));
let merchant_defined_information =
item.router_data.request.metadata.clone().map(|metadata| {
convert_metadata_to_merchant_defined_info(metadata)
});
let ucaf_collection_indicator = match apple_pay_data
.payment_method
.network
.to_lowercase()
.as_str()
{
"mastercard" => Some("2".to_string()),
_ => None,
};
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information: Some(
BarclaycardConsumerAuthInformation {
ucaf_collection_indicator,
cavv: None,
ucaf_authentication_data: None,
xid: None,
directory_server_transaction_id: None,
specification_version: None,
pa_specification_version: None,
veres_enrolled: None,
eci_raw: None,
pares_status: None,
authentication_date: None,
effective_authentication_type: None,
challenge_code: None,
pares_status_reason: None,
challenge_cancel_code: None,
network_score: None,
acs_transaction_id: None,
},
),
})
}
}
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::RevolutPay(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::AmazonPay(_)
| WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Barclaycard"),
)
.into()),
},
PaymentMethodData::MandatePayment
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Barclaycard"),
)
.into())
}
}
}
}
impl TryFrom<PaymentsPreAuthenticateResponseRouterData<BarclaycardAuthSetupResponse>>
for PaymentsPreAuthenticateRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsPreAuthenticateResponseRouterData<BarclaycardAuthSetupResponse>,
) -> Result<Self, Self::Error> {
match item.response {
BarclaycardAuthSetupResponse::ClientAuthSetupInfo(info_response) => Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::BarclaycardAuthSetup {
access_token: info_response
.consumer_authentication_information
.access_token,
ddc_url: info_response
.consumer_authentication_information
.device_data_collection_url,
reference_id: info_response
.consumer_authentication_information
.reference_id,
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
info_response
.client_reference_information
.code
.unwrap_or(info_response.id.clone()),
),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
}),
BarclaycardAuthSetupResponse::ErrorInformation(error_response) => {
let detailed_error_info =
error_response
.error_information
.details
.to_owned()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message,
detailed_error_info,
None,
);
let error_message = error_response.error_information.reason;
Ok(Self {
response: Err(ErrorResponse {
code: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_message.unwrap_or(
hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string(),
),
reason,
status_code: item.http_code,
connector_response_reference_id: None,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
status: enums::AttemptStatus::AuthenticationFailed,
..item.data
})
}
}
}
}
impl TryFrom<PaymentsResponseRouterData<BarclaycardAuthSetupResponse>>
for PaymentsAuthorizeRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<BarclaycardAuthSetupResponse>,
) -> Result<Self, Self::Error> {
match item.response {
BarclaycardAuthSetupResponse::ClientAuthSetupInfo(info_response) => Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::BarclaycardAuthSetup {
access_token: info_response
.consumer_authentication_information
.access_token,
ddc_url: info_response
.consumer_authentication_information
.device_data_collection_url,
reference_id: info_response
.consumer_authentication_information
.reference_id,
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
info_response
.client_reference_information
.code
.unwrap_or(info_response.id.clone()),
),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
}),
BarclaycardAuthSetupResponse::ErrorInformation(error_response) => {
let detailed_error_info =
error_response
.error_information
.details
.to_owned()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message,
detailed_error_info,
None,
);
let error_message = error_response.error_information.reason;
Ok(Self {
response: Err(ErrorResponse {
code: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_message.unwrap_or(
hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string(),
),
reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
status: enums::AttemptStatus::AuthenticationFailed,
..item.data
})
}
}
}
}
impl TryFrom<&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>>
for BarclaycardPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "payment_method_data",
},
)?;
match payment_method_data {
PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)),
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Barclaycard"),
)
.into())
}
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BarclaycardPaymentStatus {
Authorized,
Succeeded,
Failed,
Voided,
Reversed,
Pending,
Declined,
Rejected,
Challenge,
AuthorizedPendingReview,
AuthorizedRiskDeclined,
Transmitted,
InvalidRequest,
ServerError,
PendingAuthentication,
PendingReview,
Accepted,
Cancelled,
StatusNotReceived,
//PartialAuthorized, not being consumed yet.
}
fn map_barclaycard_attempt_status(
(status, auto_capture): (BarclaycardPaymentStatus, bool),
) -> enums::AttemptStatus {
match status {
BarclaycardPaymentStatus::Authorized
| BarclaycardPaymentStatus::AuthorizedPendingReview => {
if auto_capture {
// Because Barclaycard will return Payment Status as Authorized even in AutoCapture Payment
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
BarclaycardPaymentStatus::Pending => {
if auto_capture {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Pending
}
}
BarclaycardPaymentStatus::Succeeded | BarclaycardPaymentStatus::Transmitted => {
enums::AttemptStatus::Charged
}
BarclaycardPaymentStatus::Voided
| BarclaycardPaymentStatus::Reversed
| BarclaycardPaymentStatus::Cancelled => enums::AttemptStatus::Voided,
BarclaycardPaymentStatus::Failed
| BarclaycardPaymentStatus::Declined
| BarclaycardPaymentStatus::AuthorizedRiskDeclined
| BarclaycardPaymentStatus::InvalidRequest
| BarclaycardPaymentStatus::Rejected
| BarclaycardPaymentStatus::ServerError => enums::AttemptStatus::Failure,
BarclaycardPaymentStatus::PendingAuthentication => {
enums::AttemptStatus::AuthenticationPending
}
BarclaycardPaymentStatus::PendingReview
| BarclaycardPaymentStatus::StatusNotReceived
| BarclaycardPaymentStatus::Challenge
| BarclaycardPaymentStatus::Accepted => enums::AttemptStatus::Pending,
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BarclaycardPaymentsResponse {
ClientReferenceInformation(Box<BarclaycardClientReferenceResponse>),
ErrorInformation(Box<BarclaycardErrorInformationResponse>),
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardClientReferenceResponse {
id: String,
status: Option<BarclaycardPaymentStatus>,
client_reference_information: ClientReferenceInformation,
processor_information: Option<ClientProcessorInformation>,
processing_information: Option<ProcessingInformationResponse>,
payment_information: Option<PaymentInformationResponse>,
payment_insights_information: Option<PaymentInsightsInformation>,
risk_information: Option<ClientRiskInformation>,
error_information: Option<BarclaycardErrorInformation>,
issuer_information: Option<IssuerInformation>,
sender_information: Option<SenderInformation>,
payment_account_information: Option<PaymentAccountInformation>,
reconciliation_id: Option<String>,
consumer_authentication_information: Option<ConsumerAuthenticationInformation>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConsumerAuthenticationInformation {
eci_raw: Option<String>,
eci: Option<String>,
acs_transaction_id: Option<String>,
cavv: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SenderInformation {
payment_information: Option<PaymentInformationResponse>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInsightsInformation {
response_insights: Option<ResponseInsights>,
rule_results: Option<RuleResults>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResponseInsights {
category_code: Option<String>,
category: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RuleResults {
id: Option<String>,
decision: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInformationResponse {
tokenized_card: Option<CardResponseObject>,
customer: Option<CustomerResponseObject>,
card: Option<CardResponseObject>,
scheme: Option<String>,
bin: Option<String>,
account_type: Option<String>,
issuer: Option<String>,
bin_country: Option<enums::CountryAlpha2>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomerResponseObject {
customer_id: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentAccountInformation {
card: Option<PaymentAccountCardInformation>,
features: Option<PaymentAccountFeatureInformation>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentAccountFeatureInformation {
health_card: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentAccountCardInformation {
#[serde(rename = "type")]
card_type: Option<String>,
hashed_number: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingInformationResponse {
payment_solution: Option<String>,
commerce_indicator: Option<String>,
commerce_indicator_label: Option<String>,
ecommerce_indicator: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IssuerInformation {
country: Option<enums::CountryAlpha2>,
discretionary_data: Option<String>,
country_specific_discretionary_data: Option<String>,
response_code: Option<String>,
pin_request_indicator: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardResponseObject {
suffix: Option<String>,
prefix: Option<String>,
expiration_month: Option<Secret<String>>,
expiration_year: Option<Secret<String>>,
#[serde(rename = "type")]
card_type: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardErrorInformationResponse {
id: String,
error_information: BarclaycardErrorInformation,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct BarclaycardErrorInformation {
reason: Option<String>,
message: Option<String>,
details: Option<Vec<Details>>,
}
fn map_error_response<F, T>(
error_response: &BarclaycardErrorInformationResponse,
item: ResponseRouterData<F, BarclaycardPaymentsResponse, T, PaymentsResponseData>,
transaction_status: Option<enums::AttemptStatus>,
) -> RouterData<F, T, PaymentsResponseData> {
let detailed_error_info = error_response
.error_information
.details
.as_ref()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message.clone(),
detailed_error_info,
None,
);
let response = Err(ErrorResponse {
code: error_response
.error_information
.reason
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_response
.error_information
.reason
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
match transaction_status {
Some(status) => RouterData {
response,
status,
..item.data
},
None => RouterData {
response,
..item.data
},
}
}
fn get_error_response_if_failure(
(info_response, status, http_code): (
&BarclaycardClientReferenceResponse,
enums::AttemptStatus,
u16,
),
) -> Option<ErrorResponse> {
if utils::is_payment_failure(status) {
Some(get_error_response(
&info_response.error_information,
&info_response.processor_information,
&info_response.risk_information,
Some(status),
http_code,
info_response.id.clone(),
))
} else {
None
}
}
fn get_payment_response(
(info_response, status, http_code): (
&BarclaycardClientReferenceResponse,
enums::AttemptStatus,
u16,
),
) -> Result<PaymentsResponseData, Box<ErrorResponse>> {
let error_response = get_error_response_if_failure((info_response, status, http_code));
match error_response {
Some(error) => Err(Box::new(error)),
None => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(info_response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
info_response
.client_reference_information
.code
.clone()
.unwrap_or(info_response.id.clone()),
),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
}
}
impl TryFrom<PaymentsResponseRouterData<BarclaycardPaymentsResponse>>
for PaymentsAuthorizeRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<BarclaycardPaymentsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
BarclaycardPaymentsResponse::ClientReferenceInformation(info_response) => {
let status = map_barclaycard_attempt_status((
info_response
.status
.clone()
.unwrap_or(BarclaycardPaymentStatus::StatusNotReceived),
item.data.request.is_auto_capture()?,
));
let response = get_payment_response((&info_response, status, item.http_code))
.map_err(|err| *err);
let connector_response = match item.data.payment_method {
common_enums::PaymentMethod::Card => info_response
.processor_information
.as_ref()
.and_then(|processor_information| {
info_response
.consumer_authentication_information
.as_ref()
.map(|consumer_auth_information| {
convert_to_additional_payment_method_connector_response(
processor_information,
consumer_auth_information,
)
})
})
.map(ConnectorResponseData::with_additional_payment_method_data),
common_enums::PaymentMethod::CardRedirect
| common_enums::PaymentMethod::PayLater
| common_enums::PaymentMethod::Wallet
| common_enums::PaymentMethod::BankRedirect
| common_enums::PaymentMethod::BankTransfer
| common_enums::PaymentMethod::Crypto
| common_enums::PaymentMethod::BankDebit
| common_enums::PaymentMethod::Reward
| common_enums::PaymentMethod::RealTimePayment
| common_enums::PaymentMethod::MobilePayment
| common_enums::PaymentMethod::Upi
| common_enums::PaymentMethod::Voucher
| common_enums::PaymentMethod::OpenBanking
| common_enums::PaymentMethod::GiftCard
| common_enums::PaymentMethod::NetworkToken => None,
};
Ok(Self {
status,
response,
connector_response,
..item.data
})
}
BarclaycardPaymentsResponse::ErrorInformation(ref error_response) => {
Ok(map_error_response(
&error_response.clone(),
item,
Some(enums::AttemptStatus::Failure),
))
}
}
}
}
fn convert_to_additional_payment_method_connector_response(
processor_information: &ClientProcessorInformation,
consumer_authentication_information: &ConsumerAuthenticationInformation,
) -> AdditionalPaymentMethodConnectorResponse {
let payment_checks = Some(serde_json::json!({
"avs_response": processor_information.avs,
"card_verification": processor_information.card_verification,
"approval_code": processor_information.approval_code,
"consumer_authentication_response": processor_information.consumer_authentication_response,
"cavv": consumer_authentication_information.cavv,
"eci": consumer_authentication_information.eci,
"eci_raw": consumer_authentication_information.eci_raw,
}));
let authentication_data = Some(serde_json::json!({
"retrieval_reference_number": processor_information.retrieval_reference_number,
"acs_transaction_id": consumer_authentication_information.acs_transaction_id,
"system_trace_audit_number": processor_information.system_trace_audit_number,
}));
AdditionalPaymentMethodConnectorResponse::Card {
authentication_data,
payment_checks,
card_network: None,
domestic_network: None,
auth_code: None,
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<BarclaycardPaymentsResponse>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<BarclaycardPaymentsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
BarclaycardPaymentsResponse::ClientReferenceInformation(info_response) => {
let status = map_barclaycard_attempt_status((
info_response
.status
.clone()
.unwrap_or(BarclaycardPaymentStatus::StatusNotReceived),
true,
));
let response = get_payment_response((&info_response, status, item.http_code))
.map_err(|err| *err);
Ok(Self {
status,
response,
..item.data
})
}
BarclaycardPaymentsResponse::ErrorInformation(ref error_response) => {
Ok(map_error_response(&error_response.clone(), item, None))
}
}
}
}
impl TryFrom<PaymentsCancelResponseRouterData<BarclaycardPaymentsResponse>>
for PaymentsCancelRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<BarclaycardPaymentsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
BarclaycardPaymentsResponse::ClientReferenceInformation(info_response) => {
let status = map_barclaycard_attempt_status((
info_response
.status
.clone()
.unwrap_or(BarclaycardPaymentStatus::StatusNotReceived),
false,
));
let response = get_payment_response((&info_response, status, item.http_code))
.map_err(|err| *err);
Ok(Self {
status,
response,
..item.data
})
}
BarclaycardPaymentsResponse::ErrorInformation(ref error_response) => {
Ok(map_error_response(&error_response.clone(), item, None))
}
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardTransactionResponse {
id: String,
application_information: ApplicationInformation,
client_reference_information: Option<ClientReferenceInformation>,
processor_information: Option<ClientProcessorInformation>,
processing_information: Option<ProcessingInformationResponse>,
payment_information: Option<PaymentInformationResponse>,
payment_insights_information: Option<PaymentInsightsInformation>,
error_information: Option<BarclaycardErrorInformation>,
fraud_marking_information: Option<FraudMarkingInformation>,
risk_information: Option<ClientRiskInformation>,
reconciliation_id: Option<String>,
consumer_authentication_information: Option<ConsumerAuthenticationInformation>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FraudMarkingInformation {
reason: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplicationInformation {
status: Option<BarclaycardPaymentStatus>,
}
impl TryFrom<PaymentsSyncResponseRouterData<BarclaycardTransactionResponse>>
for PaymentsSyncRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<BarclaycardTransactionResponse>,
) -> Result<Self, Self::Error> {
match item.response.application_information.status {
Some(app_status) => {
let status = map_barclaycard_attempt_status((
app_status,
item.data.request.is_auto_capture()?,
));
let connector_response = match item.data.payment_method {
common_enums::PaymentMethod::Card => item
.response
.processor_information
.as_ref()
.and_then(|processor_information| {
item.response
.consumer_authentication_information
.as_ref()
.map(|consumer_auth_information| {
convert_to_additional_payment_method_connector_response(
processor_information,
consumer_auth_information,
)
})
})
.map(ConnectorResponseData::with_additional_payment_method_data),
common_enums::PaymentMethod::CardRedirect
| common_enums::PaymentMethod::PayLater
| common_enums::PaymentMethod::Wallet
| common_enums::PaymentMethod::BankRedirect
| common_enums::PaymentMethod::BankTransfer
| common_enums::PaymentMethod::Crypto
| common_enums::PaymentMethod::BankDebit
| common_enums::PaymentMethod::Reward
| common_enums::PaymentMethod::RealTimePayment
| common_enums::PaymentMethod::MobilePayment
| common_enums::PaymentMethod::Upi
| common_enums::PaymentMethod::Voucher
| common_enums::PaymentMethod::OpenBanking
| common_enums::PaymentMethod::GiftCard
| common_enums::PaymentMethod::NetworkToken => None,
};
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
Ok(Self {
response: Err(get_error_response(
&item.response.error_information,
&item.response.processor_information,
&risk_info,
Some(status),
item.http_code,
item.response.id.clone(),
)),
status: enums::AttemptStatus::Failure,
connector_response,
..item.data
})
} else {
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
.response
.client_reference_information
.map(|cref| cref.code)
.unwrap_or(Some(item.response.id)),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
connector_response,
..item.data
})
}
}
None => Ok(Self {
status: item.data.status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
}),
}
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BarclaycardPaymentsResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BarclaycardPaymentsResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
BarclaycardPaymentsResponse::ClientReferenceInformation(info_response) => {
let status = map_barclaycard_attempt_status((
info_response
.status
.clone()
.unwrap_or(BarclaycardPaymentStatus::StatusNotReceived),
item.data.request.is_auto_capture()?,
));
let response = get_payment_response((&info_response, status, item.http_code))
.map_err(|err| *err);
let connector_response = info_response
.processor_information
.as_ref()
.map(AdditionalPaymentMethodConnectorResponse::from)
.map(ConnectorResponseData::with_additional_payment_method_data);
Ok(Self {
status,
response,
connector_response,
..item.data
})
}
BarclaycardPaymentsResponse::ErrorInformation(ref error_response) => {
Ok(map_error_response(&error_response.clone(), item, None))
}
}
}
}
impl From<&ClientProcessorInformation> for AdditionalPaymentMethodConnectorResponse {
fn from(processor_information: &ClientProcessorInformation) -> Self {
let payment_checks = Some(
serde_json::json!({"avs_response": processor_information.avs, "card_verification": processor_information.card_verification}),
);
Self::Card {
authentication_data: None,
payment_checks,
card_network: None,
domestic_network: None,
auth_code: None,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderInformation {
amount_details: Amount,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardCaptureRequest {
order_information: OrderInformation,
client_reference_information: ClientReferenceInformation,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_defined_information: Option<Vec<MerchantDefinedInformation>>,
}
impl TryFrom<&BarclaycardRouterData<&PaymentsCaptureRouterData>> for BarclaycardCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: &BarclaycardRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let merchant_defined_information = value
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
order_information: OrderInformation {
amount_details: Amount {
total_amount: value.amount.to_owned(),
currency: value.router_data.request.currency,
},
},
client_reference_information: ClientReferenceInformation {
code: Some(value.router_data.connector_request_reference_id.clone()),
},
merchant_defined_information,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardVoidRequest {
client_reference_information: ClientReferenceInformation,
reversal_information: ReversalInformation,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_defined_information: Option<Vec<MerchantDefinedInformation>>,
// The connector documentation does not mention the merchantDefinedInformation field for Void requests. But this has been still added because it works!
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReversalInformation {
amount_details: Amount,
reason: String,
}
impl TryFrom<&BarclaycardRouterData<&PaymentsCancelRouterData>> for BarclaycardVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: &BarclaycardRouterData<&PaymentsCancelRouterData>,
) -> Result<Self, Self::Error> {
let merchant_defined_information = value
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
client_reference_information: ClientReferenceInformation {
code: Some(value.router_data.connector_request_reference_id.clone()),
},
reversal_information: ReversalInformation {
amount_details: Amount {
total_amount: value.amount.to_owned(),
currency: value.router_data.request.currency.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "Currency",
},
)?,
},
reason: value
.router_data
.request
.cancellation_reason
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "Cancellation Reason",
})?,
},
merchant_defined_information,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardRefundRequest {
order_information: OrderInformation,
client_reference_information: ClientReferenceInformation,
}
impl<F> TryFrom<&BarclaycardRouterData<&RefundsRouterData<F>>> for BarclaycardRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &BarclaycardRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
order_information: OrderInformation {
amount_details: Amount {
total_amount: item.amount.clone(),
currency: item.router_data.request.currency,
},
},
client_reference_information: ClientReferenceInformation {
code: Some(item.router_data.request.refund_id.clone()),
},
})
}
}
impl From<BarclaycardRefundResponse> for enums::RefundStatus {
fn from(item: BarclaycardRefundResponse) -> Self {
let error_reason = item
.error_information
.and_then(|error_info| error_info.reason);
match item.status {
BarclaycardRefundStatus::Succeeded | BarclaycardRefundStatus::Transmitted => {
Self::Success
}
BarclaycardRefundStatus::Cancelled
| BarclaycardRefundStatus::Failed
| BarclaycardRefundStatus::Voided => Self::Failure,
BarclaycardRefundStatus::Pending => Self::Pending,
BarclaycardRefundStatus::TwoZeroOne => {
if error_reason == Some("PROCESSOR_DECLINED".to_string()) {
Self::Failure
} else {
Self::Pending
}
}
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardRefundResponse {
id: String,
status: BarclaycardRefundStatus,
error_information: Option<BarclaycardErrorInformation>,
}
impl TryFrom<RefundsResponseRouterData<Execute, BarclaycardRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, BarclaycardRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.clone());
let response = if utils::is_refund_failure(refund_status) {
Err(get_error_response(
&item.response.error_information,
&None,
&None,
None,
item.http_code,
item.response.id,
))
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BarclaycardRefundStatus {
Succeeded,
Transmitted,
Failed,
Pending,
Voided,
Cancelled,
#[serde(rename = "201")]
TwoZeroOne,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RsyncApplicationInformation {
status: Option<BarclaycardRefundStatus>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardRsyncResponse {
id: String,
application_information: Option<RsyncApplicationInformation>,
error_information: Option<BarclaycardErrorInformation>,
}
impl TryFrom<RefundsResponseRouterData<RSync, BarclaycardRsyncResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, BarclaycardRsyncResponse>,
) -> Result<Self, Self::Error> {
let response = match item
.response
.application_information
.and_then(|application_information| application_information.status)
{
Some(status) => {
let error_reason = item
.response
.error_information
.clone()
.and_then(|error_info| error_info.reason);
let refund_status = match status {
BarclaycardRefundStatus::Succeeded | BarclaycardRefundStatus::Transmitted => {
enums::RefundStatus::Success
}
BarclaycardRefundStatus::Cancelled
| BarclaycardRefundStatus::Failed
| BarclaycardRefundStatus::Voided => enums::RefundStatus::Failure,
BarclaycardRefundStatus::Pending => enums::RefundStatus::Pending,
BarclaycardRefundStatus::TwoZeroOne => {
if error_reason == Some("PROCESSOR_DECLINED".to_string()) {
enums::RefundStatus::Failure
} else {
enums::RefundStatus::Pending
}
}
};
if utils::is_refund_failure(refund_status) {
if status == BarclaycardRefundStatus::Voided {
Err(get_error_response(
&Some(BarclaycardErrorInformation {
message: Some(constants::REFUND_VOIDED.to_string()),
reason: Some(constants::REFUND_VOIDED.to_string()),
details: None,
}),
&None,
&None,
None,
item.http_code,
item.response.id.clone(),
))
} else {
Err(get_error_response(
&item.response.error_information,
&None,
&None,
None,
item.http_code,
item.response.id.clone(),
))
}
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
})
}
}
None => Ok(RefundsResponseData {
connector_refund_id: item.response.id.clone(),
refund_status: match item.data.response {
Ok(response) => response.refund_status,
Err(_) => common_enums::RefundStatus::Pending,
},
}),
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardStandardErrorResponse {
pub error_information: Option<ErrorInformation>,
pub status: Option<String>,
pub message: Option<String>,
pub reason: Option<String>,
pub details: Option<Vec<Details>>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardServerErrorResponse {
pub status: Option<String>,
pub message: Option<String>,
pub reason: Option<Reason>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Reason {
SystemError,
ServerTimeout,
ServiceTimeout,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct BarclaycardAuthenticationErrorResponse {
pub response: AuthenticationErrorInformation,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BarclaycardErrorResponse {
AuthenticationError(BarclaycardAuthenticationErrorResponse),
StandardError(BarclaycardStandardErrorResponse),
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Details {
pub field: String,
pub reason: String,
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct ErrorInformation {
pub message: String,
pub reason: String,
pub details: Option<Vec<Details>>,
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct AuthenticationErrorInformation {
pub rmsg: String,
}
fn get_error_response(
error_data: &Option<BarclaycardErrorInformation>,
processor_information: &Option<ClientProcessorInformation>,
risk_information: &Option<ClientRiskInformation>,
attempt_status: Option<enums::AttemptStatus>,
status_code: u16,
transaction_id: String,
) -> ErrorResponse {
let avs_message = risk_information
.clone()
.map(|client_risk_information| {
client_risk_information.rules.map(|rules| {
rules
.iter()
.map(|risk_info| {
risk_info.name.clone().map_or("".to_string(), |name| {
format!(" , {}", name.clone().expose())
})
})
.collect::<Vec<String>>()
.join("")
})
})
.unwrap_or(Some("".to_string()));
let detailed_error_info = error_data.to_owned().and_then(|error_info| {
error_info.details.map(|error_details| {
error_details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
})
});
let network_decline_code = processor_information
.as_ref()
.and_then(|info| info.response_code.clone());
let network_advice_code = processor_information.as_ref().and_then(|info| {
info.merchant_advice
.as_ref()
.and_then(|merchant_advice| merchant_advice.code_raw.clone())
});
let reason = get_error_reason(
error_data
.clone()
.and_then(|error_details| error_details.message),
detailed_error_info,
avs_message,
);
let error_message = error_data
.clone()
.and_then(|error_details| error_details.reason);
ErrorResponse {
code: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code,
attempt_status,
connector_transaction_id: Some(transaction_id.clone()),
connector_response_reference_id: None,
network_advice_code,
network_decline_code,
network_error_message: None,
connector_metadata: None,
}
}
impl TryFrom<&hyperswitch_domain_models::payment_method_data::Card> for PaymentInformation {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
ccard: &hyperswitch_domain_models::payment_method_data::Card,
) -> Result<Self, Self::Error> {
let card_type = match ccard
.card_network
.clone()
.and_then(get_barclaycard_card_type)
{
Some(card_network) => Some(card_network.to_string()),
None => ccard.get_card_issuer().ok().map(String::from),
};
Ok(Self::Cards(Box::new(CardPaymentInformation {
card: Card {
number: ccard.card_number.clone(),
expiration_month: ccard.card_exp_month.clone(),
expiration_year: ccard.card_exp_year.clone(),
security_code: ccard.card_cvc.clone(),
card_type,
type_selection_indicator: Some("1".to_owned()),
},
})))
}
}
impl TryFrom<&GooglePayWalletData> for PaymentInformation {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(google_pay_data: &GooglePayWalletData) -> Result<Self, Self::Error> {
Ok(Self::GooglePay(Box::new(GooglePayPaymentInformation {
fluid_data: FluidData {
value: Secret::from(
consts::BASE64_ENGINE.encode(
google_pay_data
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?
.clone(),
),
),
descriptor: None,
},
})))
}
}
fn get_commerce_indicator(network: Option<String>) -> String {
match network {
Some(card_network) => match card_network.to_lowercase().as_str() {
"amex" => "aesk",
"discover" => "dipb",
"mastercard" => "spa",
"visa" => "internet",
_ => "internet",
},
None => "internet",
}
.to_string()
}
pub fn get_error_reason(
error_info: Option<String>,
detailed_error_info: Option<String>,
avs_error_info: Option<String>,
) -> Option<String> {
match (error_info, detailed_error_info, avs_error_info) {
(Some(message), Some(details), Some(avs_message)) => Some(format!(
"{message}, detailed_error_information: {details}, avs_message: {avs_message}",
)),
(Some(message), Some(details), None) => {
Some(format!("{message}, detailed_error_information: {details}"))
}
(Some(message), None, Some(avs_message)) => {
Some(format!("{message}, avs_message: {avs_message}"))
}
(None, Some(details), Some(avs_message)) => {
Some(format!("{details}, avs_message: {avs_message}"))
}
(Some(message), None, None) => Some(message),
(None, Some(details), None) => Some(details),
(None, None, Some(avs_message)) => Some(avs_message),
(None, None, None) => None,
}
}
|
crates__hyperswitch_connectors__src__connectors__billwerk.rs
|
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},
};
use masking::{Mask, PeekInterface};
use transformers::{
self as billwerk, BillwerkAuthType, BillwerkCaptureRequest, BillwerkErrorResponse,
BillwerkPaymentsRequest, BillwerkPaymentsResponse, BillwerkRefundRequest, BillwerkRouterData,
BillwerkTokenRequest, BillwerkTokenResponse,
};
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{convert_amount, RefundsRequestData},
};
#[derive(Clone)]
pub struct Billwerk {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Billwerk {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Billwerk {}
impl api::PaymentSession for Billwerk {}
impl api::ConnectorAccessToken for Billwerk {}
impl api::MandateSetup for Billwerk {}
impl api::PaymentAuthorize for Billwerk {}
impl api::PaymentSync for Billwerk {}
impl api::PaymentCapture for Billwerk {}
impl api::PaymentVoid for Billwerk {}
impl api::Refund for Billwerk {}
impl api::RefundExecute for Billwerk {}
impl api::RefundSync for Billwerk {}
impl api::PaymentToken for Billwerk {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Billwerk
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Billwerk {
fn id(&self) -> &'static str {
"billwerk"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.billwerk.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = BillwerkAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let encoded_api_key = BASE64_ENGINE.encode(format!("{}:", auth.api_key.peek()));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Basic {encoded_api_key}").into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: BillwerkErrorResponse = res
.response
.parse_struct("BillwerkErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response
.code
.map_or(NO_ERROR_CODE.to_string(), |code| code.to_string()),
message: response.message.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: Some(response.error),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Billwerk {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Billwerk {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Billwerk {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Billwerk
{
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Billwerk
{
fn get_headers(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url = connectors
.billwerk
.secondary_base_url
.as_ref()
.ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
Ok(format!("{base_url}v1/token"))
}
fn get_request_body(
&self,
req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = BillwerkTokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::TokenizationType::get_headers(self, req, connectors)?)
.set_body(types::TokenizationType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &TokenizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<TokenizationRouterData, errors::ConnectorError>
where
PaymentsResponseData: Clone,
{
let response: BillwerkTokenResponse = res
.response
.parse_struct("BillwerkTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Billwerk {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v1/charge", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = BillwerkRouterData::try_from((amount, req))?;
let connector_req = BillwerkPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: BillwerkPaymentsResponse = res
.response
.parse_struct("Billwerk BillwerkPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Billwerk {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}v1/charge/{}",
self.base_url(connectors),
req.connector_request_reference_id
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: BillwerkPaymentsResponse = res
.response
.parse_struct("billwerk BillwerkPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Billwerk {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_transaction_id = &req.request.connector_transaction_id;
Ok(format!(
"{}v1/charge/{connector_transaction_id}/settle",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = BillwerkRouterData::try_from((amount, req))?;
let connector_req = BillwerkCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: BillwerkPaymentsResponse = res
.response
.parse_struct("Billwerk BillwerkPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Billwerk {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_transaction_id = &req.request.connector_transaction_id;
Ok(format!(
"{}v1/charge/{connector_transaction_id}/cancel",
self.base_url(connectors)
))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: BillwerkPaymentsResponse = res
.response
.parse_struct("Billwerk BillwerkPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Billwerk {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v1/refund", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = BillwerkRouterData::try_from((amount, req))?;
let connector_req = BillwerkRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: billwerk::RefundResponse = res
.response
.parse_struct("billwerk RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Billwerk {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}v1/refund/{refund_id}",
self.base_url(connectors)
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: billwerk::RefundResponse = res
.response
.parse_struct("billwerk RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Billwerk {
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static BILLWERK_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::CartesBancaires,
];
let mut billwerk_supported_payment_methods = SupportedPaymentMethods::new();
billwerk_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
billwerk_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
billwerk_supported_payment_methods
});
static BILLWERK_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Billwerk",
description: "Billwerk+ Pay is an acquirer independent payment gateway that's easy to setup with more than 50 recurring and non-recurring payment methods.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static BILLWERK_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Billwerk {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&BILLWERK_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*BILLWERK_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&BILLWERK_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__bitpay.rs
|
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::IncomingWebhookEvent;
use common_enums::enums;
use common_utils::{
errors::{CustomResult, ReportSwitchExt},
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts, errors,
events::connector_api_logs::ConnectorEvent,
types::{PaymentsAuthorizeType, PaymentsSyncType, Response},
webhooks,
};
use masking::{Mask, PeekInterface};
use transformers as bitpay;
use self::bitpay::BitpayWebhookDetails;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Bitpay {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Bitpay {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Bitpay {}
impl api::PaymentToken for Bitpay {}
impl api::PaymentSession for Bitpay {}
impl api::ConnectorAccessToken for Bitpay {}
impl api::MandateSetup for Bitpay {}
impl api::PaymentAuthorize for Bitpay {}
impl api::PaymentSync for Bitpay {}
impl api::PaymentCapture for Bitpay {}
impl api::PaymentVoid for Bitpay {}
impl api::Refund for Bitpay {}
impl api::RefundExecute for Bitpay {}
impl api::RefundSync for Bitpay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Bitpay
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Bitpay
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
_req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let header = vec![
(
headers::CONTENT_TYPE.to_string(),
PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
),
(
headers::X_ACCEPT_VERSION.to_string(),
"2.0.0".to_string().into(),
),
];
Ok(header)
}
}
impl ConnectorCommon for Bitpay {
fn id(&self) -> &'static str {
"bitpay"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.bitpay.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = bitpay::BitpayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: bitpay::BitpayErrorResponse =
res.response.parse_struct("BitpayErrorResponse").switch()?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response
.code
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: response.error,
reason: response.message,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Bitpay {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Bitpay {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Bitpay {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Bitpay {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Bitpay".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Bitpay {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/invoices", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = bitpay::BitpayRouterData::from((amount, req));
let connector_req = bitpay::BitpayPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: bitpay::BitpayPaymentsResponse = res
.response
.parse_struct("Bitpay PaymentsAuthorizeResponse")
.switch()?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Bitpay {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth = bitpay::BitpayAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let connector_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/invoices/{}?token={}",
self.base_url(connectors),
connector_id,
auth.api_key.peek(),
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: bitpay::BitpayPaymentsResponse = res
.response
.parse_struct("bitpay PaymentsSyncResponse")
.switch()?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Bitpay {
fn build_request(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Bitpay".to_string(),
}
.into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Bitpay {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Bitpay {
fn build_request(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Refund flow not Implemented".to_string())
.into(),
)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Bitpay {
// default implementation of build_request method will be executed
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Bitpay {
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif: BitpayWebhookDetails = request
.body
.parse_struct("BitpayWebhookDetails")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(notif.data.id),
))
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let notif: BitpayWebhookDetails = request
.body
.parse_struct("BitpayWebhookDetails")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
match notif.event.name {
bitpay::WebhookEventType::Confirmed | bitpay::WebhookEventType::Completed => {
Ok(IncomingWebhookEvent::PaymentIntentSuccess)
}
bitpay::WebhookEventType::Paid => Ok(IncomingWebhookEvent::PaymentIntentProcessing),
bitpay::WebhookEventType::Declined => Ok(IncomingWebhookEvent::PaymentIntentFailure),
bitpay::WebhookEventType::Unknown
| bitpay::WebhookEventType::Expired
| bitpay::WebhookEventType::Invalid
| bitpay::WebhookEventType::Refunded
| bitpay::WebhookEventType::Resent => Ok(IncomingWebhookEvent::EventNotSupported),
}
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif: BitpayWebhookDetails = request
.body
.parse_struct("BitpayWebhookDetails")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(Box::new(notif))
}
}
static BITPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![enums::CaptureMethod::Automatic];
let mut bitpay_supported_payment_methods = SupportedPaymentMethods::new();
bitpay_supported_payment_methods.add(
enums::PaymentMethod::Crypto,
enums::PaymentMethodType::CryptoCurrency,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
bitpay_supported_payment_methods
});
static BITPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Bitpay",
description:
"BitPay is a cryptocurrency payment processor that enables businesses to accept Bitcoin and other digital currencies ",
connector_type: enums::HyperswitchConnectorCategory::AlternativePaymentMethod,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static BITPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];
impl ConnectorSpecifications for Bitpay {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&BITPAY_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*BITPAY_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&BITPAY_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__blackhawknetwork.rs
|
pub mod transformers;
use std::sync::LazyLock;
use common_enums::{enums, enums::PaymentMethodType};
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{
Authorize, Capture, PSync, PaymentMethodToken, PreProcessing, Session, SetupMandate,
Void,
},
refunds::{Execute, RSync},
GiftCardBalanceCheck,
},
router_request_types::{
AccessTokenRequestData, GiftCardBalanceCheckRequestData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData,
PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, GiftCardBalanceCheckResponseData, PaymentMethodDetails,
PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods,
SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData,
PaymentsGiftCardBalanceCheckRouterData, PaymentsPreProcessingRouterData,
PaymentsSyncRouterData, RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts::NO_ERROR_MESSAGE,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::Maskable;
use transformers as blackhawknetwork;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Blackhawknetwork {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Blackhawknetwork {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl api::Payment for Blackhawknetwork {}
impl api::PaymentSession for Blackhawknetwork {}
impl api::ConnectorAccessToken for Blackhawknetwork {}
impl api::MandateSetup for Blackhawknetwork {}
impl api::PaymentAuthorize for Blackhawknetwork {}
impl api::PaymentSync for Blackhawknetwork {}
impl api::PaymentCapture for Blackhawknetwork {}
impl api::PaymentVoid for Blackhawknetwork {}
impl api::Refund for Blackhawknetwork {}
impl api::RefundExecute for Blackhawknetwork {}
impl api::RefundSync for Blackhawknetwork {}
impl api::PaymentToken for Blackhawknetwork {}
impl api::PaymentsPreProcessing for Blackhawknetwork {}
impl api::PaymentsGiftCardBalanceCheck for Blackhawknetwork {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>
for Blackhawknetwork
{
fn get_headers(
&self,
_req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(vec![(
headers::CONTENT_TYPE.to_string(),
"application/x-www-form-urlencoded".to_string().into(),
)])
}
fn get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/realms/dev-experience/protocol/openid-connect/token",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let auth = blackhawknetwork::BlackhawknetworkAuthType::try_from(&req.connector_auth_type)?;
let connector_req = blackhawknetwork::BlackhawknetworkAccessTokenRequest {
grant_type: "client_credentials".to_string(),
client_id: auth.client_id.clone(),
client_secret: auth.client_secret.clone(),
scope: "openid".to_string(),
};
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefreshTokenType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefreshTokenType::get_headers(self, req, connectors)?)
.set_body(types::RefreshTokenType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefreshTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
let response: blackhawknetwork::BlackhawknetworkTokenResponse = res
.response
.parse_struct("BlackhawknetworkTokenResponse")
.or_else(|_| res.response.parse_struct("BlackhawknetworkErrorResponse"))
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Blackhawknetwork
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Blackhawknetwork
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Blackhawknetwork {
fn id(&self) -> &'static str {
"blackhawknetwork"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.blackhawknetwork.base_url.as_ref()
}
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(vec![])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: blackhawknetwork::BlackhawknetworkErrorResponse = res
.response
.parse_struct("BlackhawknetworkErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error,
message: response
.error_description
.clone()
.unwrap_or(NO_ERROR_MESSAGE.to_owned()),
reason: response.error_description,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Blackhawknetwork {
fn validate_mandate_payment(
&self,
_pm_type: Option<PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
match pm_data {
PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
"validate_mandate_payment does not support cards".to_string(),
)
.into()),
_ => Ok(()),
}
}
fn validate_psync_reference_id(
&self,
_data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
Ok(())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Blackhawknetwork {
//TODO: implement sessions flow
}
impl
ConnectorIntegration<
GiftCardBalanceCheck,
GiftCardBalanceCheckRequestData,
GiftCardBalanceCheckResponseData,
> for Blackhawknetwork
{
fn get_headers(
&self,
req: &PaymentsGiftCardBalanceCheckRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut headers = vec![(
headers::CONTENT_TYPE.to_string(),
"application/x-www-form-urlencoded".to_string().into(),
)];
let mut auth_header = self.get_auth_header(&req.connector_auth_type)?;
headers.append(&mut auth_header);
Ok(headers)
}
fn get_url(
&self,
req: &PaymentsGiftCardBalanceCheckRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url = self.base_url(connectors);
let connector_req = blackhawknetwork::BlackhawknetworkVerifyAccountRequest::try_from(req)?;
let query = serde_urlencoded::to_string(&connector_req)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(format!(
"{base_url}/accountProcessing/v1/verifyAccount?{query}"
))
}
fn build_request(
&self,
req: &PaymentsGiftCardBalanceCheckRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsGiftCardBalanceCheckType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsGiftCardBalanceCheckType::get_headers(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsGiftCardBalanceCheckRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsGiftCardBalanceCheckRouterData, errors::ConnectorError> {
let response: blackhawknetwork::BlackhawknetworkVerifyAccountResponse = res
.response
.parse_struct("BlackhawknetworkVerifyAccountResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
}
impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
for Blackhawknetwork
{
fn get_headers(
&self,
req: &PaymentsPreProcessingRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut headers = vec![(
headers::CONTENT_TYPE.to_string(),
"application/x-www-form-urlencoded".to_string().into(),
)];
let mut auth_header = self.get_auth_header(&req.connector_auth_type)?;
headers.append(&mut auth_header);
Ok(headers)
}
fn get_url(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url = self.base_url(connectors);
let connector_req = blackhawknetwork::BlackhawknetworkVerifyAccountRequest::try_from(req)?;
let query = serde_urlencoded::to_string(&connector_req)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(format!(
"{base_url}/accountProcessing/v1/verifyAccount?{query}"
))
}
fn build_request(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsPreProcessingType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsPreProcessingType::get_headers(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsPreProcessingRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: blackhawknetwork::BlackhawknetworkVerifyAccountResponse = res
.response
.parse_struct("BlackhawknetworkVerifyAccountResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Blackhawknetwork
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for Blackhawknetwork
{
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut headers = vec![(
headers::CONTENT_TYPE.to_string(),
"application/json".to_string().into(),
)];
let mut auth_header = self.get_auth_header(&req.connector_auth_type)?;
headers.append(&mut auth_header);
Ok(headers)
}
fn get_content_type(&self) -> &'static str {
"application/json"
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/accountProcessing/v1/redeem",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data =
blackhawknetwork::BlackhawknetworkRouterData::from((amount, req));
let connector_req =
blackhawknetwork::BlackhawknetworkPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: blackhawknetwork::BlackhawknetworkRedeemResponse = res
.response
.parse_struct("BlackhawknetworkRedeemResponse")
.or_else(|_| res.response.parse_struct("BlackhawknetworkErrorResponse"))
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: blackhawknetwork::BlackhawknetworkErrorResponse = res
.response
.parse_struct("BlackhawknetworkErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error,
message: response
.error_description
.unwrap_or(NO_ERROR_MESSAGE.to_owned()),
reason: Some("Verify redemption details or contact BHN support".to_string()),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Blackhawknetwork {
fn build_request(
&self,
_req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Payments Sync".to_string(),
connector: "BlackHawkNetwork".to_string(),
}
.into())
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Blackhawknetwork {
fn build_request(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "BlackHawkNetwork".to_string(),
}
.into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Blackhawknetwork {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Blackhawknetwork {
fn build_request(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refunds".to_string(),
connector: "BlackHawkNetwork".to_string(),
}
.into())
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Blackhawknetwork {
fn build_request(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refunds Sync".to_string(),
connector: "BlackHawkNetwork".to_string(),
}
.into())
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Blackhawknetwork {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static BLACKHAWKNETWORK_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Blackhawknetwork",
description: "Blackhawknetwork connector",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static BLACKHAWKNETWORK_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
static BLACKHAWKNETWORK_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![enums::CaptureMethod::Automatic];
let mut supported_payment_methods = SupportedPaymentMethods::new();
supported_payment_methods.add(
enums::PaymentMethod::GiftCard,
PaymentMethodType::BhnCardNetwork,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
supported_payment_methods
});
impl ConnectorSpecifications for Blackhawknetwork {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&BLACKHAWKNETWORK_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*BLACKHAWKNETWORK_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&BLACKHAWKNETWORK_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__bluesnap.rs
|
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::IncomingWebhookEvent;
use base64::Engine;
use common_enums::{enums, CallConnectorAction, PaymentAction};
use common_utils::{
consts::BASE64_ENGINE,
crypto,
errors::CustomResult,
ext_traits::{BytesExt, StringExt, ValueExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{
AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector, StringMajorUnit,
StringMajorUnitForConnector, StringMinorUnit, StringMinorUnitForConnector,
},
};
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
CompleteAuthorize,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, ResponseId, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RedirectForm,
RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsSessionRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
disputes::DisputePayload,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},
};
use masking::{Mask, PeekInterface};
use router_env::logger;
use transformers as bluesnap;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{
construct_not_supported_error_report, convert_amount, convert_back_amount_to_minor_units,
get_error_code_error_message_based_on_priority, get_header_key_value, get_http_header,
handle_json_response_deserialization_failure, to_connector_meta_from_secret,
ConnectorErrorType, ConnectorErrorTypeMapping, ForeignTryFrom,
PaymentsAuthorizeRequestData, RefundsRequestData, RouterData as _,
},
};
pub const BLUESNAP_TRANSACTION_NOT_FOUND: &str = "is not authorized to view merchant-transaction:";
pub const REQUEST_TIMEOUT_PAYMENT_NOT_FOUND: &str = "Timed out ,payment not found";
#[derive(Clone)]
pub struct Bluesnap {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
amount_converter_to_string_minor_unit:
&'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
amount_converter_float_major_unit:
&'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Bluesnap {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
amount_converter_to_string_minor_unit: &StringMinorUnitForConnector,
amount_converter_float_major_unit: &FloatMajorUnitForConnector,
}
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Bluesnap
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = self.get_auth_header(&req.connector_auth_type)?;
header.push((
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
));
Ok(header)
}
}
impl ConnectorCommon for Bluesnap {
fn id(&self) -> &'static str {
"bluesnap"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.bluesnap.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = bluesnap::BluesnapAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let encoded_api_key =
BASE64_ENGINE.encode(format!("{}:{}", auth.key1.peek(), auth.api_key.peek()));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Basic {encoded_api_key}").into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
logger::debug!(bluesnap_error_response=?res);
let response_data: Result<
bluesnap::BluesnapErrors,
Report<common_utils::errors::ParsingError>,
> = res.response.parse_struct("BluesnapErrors");
match response_data {
Ok(response) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let response_error_message = match response {
bluesnap::BluesnapErrors::Payment(error_response) => {
let error_list = error_response.message.clone();
let option_error_code_message =
get_error_code_error_message_based_on_priority(
self.clone(),
error_list.into_iter().map(|errors| errors.into()).collect(),
);
let reason = error_response
.message
.iter()
.map(|error| error.description.clone())
.collect::<Vec<String>>()
.join(" & ");
ErrorResponse {
status_code: res.status_code,
code: option_error_code_message
.clone()
.map(|error_code_message| error_code_message.error_code)
.unwrap_or(NO_ERROR_CODE.to_string()),
message: option_error_code_message
.map(|error_code_message| error_code_message.error_message)
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: Some(reason),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
bluesnap::BluesnapErrors::Auth(error_res) => ErrorResponse {
status_code: res.status_code,
code: error_res.error_code.clone(),
message: error_res.error_name.clone().unwrap_or(error_res.error_code),
reason: Some(error_res.error_description),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
},
bluesnap::BluesnapErrors::General(error_response) => {
let (error_res, attempt_status) = if res.status_code == 403
&& error_response.contains(BLUESNAP_TRANSACTION_NOT_FOUND)
{
(
format!(
"{REQUEST_TIMEOUT_PAYMENT_NOT_FOUND} in bluesnap dashboard",
),
Some(enums::AttemptStatus::Failure), // when bluesnap throws 403 for payment not found, we update the payment status to failure.
)
} else {
(error_response.clone(), None)
};
ErrorResponse {
status_code: res.status_code,
code: NO_ERROR_CODE.to_string(),
message: error_response,
reason: Some(error_res),
attempt_status,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
};
Ok(response_error_message)
}
Err(error_msg) => {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
router_env::logger::error!(deserialization_error =? error_msg);
handle_json_response_deserialization_failure(res, "bluesnap")
}
}
}
}
impl ConnectorValidation for Bluesnap {
fn validate_connector_against_payment_request(
&self,
capture_method: Option<enums::CaptureMethod>,
_payment_method: enums::PaymentMethod,
_pmt: Option<enums::PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
match capture_method {
enums::CaptureMethod::Automatic
| enums::CaptureMethod::Manual
| enums::CaptureMethod::SequentialAutomatic => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
construct_not_supported_error_report(capture_method, self.id()),
),
}
}
fn validate_psync_reference_id(
&self,
data: &PaymentsSyncData,
is_three_ds: bool,
status: enums::AttemptStatus,
connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
// If 3DS payment was triggered, connector will have context about payment in CompleteAuthorizeFlow and thus can't make force_sync
if is_three_ds && status == enums::AttemptStatus::AuthenticationPending {
return Err(
errors::ConnectorError::MissingConnectorRelatedTransactionID {
id: "connector_transaction_id".to_string(),
}
.into(),
);
}
// if connector_transaction_id is present, psync can be made
if data
.connector_transaction_id
.get_connector_transaction_id()
.is_ok()
{
return Ok(());
}
// if merchant_id is present, psync can be made along with attempt_id
let meta_data: CustomResult<bluesnap::BluesnapConnectorMetaData, errors::ConnectorError> =
to_connector_meta_from_secret(connector_meta_data.clone());
meta_data.map(|_| ())
}
}
impl api::Payment for Bluesnap {}
impl api::PaymentToken for Bluesnap {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Bluesnap
{
// Not Implemented (R)
}
impl api::MandateSetup for Bluesnap {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Bluesnap
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Bluesnap".to_string())
.into(),
)
}
}
impl api::PaymentVoid for Bluesnap {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Bluesnap {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"services/2/transactions"
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = bluesnap::BluesnapVoidRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Put)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: bluesnap::BluesnapPaymentsResponse = res
.response
.parse_struct("BluesnapPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::ConnectorAccessToken for Bluesnap {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Bluesnap {}
impl api::PaymentSync for Bluesnap {}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Bluesnap {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_transaction_id = req.request.connector_transaction_id.clone();
match connector_transaction_id {
// if connector_transaction_id is present, we always sync with connector_transaction_id
ResponseId::ConnectorTransactionId(trans_id) => {
get_psync_url_with_connector_transaction_id(
trans_id,
self.base_url(connectors).to_string(),
)
}
_ => {
// if connector_transaction_id is not present, we sync with merchant_transaction_id
let meta_data: bluesnap::BluesnapConnectorMetaData =
to_connector_meta_from_secret(req.connector_meta_data.clone())
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
get_url_with_merchant_transaction_id(
self.base_url(connectors).to_string(),
meta_data.merchant_id,
req.attempt_id.to_owned(),
)
}
}
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: bluesnap::BluesnapPaymentsResponse = res
.response
.parse_struct("BluesnapPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
}
impl api::PaymentCapture for Bluesnap {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Bluesnap {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"services/2/transactions"
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_to_capture = convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data =
bluesnap::BluesnapRouterData::try_from((amount_to_capture, req))?;
let connector_req = bluesnap::BluesnapCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Put)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: bluesnap::BluesnapPaymentsResponse = res
.response
.parse_struct("Bluesnap BluesnapPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
// This session code is not used
impl api::PaymentSession for Bluesnap {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Bluesnap {
fn get_headers(
&self,
req: &PaymentsSessionRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsSessionRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"services/2/wallets"
))
}
fn get_request_body(
&self,
req: &PaymentsSessionRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = bluesnap::BluesnapCreateWalletToken::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsSessionRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsSessionType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSessionType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsSessionType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSessionRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSessionRouterData, errors::ConnectorError> {
let response: bluesnap::BluesnapWalletTokenResponse = res
.response
.parse_struct("BluesnapWalletTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
let req_amount = data.request.minor_amount;
let req_currency = data.request.currency;
let apple_pay_amount = convert_amount(self.amount_converter, req_amount, req_currency)?;
RouterData::foreign_try_from((
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
apple_pay_amount,
))
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::PaymentAuthorize for Bluesnap {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Bluesnap {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
if req.is_three_ds() && req.request.is_card() {
Ok(format!(
"{}{}",
self.base_url(connectors),
"services/2/payment-fields-tokens/prefill",
))
} else {
Ok(format!(
"{}{}",
self.base_url(connectors),
"services/2/transactions"
))
}
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = bluesnap::BluesnapRouterData::try_from((amount, req))?;
match req.is_three_ds() && req.request.is_card() {
true => {
let connector_req =
bluesnap::BluesnapPaymentsTokenRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
_ => {
let connector_req =
bluesnap::BluesnapPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
}
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
match (data.is_three_ds() && data.request.is_card(), res.headers) {
(true, Some(headers)) => {
let location = get_http_header("Location", &headers)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?; // If location headers are not present connector will return 4XX so this error will never be propagated
let payment_fields_token = location
.split('/')
.next_back()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?
.to_string();
let response =
serde_json::json!({"payment_fields_token": payment_fields_token.clone()});
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(RouterData {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::BlueSnap {
payment_fields_token,
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..data.clone()
})
}
_ => {
let response: bluesnap::BluesnapPaymentsResponse = res
.response
.parse_struct("BluesnapPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::PaymentsCompleteAuthorize for Bluesnap {}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Bluesnap
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}services/2/transactions",
self.base_url(connectors),
))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = bluesnap::BluesnapRouterData::try_from((amount, req))?;
let connector_req =
bluesnap::BluesnapCompletePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: bluesnap::BluesnapPaymentsResponse = res
.response
.parse_struct("BluesnapPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::Refund for Bluesnap {}
impl api::RefundExecute for Bluesnap {}
impl api::RefundSync for Bluesnap {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Bluesnap {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"services/2/transactions/refund/",
req.request.connector_transaction_id
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = bluesnap::BluesnapRouterData::try_from((refund_amount, req))?;
let connector_req = bluesnap::BluesnapRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: bluesnap::RefundResponse = res
.response
.parse_struct("bluesnap RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Bluesnap {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
if req.request.payment_amount == req.request.refund_amount {
let meta_data: CustomResult<
bluesnap::BluesnapConnectorMetaData,
errors::ConnectorError,
> = to_connector_meta_from_secret(req.connector_meta_data.clone());
match meta_data {
// if merchant_id is present, rsync can be made using merchant_transaction_id
Ok(data) => get_url_with_merchant_transaction_id(
self.base_url(connectors).to_string(),
data.merchant_id,
req.attempt_id.to_owned(),
),
// otherwise rsync is made using connector_transaction_id
Err(_) => get_rsync_url_with_connector_refund_id(
req,
self.base_url(connectors).to_string(),
),
}
} else {
get_rsync_url_with_connector_refund_id(req, self.base_url(connectors).to_string())
}
}
fn build_request(
&self,
req: &RefundsRouterData<RSync>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: bluesnap::BluesnapPaymentsResponse = res
.response
.parse_struct("bluesnap BluesnapPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Bluesnap {
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let security_header = get_header_key_value("bls-signature", request.headers)?;
hex::decode(security_header)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)
}
fn get_webhook_source_verification_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let timestamp = get_header_key_value("bls-ipn-timestamp", request.headers)?;
Ok(format!("{}{}", timestamp, String::from_utf8_lossy(request.body)).into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook_body: bluesnap::BluesnapWebhookBody =
serde_urlencoded::from_bytes(request.body)
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
match webhook_body.transaction_type {
bluesnap::BluesnapWebhookEvents::Decline
| bluesnap::BluesnapWebhookEvents::CcChargeFailed
| bluesnap::BluesnapWebhookEvents::Charge
| bluesnap::BluesnapWebhookEvents::Chargeback
| bluesnap::BluesnapWebhookEvents::ChargebackStatusChanged => {
if webhook_body.merchant_transaction_id.is_empty() {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
webhook_body.reference_number,
),
))
} else {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::PaymentAttemptId(
webhook_body.merchant_transaction_id,
),
))
}
}
bluesnap::BluesnapWebhookEvents::Refund => {
Ok(api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(
webhook_body
.reversal_ref_num
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?,
),
))
}
bluesnap::BluesnapWebhookEvents::Unknown => {
Err(report!(errors::ConnectorError::WebhookReferenceIdNotFound))
}
}
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let details: bluesnap::BluesnapWebhookObjectEventType =
serde_urlencoded::from_bytes(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
IncomingWebhookEvent::try_from(details)
}
fn get_dispute_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<DisputePayload, errors::ConnectorError> {
let dispute_details: bluesnap::BluesnapDisputeWebhookBody =
serde_urlencoded::from_bytes(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let amount = convert_back_amount_to_minor_units(
self.amount_converter_float_major_unit,
dispute_details.invoice_charge_amount,
dispute_details.currency,
)?;
Ok(DisputePayload {
amount: convert_amount(
self.amount_converter_to_string_minor_unit,
amount,
dispute_details.currency,
)?,
currency: dispute_details.currency,
dispute_stage: api_models::enums::DisputeStage::Dispute,
connector_dispute_id: dispute_details.reversal_ref_num,
connector_reason: dispute_details.reversal_reason,
connector_reason_code: None,
challenge_required_by: None,
connector_status: dispute_details.cb_status,
created_at: None,
updated_at: None,
})
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let resource: bluesnap::BluesnapWebhookObjectResource =
serde_urlencoded::from_bytes(request.body)
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(resource))
}
}
impl ConnectorRedirectResponse for Bluesnap {
fn get_flow_type(
&self,
_query_params: &str,
json_payload: Option<serde_json::Value>,
action: PaymentAction,
) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
match action {
PaymentAction::PSync | PaymentAction::PaymentAuthenticateCompleteAuthorize => {
Ok(CallConnectorAction::Trigger)
}
PaymentAction::CompleteAuthorize => {
let redirection_response: bluesnap::BluesnapRedirectionResponse = json_payload
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "json_payload",
})?
.parse_value("BluesnapRedirectionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let redirection_result: bluesnap::BluesnapThreeDsResult = redirection_response
.authentication_response
.parse_struct("BluesnapThreeDsResult")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
match redirection_result.status.as_str() {
"Success" => Ok(CallConnectorAction::Trigger),
_ => Ok(CallConnectorAction::StatusUpdate {
status: enums::AttemptStatus::AuthenticationFailed,
error_code: redirection_result.code,
error_message: redirection_result
.info
.as_ref()
.and_then(|info| info.errors.as_ref().and_then(|error| error.first()))
.cloned(),
}),
}
}
}
}
}
impl ConnectorErrorTypeMapping for Bluesnap {
fn get_connector_error_type(
&self,
error_code: String,
error_message: String,
) -> ConnectorErrorType {
match (error_code.as_str(), error_message.as_str()) {
("7", "INVALID_TRANSACTION_TYPE") => ConnectorErrorType::UserError,
("30", "MISSING_SHOPPER_OR_CARD_HOLDER") => ConnectorErrorType::UserError,
("85", "INVALID_HTTP_METHOD") => ConnectorErrorType::BusinessError,
("90", "MISSING_CARD_TYPE") => ConnectorErrorType::BusinessError,
("10000", "INVALID_API_VERSION") => ConnectorErrorType::BusinessError,
("10000", "PAYMENT_GENERAL_FAILURE") => ConnectorErrorType::TechnicalError,
("10000", "SERVER_GENERAL_FAILURE") => ConnectorErrorType::BusinessError,
("10001", "VALIDATION_GENERAL_FAILURE") => ConnectorErrorType::BusinessError,
("10001", "INVALID_MERCHANT_TRANSACTION_ID") => ConnectorErrorType::BusinessError,
("10001", "INVALID_RECURRING_TRANSACTION") => ConnectorErrorType::BusinessError,
("10001", "MERCHANT_CONFIGURATION_ERROR") => ConnectorErrorType::BusinessError,
("10001", "MISSING_CARD_TYPE") => ConnectorErrorType::BusinessError,
("11001", "XSS_EXCEPTION") => ConnectorErrorType::UserError,
("14002", "THREE_D_SECURITY_AUTHENTICATION_REQUIRED") => {
ConnectorErrorType::TechnicalError
}
("14002", "ACCOUNT_CLOSED") => ConnectorErrorType::BusinessError,
("14002", "AUTHORIZATION_AMOUNT_ALREADY_REVERSED") => ConnectorErrorType::BusinessError,
("14002", "AUTHORIZATION_AMOUNT_NOT_VALID") => ConnectorErrorType::BusinessError,
("14002", "AUTHORIZATION_EXPIRED") => ConnectorErrorType::BusinessError,
("14002", "AUTHORIZATION_REVOKED") => ConnectorErrorType::BusinessError,
("14002", "AUTHORIZATION_NOT_FOUND") => ConnectorErrorType::UserError,
("14002", "BLS_CONNECTION_PROBLEM") => ConnectorErrorType::BusinessError,
("14002", "CALL_ISSUER") => ConnectorErrorType::UnknownError,
("14002", "CARD_LOST_OR_STOLEN") => ConnectorErrorType::UserError,
("14002", "CVV_ERROR") => ConnectorErrorType::UserError,
("14002", "DO_NOT_HONOR") => ConnectorErrorType::TechnicalError,
("14002", "EXPIRED_CARD") => ConnectorErrorType::UserError,
("14002", "GENERAL_PAYMENT_PROCESSING_ERROR") => ConnectorErrorType::TechnicalError,
("14002", "HIGH_RISK_ERROR") => ConnectorErrorType::BusinessError,
("14002", "INCORRECT_INFORMATION") => ConnectorErrorType::BusinessError,
("14002", "INCORRECT_SETUP") => ConnectorErrorType::BusinessError,
("14002", "INSUFFICIENT_FUNDS") => ConnectorErrorType::UserError,
("14002", "INVALID_AMOUNT") => ConnectorErrorType::BusinessError,
("14002", "INVALID_CARD_NUMBER") => ConnectorErrorType::UserError,
("14002", "INVALID_CARD_TYPE") => ConnectorErrorType::BusinessError,
("14002", "INVALID_PIN_OR_PW_OR_ID_ERROR") => ConnectorErrorType::UserError,
("14002", "INVALID_TRANSACTION") => ConnectorErrorType::BusinessError,
("14002", "LIMIT_EXCEEDED") => ConnectorErrorType::TechnicalError,
("14002", "PICKUP_CARD") => ConnectorErrorType::UserError,
("14002", "PROCESSING_AMOUNT_ERROR") => ConnectorErrorType::BusinessError,
("14002", "PROCESSING_DUPLICATE") => ConnectorErrorType::BusinessError,
("14002", "PROCESSING_GENERAL_DECLINE") => ConnectorErrorType::TechnicalError,
("14002", "PROCESSING_TIMEOUT") => ConnectorErrorType::TechnicalError,
("14002", "REFUND_FAILED") => ConnectorErrorType::TechnicalError,
("14002", "RESTRICTED_CARD") => ConnectorErrorType::UserError,
("14002", "STRONG_CUSTOMER_AUTHENTICATION_REQUIRED") => ConnectorErrorType::UserError,
("14002", "SYSTEM_TECHNICAL_ERROR") => ConnectorErrorType::BusinessError,
("14002", "THE_ISSUER_IS_UNAVAILABLE_OR_OFFLINE") => ConnectorErrorType::TechnicalError,
("14002", "THREE_D_SECURE_FAILURE") => ConnectorErrorType::UserError,
("14010", "FAILED_CREATING_PAYPAL_TOKEN") => ConnectorErrorType::TechnicalError,
("14011", "PAYMENT_METHOD_NOT_SUPPORTED") => ConnectorErrorType::BusinessError,
("14016", "NO_AVAILABLE_PROCESSORS") => ConnectorErrorType::TechnicalError,
("14034", "INVALID_PAYMENT_DETAILS") => ConnectorErrorType::UserError,
("15008", "SHOPPER_NOT_FOUND") => ConnectorErrorType::BusinessError,
("15012", "SHOPPER_COUNTRY_OFAC_SANCTIONED") => ConnectorErrorType::BusinessError,
("16003", "MULTIPLE_PAYMENT_METHODS_NON_SELECTED") => ConnectorErrorType::BusinessError,
("16001", "MISSING_ARGUMENTS") => ConnectorErrorType::BusinessError,
("17005", "INVALID_STEP_FIELD") => ConnectorErrorType::BusinessError,
("20002", "MULTIPLE_TRANSACTIONS_FOUND") => ConnectorErrorType::BusinessError,
("20003", "TRANSACTION_LOCKED") => ConnectorErrorType::BusinessError,
("20004", "TRANSACTION_PAYMENT_METHOD_NOT_SUPPORTED") => {
ConnectorErrorType::BusinessError
}
("20005", "TRANSACTION_NOT_AUTHORIZED") => ConnectorErrorType::UserError,
("20006", "TRANSACTION_ALREADY_EXISTS") => ConnectorErrorType::BusinessError,
("20007", "TRANSACTION_EXPIRED") => ConnectorErrorType::UserError,
("20008", "TRANSACTION_ID_REQUIRED") => ConnectorErrorType::TechnicalError,
("20009", "INVALID_TRANSACTION_ID") => ConnectorErrorType::BusinessError,
("20010", "TRANSACTION_ALREADY_CAPTURED") => ConnectorErrorType::BusinessError,
("20017", "TRANSACTION_CARD_NOT_VALID") => ConnectorErrorType::UserError,
("20031", "MISSING_RELEVANT_METHOD_FOR_SHOPPER") => ConnectorErrorType::BusinessError,
("20020", "INVALID_ALT_TRANSACTION_TYPE") => ConnectorErrorType::BusinessError,
("20021", "MULTI_SHOPPER_INFORMATION") => ConnectorErrorType::BusinessError,
("20022", "MISSING_SHOPPER_INFORMATION") => ConnectorErrorType::UserError,
("20023", "MISSING_PAYER_INFO_FIELDS") => ConnectorErrorType::UserError,
("20024", "EXPECT_NO_ECP_DETAILS") => ConnectorErrorType::UserError,
("20025", "INVALID_ECP_ACCOUNT_TYPE") => ConnectorErrorType::UserError,
("20025", "INVALID_PAYER_INFO_FIELDS") => ConnectorErrorType::UserError,
("20026", "MISMATCH_SUBSCRIPTION_CURRENCY") => ConnectorErrorType::BusinessError,
("20027", "PAYPAL_UNSUPPORTED_CURRENCY") => ConnectorErrorType::UserError,
("20033", "IDEAL_UNSUPPORTED_PAYMENT_INFO") => ConnectorErrorType::BusinessError,
("20035", "SOFORT_UNSUPPORTED_PAYMENT_INFO") => ConnectorErrorType::BusinessError,
("23001", "MISSING_WALLET_FIELDS") => ConnectorErrorType::BusinessError,
("23002", "INVALID_WALLET_FIELDS") => ConnectorErrorType::UserError,
("23003", "WALLET_PROCESSING_FAILURE") => ConnectorErrorType::TechnicalError,
("23005", "WALLET_EXPIRED") => ConnectorErrorType::UserError,
("23006", "WALLET_DUPLICATE_PAYMENT_METHODS") => ConnectorErrorType::BusinessError,
("23007", "WALLET_PAYMENT_NOT_ENABLED") => ConnectorErrorType::BusinessError,
("23008", "DUPLICATE_WALLET_RESOURCE") => ConnectorErrorType::BusinessError,
("23009", "WALLET_CLIENT_KEY_FAILURE") => ConnectorErrorType::BusinessError,
("23010", "INVALID_WALLET_PAYMENT_DATA") => ConnectorErrorType::UserError,
("23011", "WALLET_ONBOARDING_ERROR") => ConnectorErrorType::BusinessError,
("23012", "WALLET_MISSING_DOMAIN") => ConnectorErrorType::UserError,
("23013", "WALLET_UNREGISTERED_DOMAIN") => ConnectorErrorType::BusinessError,
("23014", "WALLET_CHECKOUT_CANCELED") => ConnectorErrorType::UserError,
("24012", "USER_NOT_AUTHORIZED") => ConnectorErrorType::UserError,
("24011", "CURRENCY_CODE_NOT_FOUND") => ConnectorErrorType::UserError,
("90009", "SUBSCRIPTION_NOT_FOUND") => ConnectorErrorType::UserError,
(_, " MISSING_ARGUMENTS") => ConnectorErrorType::UnknownError,
("43008", "EXTERNAL_TAX_SERVICE_MISMATCH_CURRENCY") => {
ConnectorErrorType::BusinessError
}
("43009", "EXTERNAL_TAX_SERVICE_UNEXPECTED_TOTAL_PAYMENT") => {
ConnectorErrorType::BusinessError
}
("43010", "EXTERNAL_TAX_SERVICE_TAX_REFERENCE_ALREADY_USED") => {
ConnectorErrorType::BusinessError
}
(
_,
"USER_NOT_AUTHORIZED"
| "CREDIT_CARD_DETAILS_PLAIN_AND_ENCRYPTED"
| "CREDIT_CARD_ENCRYPTED_SECURITY_CODE_REQUIRED"
| "CREDIT_CARD_ENCRYPTED_NUMBER_REQUIRED",
) => ConnectorErrorType::UserError,
_ => ConnectorErrorType::UnknownError,
}
}
}
fn get_url_with_merchant_transaction_id(
base_url: String,
merchant_id: common_utils::id_type::MerchantId,
merchant_transaction_id: String,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{},{}",
base_url,
"services/2/transactions/",
merchant_transaction_id,
merchant_id.get_string_repr()
))
}
fn get_psync_url_with_connector_transaction_id(
connector_transaction_id: String,
base_url: String,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}",
base_url, "services/2/transactions/", connector_transaction_id
))
}
fn get_rsync_url_with_connector_refund_id(
req: &RefundSyncRouterData,
base_url: String,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}",
base_url,
"services/2/transactions/",
req.request.get_connector_refund_id()?
))
}
static BLUESNAP_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::RuPay,
common_enums::CardNetwork::Maestro,
];
let mut bluesnap_supported_payment_methods = SupportedPaymentMethods::new();
bluesnap_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
bluesnap_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
bluesnap_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
bluesnap_supported_payment_methods
});
static BLUESNAP_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "BlueSnap",
description:
"BlueSnap is a payment platform that helps businesses accept payments from customers in over 200 regions ",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static BLUESNAP_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [
enums::EventClass::Payments,
enums::EventClass::Refunds,
enums::EventClass::Disputes,
];
impl ConnectorSpecifications for Bluesnap {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&BLUESNAP_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*BLUESNAP_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&BLUESNAP_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__bluesnap__transformers.rs
|
use std::collections::HashMap;
use api_models::{
payments::{
AmountInfo, ApplePayPaymentRequest, ApplePaySessionResponse,
ApplepayCombinedSessionTokenData, ApplepaySessionTokenData, ApplepaySessionTokenMetadata,
ApplepaySessionTokenResponse, NextActionCall, NoThirdPartySdkSessionResponse,
SdkNextAction, SessionToken,
},
webhooks::IncomingWebhookEvent,
};
use base64::Engine;
use common_enums::{enums, CountryAlpha2};
use common_utils::{
consts::{APPLEPAY_VALIDATION_URL, BASE64_ENGINE},
errors::CustomResult,
ext_traits::{ByteSliceExt, Encode, OptionExt, StringExt, ValueExt},
pii::Email,
types::{FloatMajorUnit, StringMajorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
address::AddressDetails,
payment_method_data::{self, PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
types::{PaymentsSessionResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, ApplePay, CardData as _, ForeignTryFrom,
PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, RouterData as _,
},
};
const DISPLAY_METADATA: &str = "Y";
#[derive(Debug, Serialize)]
pub struct BluesnapRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(StringMajorUnit, T)> for BluesnapRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (StringMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapPaymentsRequest {
amount: StringMajorUnit,
#[serde(flatten)]
payment_method: PaymentMethodDetails,
currency: enums::Currency,
card_transaction_type: BluesnapTxnType,
transaction_fraud_info: Option<TransactionFraudInfo>,
card_holder_info: Option<BluesnapCardHolderInfo>,
merchant_transaction_id: Option<String>,
transaction_meta_data: Option<BluesnapMetadata>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapMetadata {
meta_data: Vec<RequestMetadata>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RequestMetadata {
meta_key: Option<String>,
meta_value: Option<String>,
is_visible: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapCardHolderInfo {
first_name: Secret<String>,
last_name: Secret<String>,
email: Email,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionFraudInfo {
fraud_session_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapCreateWalletToken {
wallet_type: String,
validation_url: Secret<String>,
domain_name: String,
display_name: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapThreeDSecureInfo {
three_d_secure_reference_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum PaymentMethodDetails {
CreditCard(Card),
Wallet(BluesnapWallet),
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
card_number: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
security_code: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapWallet {
wallet_type: BluesnapWalletTypes,
encoded_payment_token: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapGooglePayObject {
payment_method_data: utils::GooglePayWalletData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BluesnapWalletTypes {
GooglePay,
ApplePay,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct EncodedPaymentToken {
billing_contact: BillingDetails,
token: ApplepayPaymentData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BillingDetails {
country_code: Option<CountryAlpha2>,
address_lines: Option<Vec<Secret<String>>>,
family_name: Option<Secret<String>>,
given_name: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ApplepayPaymentData {
payment_data: ApplePayEncodedPaymentData,
payment_method: ApplepayPaymentMethod,
transaction_identifier: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ApplepayPaymentMethod {
display_name: String,
network: String,
#[serde(rename = "type")]
pm_type: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ApplePayEncodedPaymentData {
data: String,
header: Option<ApplepayHeader>,
signature: String,
version: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ApplepayHeader {
ephemeral_public_key: Secret<String>,
public_key_hash: Secret<String>,
transaction_id: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BluesnapConnectorMetaData {
pub merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapPaymentsTokenRequest {
cc_number: cards::CardNumber,
exp_date: Secret<String>,
}
impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>>
for BluesnapPaymentsTokenRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BluesnapRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => Ok(Self {
cc_number: ccard.card_number.clone(),
exp_date: ccard.get_expiry_date_as_mmyyyy("/"),
}),
PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
"Selected payment method via Token flow through bluesnap".to_string(),
)
.into())
}
}
}
}
impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for BluesnapPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BluesnapRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let auth_mode = match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual) => BluesnapTxnType::AuthOnly,
_ => BluesnapTxnType::AuthCapture,
};
let transaction_meta_data =
item.router_data
.request
.metadata
.as_ref()
.map(|metadata| BluesnapMetadata {
meta_data: convert_metadata_to_request_metadata(metadata.to_owned()),
});
let (payment_method, card_holder_info) = match item
.router_data
.request
.payment_method_data
.clone()
{
PaymentMethodData::Card(ref ccard) => Ok((
PaymentMethodDetails::CreditCard(Card {
card_number: ccard.card_number.clone(),
expiration_month: ccard.card_exp_month.clone(),
expiration_year: ccard.get_expiry_year_4_digit(),
security_code: ccard.card_cvc.clone(),
}),
get_card_holder_info(
item.router_data.get_billing_address()?,
item.router_data.request.get_email()?,
)?,
)),
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::GooglePay(payment_method_data) => {
let gpay_ecrypted_object = BluesnapGooglePayObject {
payment_method_data: utils::GooglePayWalletData::try_from(
payment_method_data,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
}
.encode_to_string_of_json()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok((
PaymentMethodDetails::Wallet(BluesnapWallet {
wallet_type: BluesnapWalletTypes::GooglePay,
encoded_payment_token: Secret::new(
BASE64_ENGINE.encode(gpay_ecrypted_object),
),
}),
None,
))
}
WalletData::ApplePay(payment_method_data) => {
let apple_pay_payment_data =
payment_method_data.get_applepay_decoded_payment_data()?;
let apple_pay_payment_data: ApplePayEncodedPaymentData = apple_pay_payment_data
.expose()
.as_bytes()
.parse_struct("ApplePayEncodedPaymentData")
.change_context(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?;
let billing = item.router_data.get_billing()?.to_owned();
let billing_address = billing
.address
.get_required_value("billing_address")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "billing",
})?;
let mut address = Vec::new();
if let Some(add) = billing_address.line1.to_owned() {
address.push(add)
}
if let Some(add) = billing_address.line2.to_owned() {
address.push(add)
}
if let Some(add) = billing_address.line3.to_owned() {
address.push(add)
}
let apple_pay_object = EncodedPaymentToken {
token: ApplepayPaymentData {
payment_data: apple_pay_payment_data,
payment_method: payment_method_data.payment_method.to_owned().into(),
transaction_identifier: payment_method_data.transaction_identifier,
},
billing_contact: BillingDetails {
country_code: billing_address.country,
address_lines: Some(address),
family_name: billing_address.last_name.to_owned(),
given_name: billing_address.first_name.to_owned(),
postal_code: billing_address.zip,
},
}
.encode_to_string_of_json()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok((
PaymentMethodDetails::Wallet(BluesnapWallet {
wallet_type: BluesnapWalletTypes::ApplePay,
encoded_payment_token: Secret::new(
BASE64_ENGINE.encode(apple_pay_object),
),
}),
get_card_holder_info(
item.router_data.get_billing_address()?,
item.router_data.request.get_email()?,
)?,
))
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::WeChatPayQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("bluesnap"),
)),
},
PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("bluesnap"),
))
}
}?;
Ok(Self {
amount: item.amount.to_owned(),
payment_method,
currency: item.router_data.request.currency,
card_transaction_type: auth_mode,
transaction_fraud_info: Some(TransactionFraudInfo {
fraud_session_id: item.router_data.connector_request_reference_id.clone(),
}),
card_holder_info,
merchant_transaction_id: Some(item.router_data.connector_request_reference_id.clone()),
transaction_meta_data,
})
}
}
impl From<payment_method_data::ApplepayPaymentMethod> for ApplepayPaymentMethod {
fn from(item: payment_method_data::ApplepayPaymentMethod) -> Self {
Self {
display_name: item.display_name,
network: item.network,
pm_type: item.pm_type,
}
}
}
impl TryFrom<&types::PaymentsSessionRouterData> for BluesnapCreateWalletToken {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsSessionRouterData) -> Result<Self, Self::Error> {
let apple_pay_metadata = item.get_connector_meta()?.expose();
let applepay_metadata = apple_pay_metadata
.clone()
.parse_value::<ApplepayCombinedSessionTokenData>("ApplepayCombinedSessionTokenData")
.change_context(errors::ConnectorError::ParsingFailed)
.map(|combined_metadata| {
ApplepaySessionTokenMetadata::ApplePayCombined(
combined_metadata.apple_pay_combined.clone(),
)
})
.or_else(|_| {
apple_pay_metadata
.parse_value::<ApplepaySessionTokenData>("ApplepaySessionTokenData")
.change_context(errors::ConnectorError::ParsingFailed)
.map(|old_metadata| {
ApplepaySessionTokenMetadata::ApplePay(old_metadata.apple_pay)
})
})?;
let session_token_data = match applepay_metadata {
ApplepaySessionTokenMetadata::ApplePay(apple_pay_data) => {
Ok(apple_pay_data.session_token_data)
}
ApplepaySessionTokenMetadata::ApplePayCombined(_apple_pay_combined_data) => {
Err(errors::ConnectorError::FlowNotSupported {
flow: "apple pay combined".to_string(),
connector: "bluesnap".to_string(),
})
}
}?;
let domain_name = session_token_data.initiative_context.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "apple pay initiative_context",
},
)?;
Ok(Self {
wallet_type: "APPLE_PAY".to_string(),
validation_url: APPLEPAY_VALIDATION_URL.to_string().into(),
domain_name,
display_name: Some(session_token_data.display_name),
})
}
}
impl
ForeignTryFrom<(
PaymentsSessionResponseRouterData<BluesnapWalletTokenResponse>,
StringMajorUnit,
)> for types::PaymentsSessionRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, apple_pay_amount): (
PaymentsSessionResponseRouterData<BluesnapWalletTokenResponse>,
StringMajorUnit,
),
) -> Result<Self, Self::Error> {
let response = &item.response;
let wallet_token = BASE64_ENGINE
.decode(response.wallet_token.clone().expose())
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let session_response: NoThirdPartySdkSessionResponse = wallet_token
.parse_struct("NoThirdPartySdkSessionResponse")
.change_context(errors::ConnectorError::ParsingFailed)?;
let metadata = item.data.get_connector_meta()?.expose();
let applepay_metadata = metadata
.clone()
.parse_value::<ApplepayCombinedSessionTokenData>("ApplepayCombinedSessionTokenData")
.change_context(errors::ConnectorError::ParsingFailed)
.map(|combined_metadata| {
ApplepaySessionTokenMetadata::ApplePayCombined(combined_metadata.apple_pay_combined)
})
.or_else(|_| {
metadata
.parse_value::<ApplepaySessionTokenData>("ApplepaySessionTokenData")
.change_context(errors::ConnectorError::ParsingFailed)
.map(|old_metadata| {
ApplepaySessionTokenMetadata::ApplePay(old_metadata.apple_pay)
})
})?;
let (payment_request_data, session_token_data) = match applepay_metadata {
ApplepaySessionTokenMetadata::ApplePayCombined(_apple_pay_combined) => {
Err(errors::ConnectorError::FlowNotSupported {
flow: "apple pay combined".to_string(),
connector: "bluesnap".to_string(),
})
}
ApplepaySessionTokenMetadata::ApplePay(apple_pay) => {
Ok((apple_pay.payment_request_data, apple_pay.session_token_data))
}
}?;
Ok(Self {
response: Ok(PaymentsResponseData::SessionResponse {
session_token: SessionToken::ApplePay(Box::new(ApplepaySessionTokenResponse {
session_token_data: Some(ApplePaySessionResponse::NoThirdPartySdk(
session_response,
)),
payment_request_data: Some(ApplePayPaymentRequest {
country_code: item.data.get_billing_country()?,
currency_code: item.data.request.currency,
total: AmountInfo {
label: payment_request_data.label,
total_type: Some("final".to_string()),
amount: apple_pay_amount,
},
merchant_capabilities: Some(payment_request_data.merchant_capabilities),
supported_networks: Some(payment_request_data.supported_networks),
merchant_identifier: Some(session_token_data.merchant_identifier),
required_billing_contact_fields: None,
required_shipping_contact_fields: None,
recurring_payment_request: None,
}),
connector: "bluesnap".to_string(),
delayed_session_token: false,
sdk_next_action: {
SdkNextAction {
next_action: NextActionCall::Confirm,
}
},
connector_reference_id: None,
connector_sdk_public_key: None,
connector_merchant_id: None,
})),
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapCompletePaymentsRequest {
amount: StringMajorUnit,
currency: enums::Currency,
card_transaction_type: BluesnapTxnType,
pf_token: Secret<String>,
three_d_secure: Option<BluesnapThreeDSecureInfo>,
transaction_fraud_info: Option<TransactionFraudInfo>,
card_holder_info: Option<BluesnapCardHolderInfo>,
merchant_transaction_id: Option<String>,
transaction_meta_data: Option<BluesnapMetadata>,
}
impl TryFrom<&BluesnapRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
for BluesnapCompletePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BluesnapRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let redirection_response: BluesnapRedirectionResponse = item
.router_data
.request
.redirect_response
.as_ref()
.and_then(|res| res.payload.to_owned())
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
})?
.parse_value("BluesnapRedirectionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let transaction_meta_data =
item.router_data
.request
.metadata
.as_ref()
.map(|metadata| BluesnapMetadata {
meta_data: convert_metadata_to_request_metadata(metadata.to_owned()),
});
let token = item
.router_data
.request
.redirect_response
.clone()
.and_then(|res| res.params.to_owned())
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.params",
})?
.peek()
.split_once('=')
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.params.paymentToken",
})?
.1
.to_string();
let redirection_result: BluesnapThreeDsResult = redirection_response
.authentication_response
.parse_struct("BluesnapThreeDsResult")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let auth_mode = match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual) => BluesnapTxnType::AuthOnly,
_ => BluesnapTxnType::AuthCapture,
};
Ok(Self {
amount: item.amount.to_owned(),
currency: item.router_data.request.currency,
card_transaction_type: auth_mode,
three_d_secure: Some(BluesnapThreeDSecureInfo {
three_d_secure_reference_id: redirection_result
.three_d_secure
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "three_d_secure_reference_id",
})?
.three_d_secure_reference_id,
}),
transaction_fraud_info: Some(TransactionFraudInfo {
fraud_session_id: item.router_data.connector_request_reference_id.clone(),
}),
card_holder_info: get_card_holder_info(
item.router_data.get_billing_address()?,
item.router_data.request.get_email()?,
)?,
merchant_transaction_id: Some(item.router_data.connector_request_reference_id.clone()),
pf_token: Secret::new(token),
transaction_meta_data,
})
}
}
#[derive(Debug, Deserialize)]
pub struct BluesnapRedirectionResponse {
pub authentication_response: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapThreeDsResult {
three_d_secure: Option<BluesnapThreeDsReference>,
pub status: String,
pub code: Option<String>,
pub info: Option<RedirectErrorMessage>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RedirectErrorMessage {
pub errors: Option<Vec<String>>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapThreeDsReference {
three_d_secure_reference_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapVoidRequest {
card_transaction_type: BluesnapTxnType,
transaction_id: String,
}
impl TryFrom<&types::PaymentsCancelRouterData> for BluesnapVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let card_transaction_type = BluesnapTxnType::AuthReversal;
let transaction_id = item.request.connector_transaction_id.to_string();
Ok(Self {
card_transaction_type,
transaction_id,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapCaptureRequest {
card_transaction_type: BluesnapTxnType,
transaction_id: String,
amount: Option<StringMajorUnit>,
}
impl TryFrom<&BluesnapRouterData<&types::PaymentsCaptureRouterData>> for BluesnapCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BluesnapRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let card_transaction_type = BluesnapTxnType::Capture;
let transaction_id = item
.router_data
.request
.connector_transaction_id
.to_string();
Ok(Self {
card_transaction_type,
transaction_id,
amount: Some(item.amount.to_owned()),
})
}
}
// Auth Struct
pub struct BluesnapAuthType {
pub(super) api_key: Secret<String>,
pub(super) key1: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BluesnapAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
api_key: api_key.to_owned(),
key1: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BluesnapTxnType {
AuthOnly,
AuthCapture,
AuthReversal,
Capture,
Refund,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum BluesnapProcessingStatus {
#[serde(alias = "success")]
Success,
#[default]
#[serde(alias = "pending")]
Pending,
#[serde(alias = "fail")]
Fail,
#[serde(alias = "pending_merchant_review")]
PendingMerchantReview,
}
impl ForeignTryFrom<(BluesnapTxnType, BluesnapProcessingStatus)> for enums::AttemptStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
item: (BluesnapTxnType, BluesnapProcessingStatus),
) -> Result<Self, Self::Error> {
let (item_txn_status, item_processing_status) = item;
Ok(match item_processing_status {
BluesnapProcessingStatus::Success => match item_txn_status {
BluesnapTxnType::AuthOnly => Self::Authorized,
BluesnapTxnType::AuthReversal => Self::Voided,
BluesnapTxnType::AuthCapture | BluesnapTxnType::Capture => Self::Charged,
BluesnapTxnType::Refund => Self::Charged,
},
BluesnapProcessingStatus::Pending | BluesnapProcessingStatus::PendingMerchantReview => {
Self::Pending
}
BluesnapProcessingStatus::Fail => Self::Failure,
})
}
}
impl From<BluesnapProcessingStatus> for enums::RefundStatus {
fn from(item: BluesnapProcessingStatus) -> Self {
match item {
BluesnapProcessingStatus::Success => Self::Success,
BluesnapProcessingStatus::Pending => Self::Pending,
BluesnapProcessingStatus::PendingMerchantReview => Self::ManualReview,
BluesnapProcessingStatus::Fail => Self::Failure,
}
}
}
impl From<BluesnapRefundStatus> for enums::RefundStatus {
fn from(item: BluesnapRefundStatus) -> Self {
match item {
BluesnapRefundStatus::Success => Self::Success,
BluesnapRefundStatus::Pending => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapPaymentsResponse {
pub processing_info: ProcessingInfoResponse,
pub transaction_id: String,
pub card_transaction_type: BluesnapTxnType,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapWalletTokenResponse {
wallet_type: String,
wallet_token: Secret<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Refund {
refund_transaction_id: String,
amount: StringMajorUnit,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingInfoResponse {
pub processing_status: BluesnapProcessingStatus,
pub authorization_code: Option<String>,
pub network_transaction_id: Option<Secret<String>>,
}
impl<F, T> TryFrom<ResponseRouterData<F, BluesnapPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BluesnapPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::foreign_try_from((
item.response.card_transaction_type,
item.response.processing_info.processing_status,
))?,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct BluesnapRefundRequest {
amount: Option<StringMajorUnit>,
reason: Option<String>,
}
impl<F> TryFrom<&BluesnapRouterData<&types::RefundsRouterData<F>>> for BluesnapRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BluesnapRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
reason: item.router_data.request.reason.clone(),
amount: Some(item.amount.to_owned()),
})
}
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum BluesnapRefundStatus {
Success,
#[default]
Pending,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
refund_transaction_id: i32,
refund_status: BluesnapRefundStatus,
}
impl TryFrom<RefundsResponseRouterData<RSync, BluesnapPaymentsResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, BluesnapPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id.clone(),
refund_status: enums::RefundStatus::from(
item.response.processing_info.processing_status,
),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund_transaction_id.to_string(),
refund_status: enums::RefundStatus::from(item.response.refund_status),
}),
..item.data
})
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapWebhookBody {
pub merchant_transaction_id: String,
pub reference_number: String,
pub transaction_type: BluesnapWebhookEvents,
pub reversal_ref_num: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapWebhookObjectEventType {
transaction_type: BluesnapWebhookEvents,
cb_status: Option<BluesnapChargebackStatus>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BluesnapChargebackStatus {
#[serde(alias = "New")]
New,
#[serde(alias = "Working")]
Working,
#[serde(alias = "Closed")]
Closed,
#[serde(alias = "Completed_Lost")]
CompletedLost,
#[serde(alias = "Completed_Pending")]
CompletedPending,
#[serde(alias = "Completed_Won")]
CompletedWon,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BluesnapWebhookEvents {
Decline,
CcChargeFailed,
Charge,
Refund,
Chargeback,
ChargebackStatusChanged,
#[serde(other)]
Unknown,
}
impl TryFrom<BluesnapWebhookObjectEventType> for IncomingWebhookEvent {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(details: BluesnapWebhookObjectEventType) -> Result<Self, Self::Error> {
match details.transaction_type {
BluesnapWebhookEvents::Decline | BluesnapWebhookEvents::CcChargeFailed => {
Ok(Self::PaymentIntentFailure)
}
BluesnapWebhookEvents::Charge => Ok(Self::PaymentIntentSuccess),
BluesnapWebhookEvents::Refund => Ok(Self::RefundSuccess),
BluesnapWebhookEvents::Chargeback | BluesnapWebhookEvents::ChargebackStatusChanged => {
match details
.cb_status
.ok_or(errors::ConnectorError::WebhookEventTypeNotFound)?
{
BluesnapChargebackStatus::New | BluesnapChargebackStatus::Working => {
Ok(Self::DisputeOpened)
}
BluesnapChargebackStatus::Closed => Ok(Self::DisputeExpired),
BluesnapChargebackStatus::CompletedLost => Ok(Self::DisputeLost),
BluesnapChargebackStatus::CompletedPending => Ok(Self::DisputeChallenged),
BluesnapChargebackStatus::CompletedWon => Ok(Self::DisputeWon),
}
}
BluesnapWebhookEvents::Unknown => Ok(Self::EventNotSupported),
}
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapDisputeWebhookBody {
pub invoice_charge_amount: FloatMajorUnit,
pub currency: enums::Currency,
pub reversal_reason: Option<String>,
pub reversal_ref_num: String,
pub cb_status: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapWebhookObjectResource {
reference_number: String,
transaction_type: BluesnapWebhookEvents,
reversal_ref_num: Option<String>,
}
impl TryFrom<BluesnapWebhookObjectResource> for Value {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(details: BluesnapWebhookObjectResource) -> Result<Self, Self::Error> {
let (card_transaction_type, processing_status, transaction_id) = match details
.transaction_type
{
BluesnapWebhookEvents::Decline | BluesnapWebhookEvents::CcChargeFailed => Ok((
BluesnapTxnType::Capture,
BluesnapProcessingStatus::Fail,
details.reference_number,
)),
BluesnapWebhookEvents::Charge => Ok((
BluesnapTxnType::Capture,
BluesnapProcessingStatus::Success,
details.reference_number,
)),
BluesnapWebhookEvents::Chargeback | BluesnapWebhookEvents::ChargebackStatusChanged => {
//It won't be consumed in dispute flow, so currently does not hold any significance
return serde_json::to_value(details)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed);
}
BluesnapWebhookEvents::Refund => Ok((
BluesnapTxnType::Refund,
BluesnapProcessingStatus::Success,
details
.reversal_ref_num
.ok_or(errors::ConnectorError::WebhookResourceObjectNotFound)?,
)),
BluesnapWebhookEvents::Unknown => {
Err(errors::ConnectorError::WebhookResourceObjectNotFound)
}
}?;
let sync_struct = BluesnapPaymentsResponse {
processing_info: ProcessingInfoResponse {
processing_status,
authorization_code: None,
network_transaction_id: None,
},
transaction_id,
card_transaction_type,
};
serde_json::to_value(sync_struct)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorDetails {
pub code: String,
pub description: String,
pub error_name: Option<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapErrorResponse {
pub message: Vec<ErrorDetails>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapAuthErrorResponse {
pub error_code: String,
pub error_description: String,
pub error_name: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BluesnapErrors {
Payment(BluesnapErrorResponse),
Auth(BluesnapAuthErrorResponse),
General(String),
}
fn get_card_holder_info(
address: &AddressDetails,
email: Email,
) -> CustomResult<Option<BluesnapCardHolderInfo>, errors::ConnectorError> {
let first_name = address.get_first_name()?;
Ok(Some(BluesnapCardHolderInfo {
first_name: first_name.clone(),
last_name: address.get_last_name().unwrap_or(first_name).clone(),
email,
}))
}
impl From<ErrorDetails> for utils::ErrorCodeAndMessage {
fn from(error: ErrorDetails) -> Self {
Self {
error_code: error.code.to_string(),
error_message: error.error_name.unwrap_or(error.code),
}
}
}
fn convert_metadata_to_request_metadata(metadata: Value) -> Vec<RequestMetadata> {
let hashmap: HashMap<Option<String>, Option<Value>> =
serde_json::from_str(&metadata.to_string()).unwrap_or(HashMap::new());
let mut vector = Vec::<RequestMetadata>::new();
for (key, value) in hashmap {
vector.push(RequestMetadata {
meta_key: key,
meta_value: value.map(|field_value| field_value.to_string()),
is_visible: Some(DISPLAY_METADATA.to_string()),
});
}
vector
}
|
crates__hyperswitch_connectors__src__connectors__boku.rs
|
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::{BytesExt, OptionExt, XmlExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts::NO_ERROR_CODE,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},
};
use masking::{ExposeInterface, Mask, PeekInterface, Secret, WithType};
use ring::hmac;
use router_env::logger;
use time::OffsetDateTime;
use transformers as boku;
use crate::{
constants::{headers, UNSUPPORTED_ERROR_MESSAGE},
metrics,
types::ResponseRouterData,
utils::convert_amount,
};
#[derive(Clone)]
pub struct Boku {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Boku {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Boku {}
impl api::PaymentSession for Boku {}
impl api::ConnectorAccessToken for Boku {}
impl api::MandateSetup for Boku {}
impl api::PaymentAuthorize for Boku {}
impl api::PaymentSync for Boku {}
impl api::PaymentCapture for Boku {}
impl api::PaymentVoid for Boku {}
impl api::Refund for Boku {}
impl api::RefundExecute for Boku {}
impl api::RefundSync for Boku {}
impl api::PaymentToken for Boku {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Boku
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Boku
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let connector_auth = boku::BokuAuthType::try_from(&req.connector_auth_type)?;
let boku_url = Self::get_url(self, req, connectors)?;
let content_type = Self::common_get_content_type(self);
let connector_method = Self::get_http_method(self);
let timestamp = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
let secret_key = boku::BokuAuthType::try_from(&req.connector_auth_type)?
.key_id
.expose();
let to_sign = format!(
"{} {}\nContent-Type: {}\n{}",
connector_method, boku_url, &content_type, timestamp
);
let key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let tag = hmac::sign(&key, to_sign.as_bytes());
let signature = hex::encode(tag);
let auth_val = format!("2/HMAC_SHA256(H+SHA256(E)) timestamp={timestamp}, signature={signature} signed-headers=Content-Type, key-id={}", connector_auth.key_id.peek());
let header = vec![
(headers::CONTENT_TYPE.to_string(), content_type.into()),
(headers::AUTHORIZATION.to_string(), auth_val.into_masked()),
];
Ok(header)
}
}
impl ConnectorCommon for Boku {
fn id(&self) -> &'static str {
"boku"
}
fn common_get_content_type(&self) -> &'static str {
"text/xml;charset=utf-8"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.boku.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response_data: Result<boku::BokuErrorResponse, Report<errors::ConnectorError>> = res
.response
.parse_struct("boku::BokuErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed);
match response_data {
Ok(response) => {
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code,
message: response.message,
reason: response.reason,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Err(_) => get_xml_deserialized(res, event_builder),
}
}
}
impl ConnectorValidation for Boku {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Boku {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Boku {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Boku {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Boku".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Boku {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_http_method(&self) -> Method {
Method::Post
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let boku_url = get_country_url(
req.connector_meta_data.clone(),
self.base_url(connectors).to_string(),
)?;
Ok(format!("{boku_url}/billing/3.0/begin-single-charge"))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = boku::BokuRouterData::from((amount, req));
let connector_req = boku::BokuPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Xml(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response_data = String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let response = response_data
.parse_xml::<boku::BokuResponse>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Boku {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let boku_url = get_country_url(
req.connector_meta_data.clone(),
self.base_url(connectors).to_string(),
)?;
Ok(format!("{boku_url}/billing/3.0/query-charge"))
}
fn get_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = boku::BokuPsyncRequest::try_from(req)?;
Ok(RequestContent::Xml(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response_data = String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let response = response_data
.parse_xml::<boku::BokuResponse>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Boku {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response_data = String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let response = response_data
.parse_xml::<boku::BokuResponse>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Boku {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Boku {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let boku_url = get_country_url(
req.connector_meta_data.clone(),
self.base_url(connectors).to_string(),
)?;
Ok(format!("{boku_url}/billing/3.0/refund-charge"))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = boku::BokuRouterData::from((refund_amount, req));
let connector_req = boku::BokuRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Xml(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: boku::RefundResponse = res
.response
.parse_struct("boku RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Boku {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let boku_url = get_country_url(
req.connector_meta_data.clone(),
self.base_url(connectors).to_string(),
)?;
Ok(format!("{boku_url}/billing/3.0/query-refund"))
}
fn get_request_body(
&self,
req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = boku::BokuRsyncRequest::try_from(req)?;
Ok(RequestContent::Xml(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: boku::BokuRsyncResponse = res
.response
.parse_struct("boku BokuRsyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Boku {
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
fn get_country_url(
meta_data: Option<Secret<serde_json::Value, WithType>>,
base_url: String,
) -> Result<String, Report<errors::ConnectorError>> {
let conn_meta_data: boku::BokuMetaData = meta_data
.parse_value("Object")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(base_url.replace('$', &conn_meta_data.country.to_lowercase()))
}
// validate xml format for the error
fn get_xml_deserialized(
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
metrics::CONNECTOR_RESPONSE_DESERIALIZATION_FAILURE
.add(1, router_env::metric_attributes!(("connector", "boku")));
let response_data = String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response_data));
router_env::logger::info!(connector_response=?response_data);
// check for whether the response is in xml format
match roxmltree::Document::parse(&response_data) {
// in case of unexpected response but in xml format
Ok(_) => Err(errors::ConnectorError::ResponseDeserializationFailed)?,
// in case of unexpected response but in html or string format
Err(_) => {
logger::error!("UNEXPECTED RESPONSE FROM CONNECTOR: {}", response_data);
Ok(ErrorResponse {
status_code: res.status_code,
code: NO_ERROR_CODE.to_string(),
message: UNSUPPORTED_ERROR_MESSAGE.to_string(),
reason: Some(response_data),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
}
static BOKU_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let mut boku_supported_payment_methods = SupportedPaymentMethods::new();
boku_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Dana,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
boku_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Gcash,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
boku_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::GoPay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
boku_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::KakaoPay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
boku_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Momo,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
boku_supported_payment_methods
});
static BOKU_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Boku",
description: "Boku, Inc. is a mobile payments company that allows businesses to collect online payments through both carrier billing and mobile wallets.",
connector_type: enums::HyperswitchConnectorCategory::AlternativePaymentMethod,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static BOKU_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Boku {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&BOKU_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*BOKU_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&BOKU_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__boku__transformers.rs
|
use std::fmt;
use common_enums::enums;
use common_utils::{request::Method, types::MinorUnit};
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{self, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use url::Url;
use uuid::Uuid;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, AddressDetailsData, RouterData as _},
};
#[derive(Debug, Serialize)]
pub struct BokuRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for BokuRouterData<T> {
fn from((amount, router_data): (MinorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum BokuPaymentsRequest {
BeginSingleCharge(SingleChargeData),
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SingleChargeData {
total_amount: MinorUnit,
currency: String,
country: String,
merchant_id: Secret<String>,
merchant_transaction_id: Secret<String>,
merchant_request_id: String,
merchant_item_description: String,
notification_url: Option<String>,
payment_method: String,
charge_type: String,
hosted: Option<BokuHostedData>,
}
#[derive(Debug, Clone, Serialize)]
pub enum BokuPaymentType {
Dana,
Momo,
Gcash,
GoPay,
Kakaopay,
}
impl fmt::Display for BokuPaymentType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Dana => write!(f, "Dana"),
Self::Momo => write!(f, "Momo"),
Self::Gcash => write!(f, "Gcash"),
Self::GoPay => write!(f, "GoPay"),
Self::Kakaopay => write!(f, "Kakaopay"),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub enum BokuChargeType {
Hosted,
}
impl fmt::Display for BokuChargeType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Hosted => write!(f, "hosted"),
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "kebab-case")]
struct BokuHostedData {
forward_url: String,
}
impl TryFrom<&BokuRouterData<&types::PaymentsAuthorizeRouterData>> for BokuPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BokuRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Wallet(wallet_data) => Self::try_from((item, &wallet_data)),
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("boku"),
))?
}
}
}
}
impl
TryFrom<(
&BokuRouterData<&types::PaymentsAuthorizeRouterData>,
&WalletData,
)> for BokuPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (
&BokuRouterData<&types::PaymentsAuthorizeRouterData>,
&WalletData,
),
) -> Result<Self, Self::Error> {
let (item_router_data, wallet_data) = value;
let item = item_router_data.router_data;
let address = item.get_billing_address()?;
let country = address.get_country()?.to_string();
let payment_method = get_wallet_type(wallet_data)?;
let hosted = get_hosted_data(item);
let auth_type = BokuAuthType::try_from(&item.connector_auth_type)?;
let merchant_item_description = item.get_description()?;
let payment_data = SingleChargeData {
total_amount: item_router_data.amount,
currency: item.request.currency.to_string(),
country,
merchant_id: auth_type.merchant_id,
merchant_transaction_id: Secret::new(item.payment_id.to_string()),
merchant_request_id: Uuid::new_v4().to_string(),
merchant_item_description,
notification_url: item.request.webhook_url.clone(),
payment_method,
charge_type: BokuChargeType::Hosted.to_string(),
hosted,
};
Ok(Self::BeginSingleCharge(payment_data))
}
}
fn get_wallet_type(wallet_data: &WalletData) -> Result<String, errors::ConnectorError> {
match wallet_data {
WalletData::DanaRedirect { .. } => Ok(BokuPaymentType::Dana.to_string()),
WalletData::MomoRedirect { .. } => Ok(BokuPaymentType::Momo.to_string()),
WalletData::GcashRedirect { .. } => Ok(BokuPaymentType::Gcash.to_string()),
WalletData::GoPayRedirect { .. } => Ok(BokuPaymentType::GoPay.to_string()),
WalletData::KakaoPayRedirect { .. } => Ok(BokuPaymentType::Kakaopay.to_string()),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::GooglePay(_)
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("boku"),
)),
}
}
pub struct BokuAuthType {
pub(super) merchant_id: Secret<String>,
pub(super) key_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BokuAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
merchant_id: key1.to_owned(),
key_id: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename = "query-charge-request")]
#[serde(rename_all = "kebab-case")]
pub struct BokuPsyncRequest {
country: String,
merchant_id: Secret<String>,
merchant_transaction_id: Secret<String>,
}
impl TryFrom<&types::PaymentsSyncRouterData> for BokuPsyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let address = item.get_billing_address()?;
let country = address.get_country()?.to_string();
let auth_type = BokuAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
country,
merchant_id: auth_type.merchant_id,
merchant_transaction_id: Secret::new(item.payment_id.to_string()),
})
}
}
// Connector Meta Data
#[derive(Debug, Clone, Deserialize)]
pub struct BokuMetaData {
pub(super) country: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum BokuResponse {
BeginSingleChargeResponse(BokuPaymentsResponse),
QueryChargeResponse(BokuPsyncResponse),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct BokuPaymentsResponse {
charge_status: String, // xml parse only string to fields
charge_id: String,
hosted: Option<HostedUrlResponse>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct HostedUrlResponse {
redirect_url: Option<Url>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename = "query-charge-response")]
#[serde(rename_all = "kebab-case")]
pub struct BokuPsyncResponse {
charges: ChargeResponseData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct ChargeResponseData {
charge: SingleChargeResponseData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SingleChargeResponseData {
charge_status: String,
charge_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, BokuResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BokuResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, transaction_id, redirection_data) = match item.response {
BokuResponse::BeginSingleChargeResponse(response) => get_authorize_response(response),
BokuResponse::QueryChargeResponse(response) => get_psync_response(response),
}?;
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
fn get_response_status(status: String) -> enums::AttemptStatus {
match status.as_str() {
"Success" => enums::AttemptStatus::Charged,
"Failure" => enums::AttemptStatus::Failure,
_ => enums::AttemptStatus::Pending,
}
}
fn get_authorize_response(
response: BokuPaymentsResponse,
) -> Result<(enums::AttemptStatus, String, Option<RedirectForm>), errors::ConnectorError> {
let status = get_response_status(response.charge_status);
let redirection_data = match response.hosted {
Some(hosted_value) => Ok(hosted_value
.redirect_url
.map(|url| RedirectForm::from((url, Method::Get)))),
None => Err(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "redirect_url",
}),
}?;
Ok((status, response.charge_id, redirection_data))
}
fn get_psync_response(
response: BokuPsyncResponse,
) -> Result<(enums::AttemptStatus, String, Option<RedirectForm>), errors::ConnectorError> {
let status = get_response_status(response.charges.charge.charge_status);
Ok((status, response.charges.charge.charge_id, None))
}
// REFUND :
#[derive(Debug, Clone, Serialize)]
#[serde(rename = "refund-charge-request")]
pub struct BokuRefundRequest {
refund_amount: MinorUnit,
merchant_id: Secret<String>,
merchant_request_id: String,
merchant_refund_id: Secret<String>,
charge_id: String,
reason_code: String,
}
#[derive(Debug, Clone, Serialize)]
pub enum BokuRefundReasonCode {
NonFulfillment,
}
impl fmt::Display for BokuRefundReasonCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NonFulfillment => write!(f, "8"),
}
}
}
impl<F> TryFrom<&BokuRouterData<&RefundsRouterData<F>>> for BokuRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &BokuRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let auth_type = BokuAuthType::try_from(&item.router_data.connector_auth_type)?;
let payment_data = Self {
refund_amount: item.amount,
merchant_id: auth_type.merchant_id,
merchant_refund_id: Secret::new(item.router_data.request.refund_id.to_string()),
merchant_request_id: Uuid::new_v4().to_string(),
charge_id: item
.router_data
.request
.connector_transaction_id
.to_string(),
reason_code: BokuRefundReasonCode::NonFulfillment.to_string(),
};
Ok(payment_data)
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename = "refund-charge-response")]
pub struct RefundResponse {
charge_id: String,
refund_status: String,
}
fn get_refund_status(status: String) -> enums::RefundStatus {
match status.as_str() {
"Success" => enums::RefundStatus::Success,
"Failure" => enums::RefundStatus::Failure,
_ => enums::RefundStatus::Pending,
}
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.charge_id,
refund_status: get_refund_status(item.response.refund_status),
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename = "query-refund-request")]
#[serde(rename_all = "kebab-case")]
pub struct BokuRsyncRequest {
country: String,
merchant_id: Secret<String>,
merchant_transaction_id: Secret<String>,
}
impl TryFrom<&types::RefundSyncRouterData> for BokuRsyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
let address = item.get_billing_address()?;
let country = address.get_country()?.to_string();
let auth_type = BokuAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
country,
merchant_id: auth_type.merchant_id,
merchant_transaction_id: Secret::new(item.payment_id.to_string()),
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename = "query-refund-response")]
#[serde(rename_all = "kebab-case")]
pub struct BokuRsyncResponse {
refunds: RefundResponseData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct RefundResponseData {
refund: SingleRefundResponseData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SingleRefundResponseData {
refund_status: String, // quick-xml only parse string as a field
refund_id: String,
}
impl TryFrom<RefundsResponseRouterData<RSync, BokuRsyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, BokuRsyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refunds.refund.refund_id,
refund_status: get_refund_status(item.response.refunds.refund.refund_status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct BokuErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
}
fn get_hosted_data(item: &types::PaymentsAuthorizeRouterData) -> Option<BokuHostedData> {
item.request
.router_return_url
.clone()
.map(|url| BokuHostedData { forward_url: url })
}
|
crates__hyperswitch_connectors__src__connectors__braintree.rs
|
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::IncomingWebhookEvent;
use base64::Engine;
use common_enums::{enums, CallConnectorAction, PaymentAction};
use common_utils::{
consts::BASE64_ENGINE,
crypto,
errors::{CustomResult, ParsingError},
ext_traits::{BytesExt, XmlExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{
AmountConvertor, StringMajorUnit, StringMajorUnitForConnector, StringMinorUnit,
StringMinorUnitForConnector,
},
};
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::{
api::ApplicationResponse,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
mandate_revoke::MandateRevoke,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
CompleteAuthorize,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, MandateRevokeRequestData,
PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData,
PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData,
SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, PaymentsResponseData,
RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsSessionRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
disputes::DisputePayload,
errors,
events::connector_api_logs::ConnectorEvent,
types::{
MandateRevokeType, PaymentsAuthorizeType, PaymentsCaptureType,
PaymentsCompleteAuthorizeType, PaymentsSessionType, PaymentsSyncType, PaymentsVoidType,
RefundExecuteType, RefundSyncType, Response, TokenizationType,
},
webhooks::{
IncomingWebhook, IncomingWebhookFlowError, IncomingWebhookRequestDetails, WebhookContext,
},
};
use masking::{ExposeInterface, Mask, PeekInterface, Secret};
use ring::hmac;
use router_env::logger;
use sha1::{Digest, Sha1};
use transformers::{self as braintree, get_status};
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{
self, convert_amount, is_mandate_supported, PaymentMethodDataType,
PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
},
};
#[derive(Clone)]
pub struct Braintree {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
amount_converter_webhooks: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Braintree {
pub const fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
amount_converter_webhooks: &StringMinorUnitForConnector,
}
}
}
pub const BRAINTREE_VERSION: &str = "Braintree-Version";
pub const BRAINTREE_VERSION_VALUE: &str = "2019-01-01";
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Braintree
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
BRAINTREE_VERSION.to_string(),
BRAINTREE_VERSION_VALUE.to_string().into(),
),
];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Braintree {
fn id(&self) -> &'static str {
"braintree"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.braintree.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = braintree::BraintreeAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_key = format!("{}:{}", auth.public_key.peek(), auth.private_key.peek());
let auth_header = format!("Basic {}", BASE64_ENGINE.encode(auth_key));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth_header.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<braintree::ErrorResponses, Report<ParsingError>> =
res.response.parse_struct("Braintree Error Response");
match response {
Ok(braintree::ErrorResponses::BraintreeApiErrorResponse(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_object = response.api_error_response.errors;
let error = error_object.errors.first().or(error_object
.transaction
.as_ref()
.and_then(|transaction_error| {
transaction_error.errors.first().or(transaction_error
.credit_card
.as_ref()
.and_then(|credit_card_error| credit_card_error.errors.first()))
}));
let (code, message) = error.map_or(
(NO_ERROR_CODE.to_string(), NO_ERROR_MESSAGE.to_string()),
|error| (error.code.clone(), error.message.clone()),
);
Ok(ErrorResponse {
status_code: res.status_code,
code,
message,
reason: Some(response.api_error_response.message),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Ok(braintree::ErrorResponses::BraintreeErrorResponse(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: Some(response.errors),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Err(error_msg) => {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
logger::error!(deserialization_error =? error_msg);
utils::handle_json_response_deserialization_failure(res, "braintree")
}
}
}
}
impl ConnectorValidation for Braintree {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: hyperswitch_domain_models::payment_method_data::PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::ApplePayThirdPartySdk,
PaymentMethodDataType::ApplePay,
]);
is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl api::Payment for Braintree {}
impl api::PaymentAuthorize for Braintree {}
impl api::PaymentSync for Braintree {}
impl api::PaymentVoid for Braintree {}
impl api::PaymentCapture for Braintree {}
impl api::PaymentsCompleteAuthorize for Braintree {}
impl api::PaymentSession for Braintree {}
impl api::ConnectorAccessToken for Braintree {}
impl api::ConnectorMandateRevoke for Braintree {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Braintree {
// Not Implemented (R)
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Braintree {
fn get_headers(
&self,
req: &PaymentsSessionRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsSessionRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &PaymentsSessionRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let metadata: braintree::BraintreeMeta =
braintree::BraintreeMeta::try_from(&req.connector_meta_data)?;
let connector_req = braintree::BraintreeClientTokenRequest::try_from(metadata)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsSessionRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsSessionType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSessionType::get_headers(self, req, connectors)?)
.set_body(PaymentsSessionType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSessionRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSessionRouterData, errors::ConnectorError>
where
PaymentsResponseData: Clone,
{
let response: braintree::BraintreeSessionResponse = res
.response
.parse_struct("BraintreeSessionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
utils::ForeignTryFrom::foreign_try_from((
crate::types::PaymentsSessionResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
data.clone(),
))
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::PaymentToken for Braintree {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Braintree
{
fn get_headers(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = transformers::BraintreeTokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(TokenizationType::get_headers(self, req, connectors)?)
.set_body(TokenizationType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &TokenizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<TokenizationRouterData, errors::ConnectorError>
where
PaymentsResponseData: Clone,
{
let response: transformers::BraintreeTokenResponse = res
.response
.parse_struct("BraintreeTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::MandateSetup for Braintree {}
#[allow(dead_code)]
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Braintree
{
// Not Implemented (R)
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Braintree".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Braintree {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?;
let connector_req =
transformers::BraintreeCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
.set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: transformers::BraintreeCaptureResponse = res
.response
.parse_struct("Braintree PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Braintree {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = transformers::BraintreePSyncRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.set_body(PaymentsSyncType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: transformers::BraintreePSyncResponse = res
.response
.parse_struct("Braintree PaymentSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Braintree {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?;
let connector_req: transformers::BraintreePaymentsRequest =
transformers::BraintreePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
match data.request.is_auto_capture()? {
true => {
let response: transformers::BraintreePaymentsResponse = res
.response
.parse_struct("Braintree PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
false => {
let response: transformers::BraintreeAuthResponse = res
.response
.parse_struct("Braintree AuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>
for Braintree
{
fn get_headers(
&self,
req: &MandateRevokeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
_req: &MandateRevokeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn build_request(
&self,
req: &MandateRevokeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&MandateRevokeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(MandateRevokeType::get_headers(self, req, connectors)?)
.set_body(MandateRevokeType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn get_request_body(
&self,
req: &MandateRevokeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = transformers::BraintreeRevokeMandateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
&self,
data: &MandateRevokeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<MandateRevokeRouterData, errors::ConnectorError> {
let response: transformers::BraintreeRevokeMandateResponse = res
.response
.parse_struct("BraintreeRevokeMandateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Braintree {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = transformers::BraintreeCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: transformers::BraintreeCancelResponse = res
.response
.parse_struct("Braintree VoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::Refund for Braintree {}
impl api::RefundExecute for Braintree {}
impl api::RefundSync for Braintree {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Braintree {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?;
let connector_req = transformers::BraintreeRefundRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: transformers::BraintreeRefundResponse = res
.response
.parse_struct("Braintree RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Braintree {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = transformers::BraintreeRSyncRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundSyncType::get_headers(self, req, connectors)?)
.set_body(RefundSyncType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RouterData<RSync, RefundsData, RefundsResponseData>, errors::ConnectorError>
{
let response: transformers::BraintreeRSyncResponse = res
.response
.parse_struct("Braintree RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Braintree {
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha1))
}
fn get_webhook_source_verification_signature(
&self,
request: &IncomingWebhookRequestDetails<'_>,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let notif_item = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let signature_pairs: Vec<(&str, &str)> = notif_item
.bt_signature
.split('&')
.collect::<Vec<&str>>()
.into_iter()
.map(|pair| pair.split_once('|').unwrap_or(("", "")))
.collect::<Vec<(_, _)>>();
let merchant_secret = connector_webhook_secrets
.additional_secret //public key
.clone()
.ok_or(errors::ConnectorError::WebhookVerificationSecretNotFound)?;
let signature = get_matching_webhook_signature(signature_pairs, merchant_secret.expose())
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)?;
Ok(signature.as_bytes().to_vec())
}
fn get_webhook_source_verification_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let notify = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let message = notify.bt_payload.to_string();
Ok(message.into_bytes())
}
async fn verify_webhook_source(
&self,
request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_label,
connector_webhook_details,
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let signature = self
.get_webhook_source_verification_signature(request, &connector_webhook_secrets)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
let message = self
.get_webhook_source_verification_message(
request,
merchant_id,
&connector_webhook_secrets,
)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let sha1_hash_key = Sha1::digest(&connector_webhook_secrets.secret);
let signing_key = hmac::Key::new(
hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
sha1_hash_key.as_slice(),
);
let signed_messaged = hmac::sign(&signing_key, &message);
let payload_sign: String = hex::encode(signed_messaged);
Ok(payload_sign.as_bytes().eq(&signature))
}
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif = get_webhook_object_from_body(_request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let response = decode_webhook_payload(notif.bt_payload.replace('\n', "").as_bytes())?;
match response.dispute {
Some(dispute_data) => Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
dispute_data.transaction.id,
),
)),
None => Err(report!(errors::ConnectorError::WebhookReferenceIdNotFound)),
}
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let response = decode_webhook_payload(notif.bt_payload.replace('\n', "").as_bytes())?;
Ok(get_status(response.kind.as_str()))
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let response = decode_webhook_payload(notif.bt_payload.replace('\n', "").as_bytes())?;
Ok(Box::new(response))
}
fn get_webhook_api_response(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_error_kind: Option<IncomingWebhookFlowError>,
) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> {
Ok(ApplicationResponse::TextPlain("[accepted]".to_string()))
}
fn get_dispute_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<DisputePayload, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let response = decode_webhook_payload(notif.bt_payload.replace('\n', "").as_bytes())?;
match response.dispute {
Some(dispute_data) => Ok(DisputePayload {
amount: convert_amount(
self.amount_converter_webhooks,
dispute_data.amount_disputed,
dispute_data.currency_iso_code,
)?,
currency: dispute_data.currency_iso_code,
dispute_stage: transformers::get_dispute_stage(dispute_data.kind.as_str())?,
connector_dispute_id: dispute_data.id,
connector_reason: dispute_data.reason,
connector_reason_code: dispute_data.reason_code,
challenge_required_by: dispute_data.reply_by_date,
connector_status: dispute_data.status,
created_at: dispute_data.created_at,
updated_at: dispute_data.updated_at,
}),
None => Err(errors::ConnectorError::WebhookResourceObjectNotFound)?,
}
}
}
fn get_matching_webhook_signature(
signature_pairs: Vec<(&str, &str)>,
secret: String,
) -> Option<String> {
for (public_key, signature) in signature_pairs {
if *public_key == secret {
return Some(signature.to_string());
}
}
None
}
fn get_webhook_object_from_body(
body: &[u8],
) -> CustomResult<transformers::BraintreeWebhookResponse, ParsingError> {
serde_urlencoded::from_bytes::<transformers::BraintreeWebhookResponse>(body)
.change_context(ParsingError::StructParseFailure("BraintreeWebhookResponse"))
}
fn decode_webhook_payload(
payload: &[u8],
) -> CustomResult<transformers::Notification, errors::ConnectorError> {
let decoded_response = BASE64_ENGINE
.decode(payload)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let xml_response = String::from_utf8(decoded_response)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
xml_response
.parse_xml::<transformers::Notification>()
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)
}
impl ConnectorRedirectResponse for Braintree {
fn get_flow_type(
&self,
_query_params: &str,
json_payload: Option<serde_json::Value>,
action: PaymentAction,
) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
match action {
PaymentAction::PSync => match json_payload {
Some(payload) => {
let redirection_response: transformers::BraintreeRedirectionResponse =
serde_json::from_value(payload).change_context(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "redirection_response",
},
)?;
let braintree_payload =
serde_json::from_str::<transformers::BraintreeThreeDsErrorResponse>(
&redirection_response.authentication_response,
);
let (error_code, error_message) = match braintree_payload {
Ok(braintree_response_payload) => (
braintree_response_payload.code,
braintree_response_payload.message,
),
Err(_) => (
NO_ERROR_CODE.to_string(),
redirection_response.authentication_response,
),
};
Ok(CallConnectorAction::StatusUpdate {
status: enums::AttemptStatus::AuthenticationFailed,
error_code: Some(error_code),
error_message: Some(error_message),
})
}
None => Ok(CallConnectorAction::Avoid),
},
PaymentAction::CompleteAuthorize
| PaymentAction::PaymentAuthenticateCompleteAuthorize => {
Ok(CallConnectorAction::Trigger)
}
}
}
}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Braintree
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?;
let connector_req =
transformers::BraintreePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
match PaymentsCompleteAuthorizeRequestData::is_auto_capture(&data.request)? {
true => {
let response: transformers::BraintreeCompleteChargeResponse = res
.response
.parse_struct("Braintree PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
false => {
let response: transformers::BraintreeCompleteAuthResponse = res
.response
.parse_struct("Braintree AuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
static BRAINTREE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
];
let mut braintree_supported_payment_methods = SupportedPaymentMethods::new();
braintree_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
braintree_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
braintree_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
braintree_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
braintree_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Paypal,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
braintree_supported_payment_methods
});
static BRAINTREE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Braintree",
description:
"Braintree, a PayPal service, offers a full-stack payment platform that simplifies accepting payments in your app or website, supporting various payment methods including credit cards and PayPal.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static BRAINTREE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] =
[enums::EventClass::Payments, enums::EventClass::Refunds];
impl ConnectorSpecifications for Braintree {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&BRAINTREE_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*BRAINTREE_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&BRAINTREE_SUPPORTED_WEBHOOK_FLOWS)
}
fn is_sdk_client_token_generation_enabled(&self) -> bool {
true
}
fn supported_payment_method_types_for_sdk_client_token_generation(
&self,
) -> Vec<enums::PaymentMethodType> {
vec![
enums::PaymentMethodType::ApplePay,
enums::PaymentMethodType::GooglePay,
enums::PaymentMethodType::Paypal,
]
}
}
|
crates__hyperswitch_connectors__src__connectors__braintree__transformers.rs
|
use api_models::{
payments as payment_types,
payments::{ApplePaySessionResponse, SessionToken},
webhooks::IncomingWebhookEvent,
};
use common_enums::enums;
use common_utils::{
ext_traits::{OptionExt, ValueExt},
pii,
types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{CompleteAuthorizeData, MandateRevokeRequestData, ResponseId},
router_response_types::{
MandateReference, MandateRevokeResponseData, PaymentsResponseData, RedirectForm,
RefundsResponseData,
},
types::{self, RefundsRouterData},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use strum::Display;
use time::PrimitiveDateTime;
use crate::{
types::{
PaymentsCaptureResponseRouterData, PaymentsResponseRouterData,
PaymentsSessionResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
},
unimplemented_payment_method,
utils::{
self, ForeignTryFrom, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
RefundsRequestData, RouterData as _,
},
};
pub const CHANNEL_CODE: &str = "HyperSwitchBT_Ecom";
pub const CLIENT_TOKEN_MUTATION: &str = "mutation createClientToken($input: CreateClientTokenInput!) { createClientToken(input: $input) { clientToken}}";
pub const TOKENIZE_CREDIT_CARD: &str = "mutation tokenizeCreditCard($input: TokenizeCreditCardInput!) { tokenizeCreditCard(input: $input) { clientMutationId paymentMethod { id } } }";
pub const CHARGE_CREDIT_CARD_MUTATION: &str = "mutation ChargeCreditCard($input: ChargeCreditCardInput!) { chargeCreditCard(input: $input) { transaction { id legacyId createdAt amount { value currencyCode } status } } }";
pub const AUTHORIZE_CREDIT_CARD_MUTATION: &str = "mutation authorizeCreditCard($input: AuthorizeCreditCardInput!) { authorizeCreditCard(input: $input) { transaction { id legacyId amount { value currencyCode } status } } }";
pub const CAPTURE_TRANSACTION_MUTATION: &str = "mutation captureTransaction($input: CaptureTransactionInput!) { captureTransaction(input: $input) { clientMutationId transaction { id legacyId amount { value currencyCode } status } } }";
pub const VOID_TRANSACTION_MUTATION: &str = "mutation voidTransaction($input: ReverseTransactionInput!) { reverseTransaction(input: $input) { clientMutationId reversal { ... on Transaction { id legacyId amount { value currencyCode } status } } } }";
pub const REFUND_TRANSACTION_MUTATION: &str = "mutation refundTransaction($input: RefundTransactionInput!) { refundTransaction(input: $input) {clientMutationId refund { id legacyId amount { value currencyCode } status } } }";
pub const AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION: &str="mutation authorizeCreditCard($input: AuthorizeCreditCardInput!) { authorizeCreditCard(input: $input) { transaction { id status createdAt paymentMethod { id } } } }";
pub const CHARGE_AND_VAULT_TRANSACTION_MUTATION: &str ="mutation ChargeCreditCard($input: ChargeCreditCardInput!) { chargeCreditCard(input: $input) { transaction { id status createdAt paymentMethod { id } } } }";
pub const DELETE_PAYMENT_METHOD_FROM_VAULT_MUTATION: &str = "mutation deletePaymentMethodFromVault($input: DeletePaymentMethodFromVaultInput!) { deletePaymentMethodFromVault(input: $input) { clientMutationId } }";
pub const TRANSACTION_QUERY: &str = "query($input: TransactionSearchInput!) { search { transactions(input: $input) { edges { node { id status } } } } }";
pub const REFUND_QUERY: &str = "query($input: RefundSearchInput!) { search { refunds(input: $input, first: 1) { edges { node { id status createdAt amount { value currencyCode } orderId } } } } }";
pub const CHARGE_GOOGLE_PAY_MUTATION: &str = "mutation ChargeGPay($input: ChargePaymentMethodInput!) { chargePaymentMethod(input: $input) { transaction { id status amount { value currencyCode } } } }";
pub const AUTHORIZE_GOOGLE_PAY_MUTATION: &str = "mutation authorizeGPay($input: AuthorizePaymentMethodInput!) { authorizePaymentMethod(input: $input) { transaction { id legacyId amount { value currencyCode } status } } }";
pub const CHARGE_APPLE_PAY_MUTATION: &str = "mutation ChargeApplepay($input: ChargePaymentMethodInput!) { chargePaymentMethod(input: $input) { transaction { id status amount { value currencyCode } } } }";
pub const AUTHORIZE_APPLE_PAY_MUTATION: &str = "mutation authorizeApplepay($input: AuthorizePaymentMethodInput!) { authorizePaymentMethod(input: $input) { transaction { id legacyId amount { value currencyCode } status } } }";
pub const CHARGE_AND_VAULT_APPLE_PAY_MUTATION: &str = "mutation ChargeApplepay($input: ChargePaymentMethodInput!) { chargePaymentMethod(input: $input) { transaction { id status amount { value currencyCode } paymentMethod { id } } } }";
pub const AUTHORIZE_AND_VAULT_APPLE_PAY_MUTATION: &str = "mutation authorizeApplepay($input: AuthorizePaymentMethodInput!) { authorizePaymentMethod(input: $input) { transaction { id legacyId amount { value currencyCode } status paymentMethod { id } } } }";
pub const CHARGE_PAYPAL_MUTATION: &str = "mutation ChargePaypal($input: ChargePaymentMethodInput!) { chargePaymentMethod(input: $input) { transaction { id status amount { value currencyCode } } } }";
pub const AUTHORIZE_PAYPAL_MUTATION: &str = "mutation authorizePaypal($input: AuthorizePaymentMethodInput!) { authorizePaymentMethod(input: $input) { transaction { id legacyId amount { value currencyCode } status } } }";
pub const TOKENIZE_NETWORK_TOKEN: &str = "mutation tokenizeNetworkToken($input: TokenizeNetworkTokenInput!) { tokenizeNetworkToken(input: $input) { clientMutationId paymentMethod { id } } }";
pub type CardPaymentRequest = GenericBraintreeRequest<VariablePaymentInput>;
pub type MandatePaymentRequest = GenericBraintreeRequest<VariablePaymentInput>;
pub type BraintreeClientTokenRequest = GenericBraintreeRequest<VariableClientTokenInput>;
pub type BraintreeTokenRequest = GenericBraintreeRequest<VariableInput>;
pub type BraintreeCaptureRequest = GenericBraintreeRequest<VariableCaptureInput>;
pub type BraintreeRefundRequest = GenericBraintreeRequest<BraintreeRefundVariables>;
pub type BraintreePSyncRequest = GenericBraintreeRequest<PSyncInput>;
pub type BraintreeRSyncRequest = GenericBraintreeRequest<RSyncInput>;
pub type BraintreeApplePayTokenizeRequest = GenericBraintreeRequest<VariablePaymentInput>;
pub type BraintreeRefundResponse = GenericBraintreeResponse<RefundResponse>;
pub type BraintreeCaptureResponse = GenericBraintreeResponse<CaptureResponse>;
pub type BraintreePSyncResponse = GenericBraintreeResponse<PSyncResponse>;
pub type VariablePaymentInput = GenericVariableInput<PaymentInput>;
pub type VariableClientTokenInput = GenericVariableInput<InputClientTokenData>;
pub type VariableInput = GenericVariableInput<InputData>;
pub type VariableCaptureInput = GenericVariableInput<CaptureInputData>;
pub type BraintreeRefundVariables = GenericVariableInput<BraintreeRefundInput>;
pub type PSyncInput = GenericVariableInput<TransactionSearchInput>;
pub type RSyncInput = GenericVariableInput<RefundSearchInput>;
pub type BraintreeWalletRequest = GenericBraintreeRequest<GenericVariableInput<WalletPaymentInput>>;
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkTokenData {
cryptogram: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
e_commerce_indicator: Option<String>,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
number: cards::CardNumber,
origin_details: NetworkTokenOriginDetailsInput,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkTokenOriginDetailsInput {
origin: NetworkTokenOrigin,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NetworkTokenOrigin {
ApplePay,
GooglePay,
NetworkToken,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletTransactionBody {
amount: StringMajorUnit,
merchant_account_id: Secret<String>,
order_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
customer_details: Option<CustomerBody>,
#[serde(skip_serializing_if = "Option::is_none")]
vault_payment_method_after_transacting: Option<TransactionTiming>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletPaymentInput {
payment_method_id: Secret<String>,
transaction: WalletTransactionBody,
}
#[derive(Debug, Clone, Serialize)]
pub struct GenericBraintreeRequest<T> {
query: String,
variables: T,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum GenericBraintreeResponse<T> {
SuccessResponse(Box<T>),
ErrorResponse(Box<ErrorResponse>),
}
#[derive(Debug, Clone, Serialize)]
pub struct GenericVariableInput<T> {
input: T,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BraintreeApiErrorResponse {
pub api_error_response: ApiErrorResponse,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ErrorsObject {
pub errors: Vec<ErrorObject>,
pub transaction: Option<TransactionError>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionError {
pub errors: Vec<ErrorObject>,
pub credit_card: Option<CreditCardError>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CreditCardError {
pub errors: Vec<ErrorObject>,
}
#[derive(Debug, Serialize)]
pub struct BraintreeRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(StringMajorUnit, T)> for BraintreeRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (StringMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ErrorObject {
pub code: String,
pub message: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BraintreeErrorResponse {
pub errors: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum ErrorResponses {
BraintreeApiErrorResponse(Box<BraintreeApiErrorResponse>),
BraintreeErrorResponse(Box<BraintreeErrorResponse>),
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ApiErrorResponse {
pub message: String,
pub errors: ErrorsObject,
}
pub struct BraintreeAuthType {
pub(super) public_key: Secret<String>,
pub(super) private_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BraintreeAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
api_secret,
key1: _merchant_id,
} = item
{
Ok(Self {
public_key: api_key.to_owned(),
private_key: api_secret.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInput {
payment_method_id: Secret<String>,
transaction: TransactionBody,
#[serde(skip_serializing_if = "Option::is_none")]
options: Option<CreditCardTransactionOptions>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum BraintreePaymentsRequest {
Card(CardPaymentRequest),
CardThreeDs(BraintreeClientTokenRequest),
Mandate(MandatePaymentRequest),
Wallet(BraintreeWalletRequest),
Session(BraintreeClientTokenRequest),
}
#[derive(Debug, Deserialize)]
pub struct BraintreeMeta {
merchant_account_id: Secret<String>,
merchant_config_currency: enums::Currency,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for BraintreeMeta {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomerBody {
email: pii::Email,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RegularTransactionBody {
amount: StringMajorUnit,
merchant_account_id: Secret<String>,
channel: String,
#[serde(skip_serializing_if = "Option::is_none")]
customer_details: Option<CustomerBody>,
order_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VaultTransactionBody {
amount: StringMajorUnit,
merchant_account_id: Secret<String>,
vault_payment_method_after_transacting: TransactionTiming,
#[serde(skip_serializing_if = "Option::is_none")]
customer_details: Option<CustomerBody>,
order_id: String,
payment_initiator: PaymentInitiatorType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MandateTransactionBody {
amount: StringMajorUnit,
merchant_account_id: Secret<String>,
channel: String,
order_id: String,
payment_initiator: PaymentInitiatorType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentInitiatorType {
Unscheduled,
RecurringFirst,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum TransactionBody {
Regular(RegularTransactionBody),
Vault(VaultTransactionBody),
Mandate(MandateTransactionBody),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum VaultTiming {
Always,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionTiming {
when: VaultTiming,
}
impl
TryFrom<(
&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
String,
BraintreeMeta,
)> for MandatePaymentRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, connector_mandate_id, metadata): (
&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
String,
BraintreeMeta,
),
) -> Result<Self, Self::Error> {
let (query, transaction_body) = (
match item.router_data.request.is_auto_capture()? {
true => CHARGE_CREDIT_CARD_MUTATION.to_string(),
false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(),
},
TransactionBody::Mandate(MandateTransactionBody {
amount: item.amount.to_owned(),
merchant_account_id: metadata.merchant_account_id,
channel: CHANNEL_CODE.to_string(),
order_id: item.router_data.connector_request_reference_id.clone(),
payment_initiator: PaymentInitiatorType::Unscheduled,
}),
);
Ok(Self {
query,
variables: VariablePaymentInput {
input: PaymentInput {
payment_method_id: connector_mandate_id.into(),
transaction: transaction_body,
options: None,
},
},
})
}
}
impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>>
for BraintreePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let metadata: BraintreeMeta = if let (
Some(merchant_account_id),
Some(merchant_config_currency),
) = (
item.router_data.request.merchant_account_id.clone(),
item.router_data.request.merchant_config_currency,
) {
router_env::logger::info!(
"BRAINTREE: Picking merchant_account_id and merchant_config_currency from payments request"
);
BraintreeMeta {
merchant_account_id,
merchant_config_currency,
}
} else {
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?
};
utils::validate_currency(
item.router_data.request.currency,
Some(metadata.merchant_config_currency),
)?;
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(_) => {
if item.router_data.is_three_ds()
&& item.router_data.request.authentication_data.is_none()
{
Ok(Self::CardThreeDs(BraintreeClientTokenRequest::try_from(
metadata,
)?))
} else {
Ok(Self::Card(CardPaymentRequest::try_from((item, metadata))?))
}
}
PaymentMethodData::MandatePayment => {
let connector_mandate_id = item.router_data.request.connector_mandate_id().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
},
)?;
Ok(Self::Mandate(MandatePaymentRequest::try_from((
item,
connector_mandate_id,
metadata,
))?))
}
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletData::GooglePayThirdPartySdk(ref req_wallet) => {
let payment_method_id = &req_wallet.token;
let query = match item.router_data.request.is_auto_capture()? {
true => CHARGE_GOOGLE_PAY_MUTATION.to_string(),
false => AUTHORIZE_GOOGLE_PAY_MUTATION.to_string(),
};
Ok(Self::Wallet(BraintreeWalletRequest {
query,
variables: GenericVariableInput {
input: WalletPaymentInput {
payment_method_id: payment_method_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "google_pay token",
},
)?,
transaction: WalletTransactionBody {
amount: item.amount.clone(),
merchant_account_id: metadata.merchant_account_id,
order_id: item
.router_data
.connector_request_reference_id
.clone(),
customer_details: None,
vault_payment_method_after_transacting: None,
},
},
},
}))
}
WalletData::ApplePayThirdPartySdk(ref req_wallet) => {
let payment_method_id = &req_wallet.token;
let is_mandate = item.router_data.request.is_mandate_payment();
let is_auto_capture = item.router_data.request.is_auto_capture()?;
let (query, customer_details, vault_payment_method_after_transacting) =
if is_mandate {
(
if is_auto_capture {
CHARGE_AND_VAULT_APPLE_PAY_MUTATION.to_string()
} else {
AUTHORIZE_AND_VAULT_APPLE_PAY_MUTATION.to_string()
},
item.router_data
.get_billing_email()
.ok()
.map(|email| CustomerBody { email }),
Some(TransactionTiming {
when: VaultTiming::Always,
}),
)
} else {
(
if is_auto_capture {
CHARGE_APPLE_PAY_MUTATION.to_string()
} else {
AUTHORIZE_APPLE_PAY_MUTATION.to_string()
},
None,
None,
)
};
Ok(Self::Wallet(BraintreeWalletRequest {
query,
variables: GenericVariableInput {
input: WalletPaymentInput {
payment_method_id: payment_method_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "apple_pay token",
},
)?,
transaction: WalletTransactionBody {
amount: item.amount.clone(),
merchant_account_id: metadata.merchant_account_id,
order_id: item
.router_data
.connector_request_reference_id
.clone(),
customer_details,
vault_payment_method_after_transacting,
},
},
},
}))
}
WalletData::PaypalSdk(ref req_wallet) => {
let payment_method_id = req_wallet.token.clone();
let query = match item.router_data.request.is_auto_capture()? {
true => CHARGE_PAYPAL_MUTATION.to_string(),
false => AUTHORIZE_PAYPAL_MUTATION.to_string(),
};
Ok(Self::Wallet(BraintreeWalletRequest {
query,
variables: GenericVariableInput {
input: WalletPaymentInput {
payment_method_id: payment_method_id.clone().into(),
transaction: WalletTransactionBody {
amount: item.amount.clone(),
merchant_account_id: metadata.merchant_account_id,
order_id: item
.router_data
.connector_request_reference_id
.clone(),
customer_details: None,
vault_payment_method_after_transacting: None,
},
},
},
}))
}
WalletData::ApplePay(_apple_pay_data) => {
match item.router_data.payment_method_token {
Some(ref payment_method_token) => match payment_method_token {
PaymentMethodToken::Token(token) => {
let is_mandate = item.router_data.request.is_mandate_payment();
let is_auto_capture = item.router_data.request.is_auto_capture()?;
let (
query,
customer_details,
vault_payment_method_after_transacting,
) = if is_mandate {
(
if is_auto_capture {
CHARGE_AND_VAULT_TRANSACTION_MUTATION.to_string()
} else {
AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION.to_string()
},
item.router_data
.get_billing_email()
.ok()
.map(|email| CustomerBody { email }),
Some(TransactionTiming {
when: VaultTiming::Always,
}),
)
} else {
(
if is_auto_capture {
CHARGE_CREDIT_CARD_MUTATION.to_string()
} else {
AUTHORIZE_CREDIT_CARD_MUTATION.to_string()
},
None,
None,
)
};
Ok(Self::Wallet(BraintreeWalletRequest {
query,
variables: GenericVariableInput {
input: WalletPaymentInput {
payment_method_id: token.clone(),
transaction: WalletTransactionBody {
amount: item.amount.clone(),
merchant_account_id: metadata
.merchant_account_id
.clone(),
order_id: item
.router_data
.connector_request_reference_id
.clone(),
customer_details,
vault_payment_method_after_transacting,
},
},
},
}))
}
PaymentMethodToken::ApplePayDecrypt(_apple_pay_decrypt_data) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"braintree",
),
)
.into())
}
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Braintree"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Braintree"))?
}
},
None => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("braintree"),
)
.into()),
}
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("braintree"),
)
.into()),
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("braintree"),
)
.into())
}
}
}
}
impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
for BraintreePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.payment_method {
api_models::enums::PaymentMethod::Card => {
Ok(Self::Card(CardPaymentRequest::try_from(item)?))
}
api_models::enums::PaymentMethod::CardRedirect
| api_models::enums::PaymentMethod::PayLater
| api_models::enums::PaymentMethod::Wallet
| api_models::enums::PaymentMethod::BankRedirect
| api_models::enums::PaymentMethod::BankTransfer
| api_models::enums::PaymentMethod::Crypto
| api_models::enums::PaymentMethod::BankDebit
| api_models::enums::PaymentMethod::Reward
| api_models::enums::PaymentMethod::RealTimePayment
| api_models::enums::PaymentMethod::MobilePayment
| api_models::enums::PaymentMethod::Upi
| api_models::enums::PaymentMethod::OpenBanking
| api_models::enums::PaymentMethod::Voucher
| api_models::enums::PaymentMethod::GiftCard
| api_models::enums::PaymentMethod::NetworkToken => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"complete authorize flow",
),
)
.into())
}
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AuthResponse {
data: DataAuthResponse,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeAuthResponse {
AuthResponse(Box<AuthResponse>),
ClientTokenResponse(Box<ClientTokenResponse>),
ErrorResponse(Box<ErrorResponse>),
WalletAuthResponse(Box<WalletAuthResponse>),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeCompleteAuthResponse {
AuthResponse(Box<AuthResponse>),
ErrorResponse(Box<ErrorResponse>),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PaymentMethodInfo {
id: Secret<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionAuthChargeResponseBody {
id: String,
status: BraintreePaymentStatus,
payment_method: Option<PaymentMethodInfo>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DataAuthResponse {
authorize_credit_card: AuthChargeCreditCard,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AuthChargeCreditCard {
transaction: TransactionAuthChargeResponseBody,
}
impl TryFrom<PaymentsResponseRouterData<BraintreeAuthResponse>>
for types::PaymentsAuthorizeRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<BraintreeAuthResponse>,
) -> Result<Self, Self::Error> {
match item.response {
BraintreeAuthResponse::ErrorResponse(error_response) => Ok(Self {
response: build_error_response(&error_response.errors, item.http_code)
.map_err(|err| *err),
..item.data
}),
BraintreeAuthResponse::AuthResponse(auth_response) => {
let transaction_data = auth_response.data.authorize_credit_card.transaction;
let status = enums::AttemptStatus::from(transaction_data.status.clone());
let response = if utils::is_payment_failure(status) {
Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: transaction_data.status.to_string(),
message: transaction_data.status.to_string(),
reason: Some(transaction_data.status.to_string()),
attempt_status: None,
connector_transaction_id: Some(transaction_data.id),
connector_response_reference_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_data.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(transaction_data.payment_method.as_ref().map(
|pm| MandateReference {
connector_mandate_id: Some(pm.id.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
},
)),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
BraintreeAuthResponse::ClientTokenResponse(client_token_data) => Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(get_braintree_redirect_form(
*client_token_data,
item.data.get_payment_method_token()?,
item.data.request.payment_method_data.clone(),
item.data.request.get_complete_authorize_url()?,
)?)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
}),
BraintreeAuthResponse::WalletAuthResponse(wallet_response) => {
let txn = &wallet_response.data.authorize_payment_method.transaction;
let status = enums::AttemptStatus::from(txn.status.clone());
let response = if utils::is_payment_failure(status) {
Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: txn.status.to_string(),
message: txn.status.to_string(),
reason: Some(txn.status.to_string()),
attempt_status: None,
connector_transaction_id: Some(txn.id.clone()),
connector_response_reference_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(txn.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: txn.legacy_id.clone(),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
}
}
fn build_error_response<T>(
response: &[ErrorDetails],
http_code: u16,
) -> Result<T, Box<hyperswitch_domain_models::router_data::ErrorResponse>> {
let error_messages = response
.iter()
.map(|error| error.message.to_string())
.collect::<Vec<String>>();
let reason = match !error_messages.is_empty() {
true => Some(error_messages.join(" ")),
false => None,
};
get_error_response(
response
.first()
.and_then(|err_details| err_details.extensions.as_ref())
.and_then(|extensions| extensions.legacy_code.clone()),
response
.first()
.map(|err_details| err_details.message.clone()),
reason,
http_code,
)
}
fn get_error_response<T>(
error_code: Option<String>,
error_msg: Option<String>,
error_reason: Option<String>,
http_code: u16,
) -> Result<T, Box<hyperswitch_domain_models::router_data::ErrorResponse>> {
Err(Box::new(
hyperswitch_domain_models::router_data::ErrorResponse {
code: error_code.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: error_msg.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: error_reason,
status_code: http_code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
},
))
}
#[derive(Debug, Clone, Deserialize, Serialize, strum::Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BraintreePaymentStatus {
Authorized,
Authorizing,
AuthorizedExpired,
Failed,
ProcessorDeclined,
GatewayRejected,
Voided,
Settling,
Settled,
SettlementPending,
SettlementDeclined,
SettlementConfirmed,
SubmittedForSettlement,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ErrorDetails {
pub message: String,
pub extensions: Option<AdditionalErrorDetails>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdditionalErrorDetails {
pub legacy_code: Option<String>,
}
impl From<BraintreePaymentStatus> for enums::AttemptStatus {
fn from(item: BraintreePaymentStatus) -> Self {
match item {
BraintreePaymentStatus::Settling
| BraintreePaymentStatus::Settled
| BraintreePaymentStatus::SettlementConfirmed
| BraintreePaymentStatus::SubmittedForSettlement
| BraintreePaymentStatus::SettlementPending => Self::Charged,
BraintreePaymentStatus::Authorizing => Self::Authorizing,
BraintreePaymentStatus::AuthorizedExpired => Self::AuthorizationFailed,
BraintreePaymentStatus::Failed
| BraintreePaymentStatus::GatewayRejected
| BraintreePaymentStatus::ProcessorDeclined
| BraintreePaymentStatus::SettlementDeclined => Self::Failure,
BraintreePaymentStatus::Authorized => Self::Authorized,
BraintreePaymentStatus::Voided => Self::Voided,
}
}
}
impl TryFrom<PaymentsResponseRouterData<BraintreePaymentsResponse>>
for types::PaymentsAuthorizeRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<BraintreePaymentsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
BraintreePaymentsResponse::ErrorResponse(error_response) => Ok(Self {
response: build_error_response(&error_response.errors.clone(), item.http_code)
.map_err(|err| *err),
..item.data
}),
BraintreePaymentsResponse::PaymentsResponse(payment_response) => {
let transaction_data = payment_response.data.charge_credit_card.transaction;
let status = enums::AttemptStatus::from(transaction_data.status.clone());
let response = if utils::is_payment_failure(status) {
Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: transaction_data.status.to_string().clone(),
message: transaction_data.status.to_string().clone(),
reason: Some(transaction_data.status.to_string().clone()),
attempt_status: None,
connector_transaction_id: Some(transaction_data.id),
connector_response_reference_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_data.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(transaction_data.payment_method.as_ref().map(
|pm| MandateReference {
connector_mandate_id: Some(pm.id.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
},
)),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
BraintreePaymentsResponse::ClientTokenResponse(client_token_data) => Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(get_braintree_redirect_form(
*client_token_data,
item.data.get_payment_method_token()?,
item.data.request.payment_method_data.clone(),
item.data.request.get_complete_authorize_url()?,
)?)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
}),
BraintreePaymentsResponse::WalletPaymentsResponse(wallet_payments_response) => {
let txn = &wallet_payments_response
.data
.charge_payment_method
.transaction;
let status = enums::AttemptStatus::from(txn.status.clone());
let response = if utils::is_payment_failure(status) {
Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: txn.status.to_string(),
message: txn.status.to_string(),
reason: Some(txn.status.to_string()),
attempt_status: None,
connector_transaction_id: Some(txn.id.clone()),
connector_response_reference_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(txn.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(txn.payment_method.as_ref().map(|pm| {
MandateReference {
connector_mandate_id: Some(pm.id.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}
})),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BraintreeCompleteChargeResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BraintreeCompleteChargeResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
BraintreeCompleteChargeResponse::ErrorResponse(error_response) => Ok(Self {
response: build_error_response(&error_response.errors.clone(), item.http_code)
.map_err(|err| *err),
..item.data
}),
BraintreeCompleteChargeResponse::PaymentsResponse(payment_response) => {
let transaction_data = payment_response.data.charge_credit_card.transaction;
let status = enums::AttemptStatus::from(transaction_data.status.clone());
let response = if utils::is_payment_failure(status) {
Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: transaction_data.status.to_string().clone(),
message: transaction_data.status.to_string().clone(),
reason: Some(transaction_data.status.to_string().clone()),
attempt_status: None,
connector_transaction_id: Some(transaction_data.id),
connector_response_reference_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_data.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(transaction_data.payment_method.as_ref().map(
|pm| MandateReference {
connector_mandate_id: Some(pm.id.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
},
)),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BraintreeCompleteAuthResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BraintreeCompleteAuthResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
BraintreeCompleteAuthResponse::ErrorResponse(error_response) => Ok(Self {
response: build_error_response(&error_response.errors, item.http_code)
.map_err(|err| *err),
..item.data
}),
BraintreeCompleteAuthResponse::AuthResponse(auth_response) => {
let transaction_data = auth_response.data.authorize_credit_card.transaction;
let status = enums::AttemptStatus::from(transaction_data.status.clone());
let response = if utils::is_payment_failure(status) {
Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: transaction_data.status.to_string().clone(),
message: transaction_data.status.to_string().clone(),
reason: Some(transaction_data.status.to_string().clone()),
attempt_status: None,
connector_transaction_id: Some(transaction_data.id),
connector_response_reference_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_data.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(transaction_data.payment_method.as_ref().map(
|pm| MandateReference {
connector_mandate_id: Some(pm.id.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
},
)),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PaymentsResponse {
data: DataResponse,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct WalletPaymentsResponse {
pub data: WalletDataResponse,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletDataResponse {
pub charge_payment_method: WalletTransactionWrapper,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct WalletTransactionWrapper {
pub transaction: WalletTransaction,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletTransaction {
pub id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub legacy_id: Option<String>,
pub status: BraintreePaymentStatus,
pub amount: Amount,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method: Option<PaymentMethodInfo>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
pub value: String,
pub currency_code: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct WalletAuthResponse {
pub data: WalletAuthDataResponse,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletAuthDataResponse {
pub authorize_payment_method: WalletTransactionWrapper,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreePaymentsResponse {
PaymentsResponse(Box<PaymentsResponse>),
WalletPaymentsResponse(Box<WalletPaymentsResponse>),
ClientTokenResponse(Box<ClientTokenResponse>),
ErrorResponse(Box<ErrorResponse>),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeCompleteChargeResponse {
PaymentsResponse(Box<PaymentsResponse>),
ErrorResponse(Box<ErrorResponse>),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DataResponse {
charge_credit_card: AuthChargeCreditCard,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundInputData {
amount: StringMajorUnit,
merchant_account_id: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
order_id: Option<String>,
}
#[derive(Serialize, Debug, Clone)]
struct IdFilter {
is: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct TransactionSearchInput {
id: IdFilter,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BraintreeRefundInput {
transaction_id: String,
refund: RefundInputData,
}
impl<F> TryFrom<BraintreeRouterData<&RefundsRouterData<F>>> for BraintreeRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: BraintreeRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let metadata: BraintreeMeta = if let (
Some(merchant_account_id),
Some(merchant_config_currency),
) = (
item.router_data.request.merchant_account_id.clone(),
item.router_data.request.merchant_config_currency,
) {
router_env::logger::info!(
"BRAINTREE: Picking merchant_account_id and merchant_config_currency from payments request"
);
BraintreeMeta {
merchant_account_id,
merchant_config_currency,
}
} else {
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?
};
utils::validate_currency(
item.router_data.request.currency,
Some(metadata.merchant_config_currency),
)?;
let query = REFUND_TRANSACTION_MUTATION.to_string();
let variables = BraintreeRefundVariables {
input: BraintreeRefundInput {
transaction_id: item.router_data.request.connector_transaction_id.clone(),
refund: RefundInputData {
amount: item.amount,
merchant_account_id: metadata.merchant_account_id,
order_id: item.router_data.refund_id.clone(),
},
},
};
Ok(Self { query, variables })
}
}
#[derive(Debug, Clone, Deserialize, Serialize, strum::Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BraintreeRefundStatus {
SettlementPending,
Settling,
Settled,
SubmittedForSettlement,
Failed,
}
impl From<BraintreeRefundStatus> for enums::RefundStatus {
fn from(item: BraintreeRefundStatus) -> Self {
match item {
BraintreeRefundStatus::Settled
| BraintreeRefundStatus::Settling
| BraintreeRefundStatus::SubmittedForSettlement
| BraintreeRefundStatus::SettlementPending => Self::Success,
BraintreeRefundStatus::Failed => Self::Failure,
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BraintreeRefundTransactionBody {
pub id: String,
pub status: BraintreeRefundStatus,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BraintreeRefundTransaction {
pub refund: BraintreeRefundTransactionBody,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BraintreeRefundResponseData {
pub refund_transaction: BraintreeRefundTransaction,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
pub data: BraintreeRefundResponseData,
}
impl TryFrom<RefundsResponseRouterData<Execute, BraintreeRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, BraintreeRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: match item.response {
BraintreeRefundResponse::ErrorResponse(error_response) => {
build_error_response(&error_response.errors, item.http_code).map_err(|err| *err)
}
BraintreeRefundResponse::SuccessResponse(refund_data) => {
let refund_data = refund_data.data.refund_transaction.refund;
let refund_status = enums::RefundStatus::from(refund_data.status.clone());
if utils::is_refund_failure(refund_status) {
Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: refund_data.status.to_string().clone(),
message: refund_data.status.to_string().clone(),
reason: Some(refund_data.status.to_string().clone()),
attempt_status: None,
connector_transaction_id: Some(refund_data.id),
connector_response_reference_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: refund_data.id.clone(),
refund_status,
})
}
}
},
..item.data
})
}
}
#[derive(Debug, Clone, Serialize)]
pub struct RefundSearchInput {
id: IdFilter,
}
impl TryFrom<&types::RefundSyncRouterData> for BraintreeRSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
let metadata: BraintreeMeta = if let (
Some(merchant_account_id),
Some(merchant_config_currency),
) = (
item.request.merchant_account_id.clone(),
item.request.merchant_config_currency,
) {
router_env::logger::info!(
"BRAINTREE: Picking merchant_account_id and merchant_config_currency from payments request"
);
BraintreeMeta {
merchant_account_id,
merchant_config_currency,
}
} else {
utils::to_connector_meta_from_secret(item.connector_meta_data.clone()).change_context(
errors::ConnectorError::InvalidConnectorConfig { config: "metadata" },
)?
};
utils::validate_currency(
item.request.currency,
Some(metadata.merchant_config_currency),
)?;
let refund_id = item.request.get_connector_refund_id()?;
Ok(Self {
query: REFUND_QUERY.to_string(),
variables: RSyncInput {
input: RefundSearchInput {
id: IdFilter { is: refund_id },
},
},
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RSyncNodeData {
id: String,
status: BraintreeRefundStatus,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RSyncEdgeData {
node: RSyncNodeData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RefundData {
edges: Vec<RSyncEdgeData>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RSyncSearchData {
refunds: RefundData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RSyncResponseData {
search: RSyncSearchData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RSyncResponse {
data: RSyncResponseData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeRSyncResponse {
RSyncResponse(Box<RSyncResponse>),
ErrorResponse(Box<ErrorResponse>),
}
impl TryFrom<RefundsResponseRouterData<RSync, BraintreeRSyncResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, BraintreeRSyncResponse>,
) -> Result<Self, Self::Error> {
match item.response {
BraintreeRSyncResponse::ErrorResponse(error_response) => Ok(Self {
response: build_error_response(&error_response.errors, item.http_code)
.map_err(|err| *err),
..item.data
}),
BraintreeRSyncResponse::RSyncResponse(rsync_response) => {
let edge_data = rsync_response
.data
.search
.refunds
.edges
.first()
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?;
let connector_refund_id = &edge_data.node.id;
let response = Ok(RefundsResponseData {
connector_refund_id: connector_refund_id.to_string(),
refund_status: enums::RefundStatus::from(edge_data.node.status.clone()),
});
Ok(Self {
response,
..item.data
})
}
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreditCardData {
number: cards::CardNumber,
expiration_year: Secret<String>,
expiration_month: Secret<String>,
cvv: Secret<String>,
cardholder_name: Secret<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientTokenInput {
merchant_account_id: Secret<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum InputData {
CreditCard(CreditCardInputData),
NetworkToken(NetworkTokenInputData),
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreditCardInputData {
credit_card: CreditCardData,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkTokenInputData {
network_token: NetworkTokenData,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InputClientTokenData {
client_token: ClientTokenInput,
}
impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(card_data) => Ok(Self {
query: TOKENIZE_CREDIT_CARD.to_string(),
variables: VariableInput {
input: InputData::CreditCard(CreditCardInputData {
credit_card: CreditCardData {
number: card_data.card_number,
expiration_year: card_data.card_exp_year,
expiration_month: card_data.card_exp_month,
cvv: card_data.card_cvc,
cardholder_name: item
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string())),
},
}),
},
}),
PaymentMethodData::Wallet(wallet_data) => Self::try_from((item, wallet_data)),
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("braintree"),
)
.into())
}
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TokenizePaymentMethodData {
id: Secret<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizeCreditCardData {
payment_method: TokenizePaymentMethodData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientToken {
client_token: Secret<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizeCreditCard {
tokenize_credit_card: TokenizeCreditCardData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizeNetworkToken {
tokenize_network_token: TokenizeCreditCardData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientTokenData {
create_client_token: ClientToken,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientTokenExtensions {
request_id: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ClientTokenResponse {
data: ClientTokenData,
extensions: ClientTokenExtensions,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum TokenResponse {
CreditCard { data: TokenizeCreditCard },
NetworkToken { data: TokenizeNetworkToken },
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ErrorResponse {
errors: Vec<ErrorDetails>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeTokenResponse {
TokenResponse(Box<TokenResponse>),
ErrorResponse(Box<ErrorResponse>),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeSessionResponse {
SessionTokenResponse(Box<ClientTokenResponse>),
ErrorResponse(Box<ErrorResponse>),
}
impl<F, T> TryFrom<ResponseRouterData<F, BraintreeTokenResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BraintreeTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: match item.response {
BraintreeTokenResponse::ErrorResponse(error_response) => {
build_error_response(error_response.errors.as_ref(), item.http_code)
.map_err(|err| *err)
}
BraintreeTokenResponse::TokenResponse(token_response) => {
let payment_method_id = match *token_response {
TokenResponse::CreditCard { data } => {
data.tokenize_credit_card.payment_method.id
}
TokenResponse::NetworkToken { data } => {
data.tokenize_network_token.payment_method.id
}
};
Ok(PaymentsResponseData::TokenizationResponse {
token: payment_method_id.expose().clone(),
})
}
},
..item.data
})
}
}
#[derive(Debug, Clone, Display, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum GooglePayPriceStatus {
#[strum(serialize = "FINAL")]
Final,
}
#[derive(Debug, Clone, Display, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PaypalFlow {
Checkout,
}
impl From<PaypalFlow> for payment_types::PaypalFlow {
fn from(item: PaypalFlow) -> Self {
match item {
PaypalFlow::Checkout => Self::Checkout,
}
}
}
impl
ForeignTryFrom<(
PaymentsSessionResponseRouterData<BraintreeSessionResponse>,
Self,
)> for types::PaymentsSessionRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, data): (
PaymentsSessionResponseRouterData<BraintreeSessionResponse>,
Self,
),
) -> Result<Self, Self::Error> {
let response = &item.response;
match response {
BraintreeSessionResponse::SessionTokenResponse(res) => {
let session_token = match data.payment_method_type {
Some(common_enums::PaymentMethodType::ApplePay) => {
let payment_request_data: payment_types::PaymentRequestMetadata =
if let Some(connector_meta) = data.connector_meta_data.clone() {
let meta_value: serde_json::Value = connector_meta.expose();
meta_value
.get("apple_pay_combined")
.ok_or(errors::ConnectorError::NoConnectorMetaData)
.attach_printable("Missing apple_pay_combined metadata")?
.get("manual")
.ok_or(errors::ConnectorError::NoConnectorMetaData)
.attach_printable("Missing manual metadata")?
.get("payment_request_data")
.ok_or(errors::ConnectorError::NoConnectorMetaData)
.attach_printable("Missing payment_request_data metadata")?
.clone()
.parse_value("PaymentRequestMetadata")
.change_context(errors::ConnectorError::ParsingFailed)
.attach_printable(
"Failed to parse apple_pay_combined.manual.payment_request_data metadata",
)?
} else {
return Err(errors::ConnectorError::NoConnectorMetaData)
.attach_printable("connector_meta_data is None");
};
let session_token_data = Some(ApplePaySessionResponse::ThirdPartySdk(
payment_types::ThirdPartySdkSessionResponse {
secrets: payment_types::SecretInfoToInitiateSdk {
display: res.data.create_client_token.client_token.clone(),
payment: None,
},
},
));
SessionToken::ApplePay(Box::new(
api_models::payments::ApplepaySessionTokenResponse {
session_token_data,
payment_request_data: Some(
api_models::payments::ApplePayPaymentRequest {
country_code: data.request.country.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "country",
},
)?,
currency_code: data.request.currency,
total: api_models::payments::AmountInfo {
label: payment_request_data.label,
total_type: None,
amount: StringMajorUnitForConnector
.convert(
MinorUnit::new(data.request.amount),
data.request.currency,
)
.change_context(
errors::ConnectorError::AmountConversionFailed,
)?,
},
merchant_capabilities: Some(
payment_request_data.merchant_capabilities,
),
supported_networks: Some(
payment_request_data.supported_networks,
),
merchant_identifier: None,
required_billing_contact_fields: None,
required_shipping_contact_fields: None,
recurring_payment_request: None,
},
),
connector: data.connector.clone(),
delayed_session_token: false,
sdk_next_action: api_models::payments::SdkNextAction {
next_action: api_models::payments::NextActionCall::Confirm,
},
connector_reference_id: None,
connector_sdk_public_key: None,
connector_merchant_id: None,
},
))
}
Some(common_enums::PaymentMethodType::GooglePay) => {
let gpay_data: payment_types::GpayMetaData =
if let Some(connector_meta) = data.connector_meta_data.clone() {
let metadata = connector_meta
.expose()
.parse_value::<payment_types::GpaySessionTokenData>(
"GpaySessionTokenData",
)
.change_context(errors::ConnectorError::ParsingFailed)
.attach_printable("Failed to parse gpay metadata")?;
if let Some(gpay_metadata) = metadata.google_pay.data {
gpay_metadata
} else {
return Err(errors::ConnectorError::InvalidConnectorConfig {
config:
"metadata.google_pay, no googlepay metadata is configured",
}.into());
}
} else {
return Err(errors::ConnectorError::NoConnectorMetaData)
.attach_printable("connector_meta_data is None");
};
SessionToken::GooglePay(Box::new(
api_models::payments::GpaySessionTokenResponse::GooglePaySession(
api_models::payments::GooglePaySessionResponse {
merchant_info: payment_types::GpayMerchantInfo {
merchant_name: gpay_data.merchant_info.merchant_name,
merchant_id: gpay_data.merchant_info.merchant_id,
},
shipping_address_required: false,
email_required: false,
shipping_address_parameters:
payment_types::GpayShippingAddressParameters {
phone_number_required: false,
},
allowed_payment_methods: gpay_data.allowed_payment_methods,
transaction_info: payment_types::GpayTransactionInfo {
country_code: data.request.country.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "country",
},
)?,
currency_code: data.request.currency,
total_price_status: GooglePayPriceStatus::Final.to_string(),
total_price: StringMajorUnitForConnector
.convert(
MinorUnit::new(data.request.amount),
data.request.currency,
)
.change_context(
errors::ConnectorError::AmountConversionFailed,
)?,
},
secrets: Some(payment_types::SecretInfoToInitiateSdk {
display: res.data.create_client_token.client_token.clone(),
payment: None,
}),
delayed_session_token: false,
connector: data.connector.clone(),
sdk_next_action: payment_types::SdkNextAction {
next_action: payment_types::NextActionCall::Confirm,
},
},
),
))
}
Some(common_enums::PaymentMethodType::Paypal) => {
let paypal_sdk_data = data
.connector_meta_data
.clone()
.parse_value::<payment_types::PaypalSdkSessionTokenData>(
"PaypalSdkSessionTokenData",
)
.change_context(errors::ConnectorError::NoConnectorMetaData)
.attach_printable("Failed to parse paypal_sdk metadata.".to_string())?;
SessionToken::Paypal(Box::new(
api_models::payments::PaypalSessionTokenResponse {
connector: data.connector.clone(),
session_token: paypal_sdk_data.data.client_id,
sdk_next_action: api_models::payments::SdkNextAction {
next_action: api_models::payments::NextActionCall::Confirm,
},
client_token: Some(
res.data.create_client_token.client_token.clone().expose(),
),
transaction_info: Some(
api_models::payments::PaypalTransactionInfo {
flow: PaypalFlow::Checkout.into(),
currency_code: data.request.currency,
total_price: StringMajorUnitForConnector
.convert(
MinorUnit::new(data.request.amount),
data.request.currency,
)
.change_context(
errors::ConnectorError::AmountConversionFailed,
)?,
},
),
},
))
}
_ => {
return Err(errors::ConnectorError::NotImplemented(
format!(
"SDK session token generation is not supported for payment method: {:?}",
data.payment_method_type
)
)
.into());
}
};
Ok(Self {
response: Ok(PaymentsResponseData::SessionResponse { session_token }),
..data
})
}
BraintreeSessionResponse::ErrorResponse(error_response) => {
let err = build_error_response(error_response.errors.as_ref(), item.http_code)
.map_err(|err| *err);
Ok(Self {
response: err,
..data
})
}
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureTransactionBody {
amount: StringMajorUnit,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureInputData {
transaction_id: String,
transaction: CaptureTransactionBody,
}
impl TryFrom<&BraintreeRouterData<&types::PaymentsCaptureRouterData>> for BraintreeCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BraintreeRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let query = CAPTURE_TRANSACTION_MUTATION.to_string();
let variables = VariableCaptureInput {
input: CaptureInputData {
transaction_id: item.router_data.request.connector_transaction_id.clone(),
transaction: CaptureTransactionBody {
amount: item.amount.to_owned(),
},
},
};
Ok(Self { query, variables })
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CaptureResponseTransactionBody {
id: String,
status: BraintreePaymentStatus,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CaptureTransactionData {
transaction: CaptureResponseTransactionBody,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureResponseData {
capture_transaction: CaptureTransactionData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CaptureResponse {
data: CaptureResponseData,
}
impl TryFrom<PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>>
for types::PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>,
) -> Result<Self, Self::Error> {
match item.response {
BraintreeCaptureResponse::SuccessResponse(capture_data) => {
let transaction_data = capture_data.data.capture_transaction.transaction;
let status = enums::AttemptStatus::from(transaction_data.status.clone());
let response = if utils::is_payment_failure(status) {
Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: transaction_data.status.to_string().clone(),
message: transaction_data.status.to_string().clone(),
reason: Some(transaction_data.status.to_string().clone()),
attempt_status: None,
connector_transaction_id: Some(transaction_data.id),
connector_response_reference_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_data.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
BraintreeCaptureResponse::ErrorResponse(error_data) => Ok(Self {
response: build_error_response(&error_data.errors, item.http_code)
.map_err(|err| *err),
..item.data
}),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeletePaymentMethodFromVaultInputData {
payment_method_id: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct VariableDeletePaymentMethodFromVaultInput {
input: DeletePaymentMethodFromVaultInputData,
}
#[derive(Debug, Serialize)]
pub struct BraintreeRevokeMandateRequest {
query: String,
variables: VariableDeletePaymentMethodFromVaultInput,
}
impl TryFrom<&types::MandateRevokeRouterData> for BraintreeRevokeMandateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::MandateRevokeRouterData) -> Result<Self, Self::Error> {
let query = DELETE_PAYMENT_METHOD_FROM_VAULT_MUTATION.to_string();
let variables = VariableDeletePaymentMethodFromVaultInput {
input: DeletePaymentMethodFromVaultInputData {
payment_method_id: Secret::new(
item.request
.connector_mandate_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorMandateID)?,
),
},
};
Ok(Self { query, variables })
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BraintreeRevokeMandateResponse,
MandateRevokeRequestData,
MandateRevokeResponseData,
>,
> for RouterData<F, MandateRevokeRequestData, MandateRevokeResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BraintreeRevokeMandateResponse,
MandateRevokeRequestData,
MandateRevokeResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: match item.response {
BraintreeRevokeMandateResponse::ErrorResponse(error_response) => {
build_error_response(error_response.errors.as_ref(), item.http_code)
.map_err(|err| *err)
}
BraintreeRevokeMandateResponse::RevokeMandateResponse(..) => {
Ok(MandateRevokeResponseData {
mandate_status: common_enums::MandateStatus::Revoked,
})
}
},
..item.data
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeRevokeMandateResponse {
RevokeMandateResponse(Box<RevokeMandateResponse>),
ErrorResponse(Box<ErrorResponse>),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RevokeMandateResponse {
data: DeletePaymentMethodFromVault,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeletePaymentMethodFromVault {
client_mutation_id: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelInputData {
transaction_id: String,
}
#[derive(Debug, Serialize)]
pub struct VariableCancelInput {
input: CancelInputData,
}
#[derive(Debug, Serialize)]
pub struct BraintreeCancelRequest {
query: String,
variables: VariableCancelInput,
}
impl TryFrom<&types::PaymentsCancelRouterData> for BraintreeCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let query = VOID_TRANSACTION_MUTATION.to_string();
let variables = VariableCancelInput {
input: CancelInputData {
transaction_id: item.request.connector_transaction_id.clone(),
},
};
Ok(Self { query, variables })
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CancelResponseTransactionBody {
id: String,
status: BraintreePaymentStatus,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CancelTransactionData {
reversal: CancelResponseTransactionBody,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelResponseData {
reverse_transaction: CancelTransactionData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CancelResponse {
data: CancelResponseData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeCancelResponse {
CancelResponse(Box<CancelResponse>),
ErrorResponse(Box<ErrorResponse>),
}
impl<F, T> TryFrom<ResponseRouterData<F, BraintreeCancelResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BraintreeCancelResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
BraintreeCancelResponse::ErrorResponse(error_response) => Ok(Self {
response: build_error_response(&error_response.errors, item.http_code)
.map_err(|err| *err),
..item.data
}),
BraintreeCancelResponse::CancelResponse(void_response) => {
let void_data = void_response.data.reverse_transaction.reversal;
let status = enums::AttemptStatus::from(void_data.status.clone());
let response = if utils::is_payment_failure(status) {
Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: void_data.status.to_string().clone(),
message: void_data.status.to_string().clone(),
reason: Some(void_data.status.to_string().clone()),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
}
}
impl TryFrom<&types::PaymentsSyncRouterData> for BraintreePSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let transaction_id = item
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(Self {
query: TRANSACTION_QUERY.to_string(),
variables: PSyncInput {
input: TransactionSearchInput {
id: IdFilter { is: transaction_id },
},
},
})
}
}
impl TryFrom<&types::PaymentsSessionRouterData> for BraintreePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsSessionRouterData) -> Result<Self, Self::Error> {
let metadata: BraintreeMeta = utils::to_connector_meta_from_secret(
item.connector_meta_data.clone(),
)
.change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata" })?;
Ok(Self::Session(BraintreeClientTokenRequest {
query: CLIENT_TOKEN_MUTATION.to_owned(),
variables: VariableClientTokenInput {
input: InputClientTokenData {
client_token: ClientTokenInput {
merchant_account_id: metadata.merchant_account_id,
},
},
},
}))
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NodeData {
id: String,
status: BraintreePaymentStatus,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct EdgeData {
node: NodeData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TransactionData {
edges: Vec<EdgeData>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SearchData {
transactions: TransactionData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PSyncResponseData {
search: SearchData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PSyncResponse {
data: PSyncResponseData,
}
impl<F, T> TryFrom<ResponseRouterData<F, BraintreePSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BraintreePSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
BraintreePSyncResponse::ErrorResponse(error_response) => Ok(Self {
response: build_error_response(&error_response.errors, item.http_code)
.map_err(|err| *err),
..item.data
}),
BraintreePSyncResponse::SuccessResponse(psync_response) => {
let edge_data = psync_response
.data
.search
.transactions
.edges
.first()
.ok_or(errors::ConnectorError::MissingConnectorTransactionID)?;
let status = enums::AttemptStatus::from(edge_data.node.status.clone());
let response = if utils::is_payment_failure(status) {
Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: edge_data.node.status.to_string().clone(),
message: edge_data.node.status.to_string().clone(),
reason: Some(edge_data.node.status.to_string().clone()),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(edge_data.node.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BraintreeThreeDsResponse {
pub nonce: Secret<String>,
pub liability_shifted: bool,
pub liability_shift_possible: bool,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BraintreeThreeDsErrorResponse {
pub code: String,
pub message: String,
}
#[derive(Debug, Deserialize)]
pub struct BraintreeRedirectionResponse {
pub authentication_response: String,
}
impl TryFrom<BraintreeMeta> for BraintreeClientTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(metadata: BraintreeMeta) -> Result<Self, Self::Error> {
Ok(Self {
query: CLIENT_TOKEN_MUTATION.to_owned(),
variables: VariableClientTokenInput {
input: InputClientTokenData {
client_token: ClientTokenInput {
merchant_account_id: metadata.merchant_account_id,
},
},
},
})
}
}
impl
TryFrom<(
&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
BraintreeMeta,
)> for CardPaymentRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, metadata): (
&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
BraintreeMeta,
),
) -> Result<Self, Self::Error> {
// Check for external 3DS authentication data
let three_ds_data =
item.router_data
.request
.authentication_data
.as_ref()
.map(|auth_data| ThreeDSecureAuthenticationInput {
pass_through: Some(convert_external_three_ds_data(auth_data)),
});
let options = three_ds_data.map(|three_ds| CreditCardTransactionOptions {
three_d_secure_authentication: Some(three_ds),
});
let (query, transaction_body) = if item.router_data.request.is_mandate_payment() {
(
match item.router_data.request.is_auto_capture()? {
true => CHARGE_AND_VAULT_TRANSACTION_MUTATION.to_string(),
false => AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION.to_string(),
},
TransactionBody::Vault(VaultTransactionBody {
amount: item.amount.to_owned(),
merchant_account_id: metadata.merchant_account_id,
vault_payment_method_after_transacting: TransactionTiming {
when: VaultTiming::Always,
},
customer_details: item
.router_data
.get_billing_email()
.ok()
.map(|email| CustomerBody { email }),
order_id: item.router_data.connector_request_reference_id.clone(),
payment_initiator: PaymentInitiatorType::RecurringFirst,
}),
)
} else {
(
match item.router_data.request.is_auto_capture()? {
true => CHARGE_CREDIT_CARD_MUTATION.to_string(),
false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(),
},
TransactionBody::Regular(RegularTransactionBody {
amount: item.amount.to_owned(),
merchant_account_id: metadata.merchant_account_id,
channel: CHANNEL_CODE.to_string(),
customer_details: item
.router_data
.get_billing_email()
.ok()
.map(|email| CustomerBody { email }),
order_id: item.router_data.connector_request_reference_id.clone(),
}),
)
};
Ok(Self {
query,
variables: VariablePaymentInput {
input: PaymentInput {
payment_method_id: match item.router_data.get_payment_method_token()? {
PaymentMethodToken::Token(token) => token,
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Braintree"),
)?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Braintree"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Braintree"))?
}
},
transaction: transaction_body,
options,
},
},
})
}
}
impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
for CardPaymentRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let metadata: BraintreeMeta = if let (
Some(merchant_account_id),
Some(merchant_config_currency),
) = (
item.router_data.request.merchant_account_id.clone(),
item.router_data.request.merchant_config_currency,
) {
router_env::logger::info!(
"BRAINTREE: Picking merchant_account_id and merchant_config_currency from payments request"
);
BraintreeMeta {
merchant_account_id,
merchant_config_currency,
}
} else {
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?
};
utils::validate_currency(
item.router_data.request.currency,
Some(metadata.merchant_config_currency),
)?;
let payload_data = PaymentsCompleteAuthorizeRequestData::get_redirect_response_payload(
&item.router_data.request,
)?
.expose();
let redirection_response: BraintreeRedirectionResponse = serde_json::from_value(
payload_data,
)
.change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "redirection_response",
})?;
let three_ds_data = serde_json::from_str::<BraintreeThreeDsResponse>(
&redirection_response.authentication_response,
)
.change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "three_ds_data",
})?;
let (query, transaction_body) = if item.router_data.request.is_mandate_payment() {
(
match item.router_data.request.is_auto_capture()? {
true => CHARGE_AND_VAULT_TRANSACTION_MUTATION.to_string(),
false => AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION.to_string(),
},
TransactionBody::Vault(VaultTransactionBody {
amount: item.amount.to_owned(),
merchant_account_id: metadata.merchant_account_id,
vault_payment_method_after_transacting: TransactionTiming {
when: VaultTiming::Always,
},
customer_details: item
.router_data
.get_billing_email()
.ok()
.map(|email| CustomerBody { email }),
order_id: item.router_data.connector_request_reference_id.clone(),
payment_initiator: PaymentInitiatorType::RecurringFirst,
}),
)
} else {
(
match item.router_data.request.is_auto_capture()? {
true => CHARGE_CREDIT_CARD_MUTATION.to_string(),
false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(),
},
TransactionBody::Regular(RegularTransactionBody {
amount: item.amount.to_owned(),
merchant_account_id: metadata.merchant_account_id,
channel: CHANNEL_CODE.to_string(),
customer_details: item
.router_data
.get_billing_email()
.ok()
.map(|email| CustomerBody { email }),
order_id: item.router_data.connector_request_reference_id.clone(),
}),
)
};
Ok(Self {
query,
variables: VariablePaymentInput {
input: PaymentInput {
payment_method_id: three_ds_data.nonce,
transaction: transaction_body,
options: None,
},
},
})
}
}
fn get_braintree_redirect_form(
client_token_data: ClientTokenResponse,
payment_method_token: PaymentMethodToken,
card_details: PaymentMethodData,
complete_authorize_url: String,
) -> Result<RedirectForm, error_stack::Report<errors::ConnectorError>> {
Ok(RedirectForm::Braintree {
client_token: client_token_data
.data
.create_client_token
.client_token
.expose(),
card_token: match payment_method_token {
PaymentMethodToken::Token(token) => token.expose(),
PaymentMethodToken::ApplePayDecrypt(_) => Err(unimplemented_payment_method!(
"Apple Pay",
"Simplified",
"Braintree"
))?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Braintree"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Braintree"))?
}
},
bin: match card_details {
PaymentMethodData::Card(card_details) => card_details.card_number.get_card_isin(),
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => Err(
errors::ConnectorError::NotImplemented("given payment method".to_owned()),
)?,
},
acs_url: complete_authorize_url,
})
}
#[derive(Debug, Deserialize)]
pub struct BraintreeWebhookResponse {
pub bt_signature: String,
pub bt_payload: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct Notification {
pub kind: String, // xml parse only string to fields
pub timestamp: String,
pub dispute: Option<BraintreeDisputeData>,
}
pub(crate) fn get_status(status: &str) -> IncomingWebhookEvent {
match status {
"dispute_opened" => IncomingWebhookEvent::DisputeOpened,
"dispute_lost" => IncomingWebhookEvent::DisputeLost,
"dispute_won" => IncomingWebhookEvent::DisputeWon,
"dispute_accepted" | "dispute_auto_accepted" => IncomingWebhookEvent::DisputeAccepted,
"dispute_expired" => IncomingWebhookEvent::DisputeExpired,
"dispute_disputed" => IncomingWebhookEvent::DisputeChallenged,
_ => IncomingWebhookEvent::EventNotSupported,
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct BraintreeDisputeData {
pub amount_disputed: MinorUnit,
pub amount_won: Option<String>,
pub case_number: Option<String>,
pub chargeback_protection_level: Option<String>,
pub currency_iso_code: enums::Currency,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub created_at: Option<PrimitiveDateTime>,
pub evidence: Option<DisputeEvidence>,
pub id: String,
pub kind: String, // xml parse only string to fields
pub status: String,
pub reason: Option<String>,
pub reason_code: Option<String>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub updated_at: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub reply_by_date: Option<PrimitiveDateTime>,
pub transaction: DisputeTransaction,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct DisputeTransaction {
pub amount: StringMajorUnit,
pub id: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct DisputeEvidence {
pub comment: String,
pub id: Secret<String>,
pub created_at: Option<PrimitiveDateTime>,
pub url: url::Url,
}
pub(crate) fn get_dispute_stage(code: &str) -> Result<enums::DisputeStage, errors::ConnectorError> {
match code {
"CHARGEBACK" => Ok(enums::DisputeStage::Dispute),
"PRE_ARBITRATION" => Ok(enums::DisputeStage::PreArbitration),
"RETRIEVAL" => Ok(enums::DisputeStage::PreDispute),
_ => Err(errors::ConnectorError::WebhookBodyDecodingFailed),
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreditCardTransactionOptions {
#[serde(skip_serializing_if = "Option::is_none")]
pub three_d_secure_authentication: Option<ThreeDSecureAuthenticationInput>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSecureAuthenticationInput {
#[serde(skip_serializing_if = "Option::is_none")]
pub pass_through: Option<ThreeDSecurePassThroughInput>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSecurePassThroughInput {
pub eci_flag: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cavv: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub three_d_secure_server_transaction_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub directory_server_response: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub directory_server_transaction_id: Option<String>,
}
fn convert_external_three_ds_data(
auth_data: &hyperswitch_domain_models::router_request_types::AuthenticationData,
) -> ThreeDSecurePassThroughInput {
ThreeDSecurePassThroughInput {
eci_flag: auth_data.eci.clone(),
cavv: Some(auth_data.cavv.clone()),
three_d_secure_server_transaction_id: auth_data.threeds_server_transaction_id.clone(),
version: auth_data
.message_version
.as_ref()
.map(|semantic_version| semantic_version.to_string()),
directory_server_response: auth_data
.transaction_status
.as_ref()
.map(map_transaction_status_to_code),
directory_server_transaction_id: auth_data.ds_trans_id.clone(),
}
}
fn map_transaction_status_to_code(status: &common_enums::TransactionStatus) -> String {
match status {
common_enums::TransactionStatus::Success => "Y".to_string(),
common_enums::TransactionStatus::Failure => "N".to_string(),
common_enums::TransactionStatus::VerificationNotPerformed => "U".to_string(),
common_enums::TransactionStatus::NotVerified => "A".to_string(),
common_enums::TransactionStatus::Rejected => "R".to_string(),
common_enums::TransactionStatus::ChallengeRequired => "C".to_string(),
common_enums::TransactionStatus::ChallengeRequiredDecoupledAuthentication => {
"D".to_string()
}
common_enums::TransactionStatus::InformationOnly => "I".to_string(),
}
}
impl TryFrom<(&types::TokenizationRouterData, WalletData)> for BraintreeTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, wallet_data): (&types::TokenizationRouterData, WalletData),
) -> Result<Self, Self::Error> {
match wallet_data {
WalletData::ApplePay(_apple_pay_data) => match &item.payment_method_token {
Some(PaymentMethodToken::ApplePayDecrypt(decrypt_data)) => Ok(Self {
query: TOKENIZE_NETWORK_TOKEN.to_string(),
variables: VariableInput {
input: InputData::NetworkToken(NetworkTokenInputData {
network_token: NetworkTokenData {
cryptogram: decrypt_data
.payment_data
.online_payment_cryptogram
.clone(),
e_commerce_indicator: decrypt_data
.payment_data
.eci_indicator
.clone()
.map(|eci| {
if eci.len() < 2 {
format!("{:0>2}", eci)
} else {
eci
}
}),
expiration_month: decrypt_data
.get_two_digit_expiry_month()
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "application_expiration_month",
})?,
expiration_year: decrypt_data.get_four_digit_expiry_year(),
number: decrypt_data.application_primary_account_number.clone(),
origin_details: NetworkTokenOriginDetailsInput {
origin: NetworkTokenOrigin::ApplePay,
},
},
}),
},
}),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("braintree"),
)
.into()),
},
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("braintree"),
)
.into()),
}
}
}
|
crates__hyperswitch_connectors__src__connectors__breadpay.rs
|
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::{enums, CallConnectorAction, PaymentAction};
use common_utils::{
consts::BASE64_ENGINE,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
CompleteAuthorize,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask, Maskable, PeekInterface};
use transformers::{
self as breadpay, BreadpayTransactionRequest, BreadpayTransactionResponse,
BreadpayTransactionType,
};
use crate::{
connectors::breadpay::transformers::CallBackResponse,
constants::headers,
types::ResponseRouterData,
utils::{self, PaymentsCompleteAuthorizeRequestData},
};
#[derive(Clone)]
pub struct Breadpay {
amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Breadpay {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Breadpay {}
impl api::PaymentSession for Breadpay {}
impl api::PaymentsCompleteAuthorize for Breadpay {}
impl api::ConnectorAccessToken for Breadpay {}
impl api::MandateSetup for Breadpay {}
impl api::PaymentAuthorize for Breadpay {}
impl api::PaymentSync for Breadpay {}
impl api::PaymentCapture for Breadpay {}
impl api::PaymentVoid for Breadpay {}
impl api::Refund for Breadpay {}
impl api::RefundExecute for Breadpay {}
impl api::RefundSync for Breadpay {}
impl api::PaymentToken for Breadpay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Breadpay
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Breadpay
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Breadpay {
fn id(&self) -> &'static str {
"breadpay"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
// TODO! Check connector documentation, on which unit they are processing the currency.
// If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
// if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.breadpay.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = breadpay::BreadpayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let encoded_api_key = BASE64_ENGINE.encode(format!(
"{}:{}",
auth.api_key.peek(),
auth.api_secret.peek()
));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Basic {encoded_api_key}").into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: breadpay::BreadpayErrorResponse = res
.response
.parse_struct("BreadpayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_type.clone(),
message: response.description.clone(),
reason: Some(response.description),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Breadpay {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Breadpay {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Breadpay {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Breadpay
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Breadpay {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "/carts"))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = breadpay::BreadpayRouterData::from((amount, req));
let connector_req = breadpay::BreadpayCartRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: breadpay::BreadpayPaymentsResponse = res
.response
.parse_struct("Breadpay BreadpayPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Breadpay
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let transaction_type = if req.request.is_auto_capture()? {
BreadpayTransactionType::Settle
} else {
BreadpayTransactionType::Authorize
};
let connector_req = BreadpayTransactionRequest { transaction_type };
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn get_url(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let redirect_response = req.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let redirect_payload = redirect_response
.payload
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
})?
.expose();
let call_back_response: CallBackResponse = serde_json::from_value::<CallBackResponse>(
redirect_payload.clone(),
)
.change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "redirection_payload",
})?;
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"/transactions/actions",
call_back_response.transaction_id
))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.headers(types::PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: BreadpayTransactionResponse = res
.response
.parse_struct("BreadpayTransactionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Breadpay {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"/transactions",
req.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: BreadpayTransactionResponse = res
.response
.parse_struct("BreadpayTransactionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Breadpay {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"/transactions/actions",
req.request.connector_transaction_id
))
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = BreadpayTransactionRequest {
transaction_type: BreadpayTransactionType::Settle,
};
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: BreadpayTransactionResponse = res
.response
.parse_struct("BreadpayTransactionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Breadpay {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"/transactions/actions",
req.request.connector_transaction_id
))
}
fn get_request_body(
&self,
_req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = BreadpayTransactionRequest {
transaction_type: BreadpayTransactionType::Cancel,
};
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: BreadpayTransactionResponse = res
.response
.parse_struct("BreadpayTransactionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Breadpay {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = breadpay::BreadpayRouterData::from((refund_amount, req));
let connector_req = breadpay::BreadpayRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: breadpay::RefundResponse = res
.response
.parse_struct("breadpay RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Breadpay {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: breadpay::RefundResponse = res
.response
.parse_struct("breadpay RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Breadpay {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static BREADPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let mut breadpay_supported_payment_methods = SupportedPaymentMethods::new();
breadpay_supported_payment_methods.add(
enums::PaymentMethod::PayLater,
enums::PaymentMethodType::Breadpay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
breadpay_supported_payment_methods
});
static BREADPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Breadpay",
description: "Breadpay connector",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static BREADPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Breadpay {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&BREADPAY_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*BREADPAY_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&BREADPAY_SUPPORTED_WEBHOOK_FLOWS)
}
}
impl ConnectorRedirectResponse for Breadpay {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
action: PaymentAction,
) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
match action {
PaymentAction::PSync
| PaymentAction::CompleteAuthorize
| PaymentAction::PaymentAuthenticateCompleteAuthorize => {
Ok(CallConnectorAction::Trigger)
}
}
}
}
|
crates__hyperswitch_connectors__src__connectors__calida.rs
|
pub mod transformers;
use std::sync::LazyLock;
use common_enums::enums;
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts, errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask, Secret};
use ring::hmac;
use serde_json::Value;
use transformers as calida;
use crate::{constants::headers, types::ResponseRouterData, utils};
const CALIDA_API_VERSION: &str = "v1";
#[derive(Clone)]
pub struct Calida {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Calida {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Calida {}
impl api::PaymentSession for Calida {}
impl api::ConnectorAccessToken for Calida {}
impl api::MandateSetup for Calida {}
impl api::PaymentAuthorize for Calida {}
impl api::PaymentSync for Calida {}
impl api::PaymentCapture for Calida {}
impl api::PaymentVoid for Calida {}
impl api::Refund for Calida {}
impl api::RefundExecute for Calida {}
impl api::RefundSync for Calida {}
impl api::PaymentToken for Calida {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Calida
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Calida
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Calida {
fn id(&self) -> &'static str {
"calida"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.calida.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = calida::CalidaAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("token {}", auth.api_key.expose()).into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: calida::CalidaErrorResponse = res
.response
.parse_struct("CalidaErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: consts::NO_ERROR_CODE.to_string(),
message: response.message.clone(),
reason: Some(response.message),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Calida {
fn validate_mandate_payment(
&self,
_pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
match pm_data {
PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
"validate_mandate_payment does not support cards".to_string(),
)
.into()),
_ => Ok(()),
}
}
fn validate_psync_reference_id(
&self,
_data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
Ok(())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Calida {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Calida {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Calida {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Calida {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}api/{}/order/payin/start",
self.base_url(connectors),
CALIDA_API_VERSION
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = calida::CalidaRouterData::from((amount, req));
let connector_req = calida::CalidaPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: calida::CalidaPaymentsResponse = res
.response
.parse_struct("Calida PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let response_integrity_object = utils::get_authorise_integrity_object(
self.amount_converter,
response.amount,
response.currency.to_string(),
)?;
let new_router_data = RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
});
new_router_data
.change_context(errors::ConnectorError::ResponseHandlingFailed)
.map(|mut router_data| {
router_data.request.integrity_object = Some(response_integrity_object);
router_data
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Calida {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_transaction_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}api/{}/order/{}/status",
self.base_url(connectors),
CALIDA_API_VERSION,
connector_transaction_id
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: calida::CalidaSyncResponse = res
.response
.parse_struct("calida PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let response_integrity_object = utils::get_sync_integrity_object(
self.amount_converter,
response.amount,
response.currency.to_string(),
)?;
let new_router_data = RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
});
new_router_data
.change_context(errors::ConnectorError::ResponseHandlingFailed)
.map(|mut router_data| {
router_data.request.integrity_object = Some(response_integrity_object);
router_data
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Calida {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Calida".to_string(),
}
.into())
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Calida".to_string(),
}
.into())
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: calida::CalidaPaymentsResponse = res
.response
.parse_struct("Calida PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Calida {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Calida {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refund".to_string(),
connector: "Calida".to_string(),
}
.into())
}
fn get_request_body(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refund".to_string(),
connector: "Calida".to_string(),
}
.into())
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: calida::RefundResponse =
res.response
.parse_struct("calida RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Calida {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "RSync".to_string(),
connector: "Calida".to_string(),
}
.into())
}
fn build_request(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "RSync".to_string(),
connector: "Calida".to_string(),
}
.into())
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: calida::RefundResponse = res
.response
.parse_struct("calida RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Calida {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha512))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let security_header = request
.headers
.get("x-eorder-webhook-signature")
.map(|header_value| {
header_value
.to_str()
.map(String::from)
.map_err(|_| errors::ConnectorError::WebhookSignatureNotFound)
})
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)??;
hex::decode(security_header)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)
}
async fn verify_webhook_source(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<Value>>,
connector_name: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_name,
connector_webhook_details,
)
.await?;
let signature = self
.get_webhook_source_verification_signature(request, &connector_webhook_secrets)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
let secret_bytes = connector_webhook_secrets.secret.as_ref();
let parsed: Value = serde_json::from_slice(request.body)
.map_err(|_| errors::ConnectorError::WebhookSourceVerificationFailed)?;
let sorted_payload = calida::sort_and_minify_json(&parsed)?;
let key = hmac::Key::new(hmac::HMAC_SHA512, secret_bytes);
let verify = hmac::verify(&key, sorted_payload.as_bytes(), &signature)
.map(|_| true)
.map_err(|_| errors::ConnectorError::WebhookSourceVerificationFailed)?;
Ok(verify)
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook_body = transformers::get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(webhook_body.order_id),
))
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let webhook_body = transformers::get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(transformers::get_calida_webhook_event(webhook_body.status))
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook_body = transformers::get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(Box::new(webhook_body))
}
}
static CALIDA_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![enums::CaptureMethod::Automatic];
let mut santander_supported_payment_methods = SupportedPaymentMethods::new();
santander_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Bluecode,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods,
specific_features: None,
},
);
santander_supported_payment_methods
});
static CALIDA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Calida",
description: "Calida Financial is a licensed e-money institution based in Malta and they provide customized financial infrastructure and payment solutions across the EU and EEA. As part of The Payments Group, it focuses on embedded finance, prepaid services, and next-generation digital payment products.",
connector_type: enums::HyperswitchConnectorCategory::AlternativePaymentMethod,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static CALIDA_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];
impl ConnectorSpecifications for Calida {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&CALIDA_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*CALIDA_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&CALIDA_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__cashtocode.rs
|
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
api::ApplicationResponse,
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{PaymentsAuthorizeType, Response},
webhooks::{self, IncomingWebhookFlowError},
};
use masking::{Mask, PeekInterface, Secret};
use transformers as cashtocode;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Cashtocode {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Cashtocode {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Cashtocode {}
impl api::PaymentSession for Cashtocode {}
impl api::ConnectorAccessToken for Cashtocode {}
impl api::MandateSetup for Cashtocode {}
impl api::PaymentAuthorize for Cashtocode {}
impl api::PaymentSync for Cashtocode {}
impl api::PaymentCapture for Cashtocode {}
impl api::PaymentVoid for Cashtocode {}
impl api::PaymentToken for Cashtocode {}
impl api::Refund for Cashtocode {}
impl api::RefundExecute for Cashtocode {}
impl api::RefundSync for Cashtocode {}
fn get_b64_auth_cashtocode(
payment_method_type: Option<enums::PaymentMethodType>,
auth_type: &transformers::CashtocodeAuth,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
fn construct_basic_auth(
username: Option<Secret<String>>,
password: Option<Secret<String>>,
) -> Result<masking::Maskable<String>, errors::ConnectorError> {
let username = username.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let password = password.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(format!(
"Basic {}",
base64::engine::general_purpose::STANDARD.encode(format!(
"{}:{}",
username.peek(),
password.peek()
))
)
.into_masked())
}
let auth_header = match payment_method_type {
Some(enums::PaymentMethodType::ClassicReward) => construct_basic_auth(
auth_type.username_classic.to_owned(),
auth_type.password_classic.to_owned(),
),
Some(enums::PaymentMethodType::Evoucher) => construct_basic_auth(
auth_type.username_evoucher.to_owned(),
auth_type.password_evoucher.to_owned(),
),
_ => return Err(errors::ConnectorError::MissingPaymentMethodType)?,
}?;
Ok(vec![(headers::AUTHORIZATION.to_string(), auth_header)])
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Cashtocode
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Cashtocode where
Self: ConnectorIntegration<Flow, Request, Response>
{
}
impl ConnectorCommon for Cashtocode {
fn id(&self) -> &'static str {
"cashtocode"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.cashtocode.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cashtocode::CashtocodeErrorResponse = res
.response
.parse_struct("CashtocodeErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.to_string(),
message: response.error_description.clone(),
reason: Some(response.error_description),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Cashtocode {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cashtocode {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cashtocode {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Cashtocode
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Cashtocode".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cashtocode {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PaymentsAuthorizeType::get_content_type(self)
.to_owned()
.into(),
)];
let auth_type = transformers::CashtocodeAuth::try_from((
&req.connector_auth_type,
&req.request.currency,
))?;
let mut api_key = get_b64_auth_cashtocode(req.request.payment_method_type, &auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/merchant/paytokens",
connectors.cashtocode.base_url
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_req = cashtocode::CashtocodePaymentsRequest::try_from((req, amount))?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: cashtocode::CashtocodePaymentsResponse = res
.response
.parse_struct("Cashtocode PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cashtocode {
// default implementation of build_request method will be executed
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: transformers::CashtocodePaymentsSyncResponse = res
.response
.parse_struct("CashtocodePaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cashtocode {
fn build_request(
&self,
_req: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Cashtocode".to_string(),
}
.into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cashtocode {
fn build_request(
&self,
_req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Payments Cancel".to_string(),
connector: "Cashtocode".to_string(),
}
.into())
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Cashtocode {
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let base64_signature = utils::get_header_key_value("authorization", request.headers)?;
let signature = base64_signature.as_bytes().to_owned();
Ok(signature)
}
async fn verify_webhook_source(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_label,
connector_webhook_details,
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let signature = self
.get_webhook_source_verification_signature(request, &connector_webhook_secrets)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let secret_auth = String::from_utf8(connector_webhook_secrets.secret.to_vec())
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Could not convert secret to UTF-8")?;
let signature_auth = String::from_utf8(signature.to_vec())
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Could not convert secret to UTF-8")?;
Ok(signature_auth == secret_auth)
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook: transformers::CashtocodePaymentsSyncResponse = request
.body
.parse_struct("CashtocodePaymentsSyncResponse")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(webhook.transaction_id),
))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook: transformers::CashtocodeIncomingWebhook = request
.body
.parse_struct("CashtocodeIncomingWebhook")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Box::new(webhook))
}
fn get_webhook_api_response(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_error_kind: Option<IncomingWebhookFlowError>,
) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> {
let status = "EXECUTED".to_string();
let obj: transformers::CashtocodePaymentsSyncResponse = request
.body
.parse_struct("CashtocodePaymentsSyncResponse")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let response: serde_json::Value =
serde_json::json!({ "status": status, "transactionId" : obj.transaction_id});
Ok(ApplicationResponse::Json(response))
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cashtocode {
fn build_request(
&self,
_req: &RouterData<Execute, RefundsData, RefundsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refunds".to_string(),
connector: "Cashtocode".to_string(),
}
.into())
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cashtocode {
// default implementation of build_request method will be executed
}
static CASHTOCODE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let mut cashtocode_supported_payment_methods = SupportedPaymentMethods::new();
cashtocode_supported_payment_methods.add(
enums::PaymentMethod::Reward,
enums::PaymentMethodType::ClassicReward,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
cashtocode_supported_payment_methods.add(
enums::PaymentMethod::Reward,
enums::PaymentMethodType::Evoucher,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
cashtocode_supported_payment_methods
});
static CASHTOCODE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "CashToCode",
description:
"CashToCode is a payment solution that enables users to convert cash into digital vouchers for online transactions",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static CASHTOCODE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];
impl ConnectorSpecifications for Cashtocode {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&CASHTOCODE_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*CASHTOCODE_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&CASHTOCODE_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__celero.rs
|
pub mod transformers;
use std::sync::LazyLock;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask};
use transformers as celero;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Celero {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Celero {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Celero {}
impl api::PaymentSession for Celero {}
impl api::ConnectorAccessToken for Celero {}
impl api::MandateSetup for Celero {}
impl api::PaymentAuthorize for Celero {}
impl api::PaymentSync for Celero {}
impl api::PaymentCapture for Celero {}
impl api::PaymentVoid for Celero {}
impl api::Refund for Celero {}
impl api::RefundExecute for Celero {}
impl api::RefundSync for Celero {}
impl api::PaymentToken for Celero {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Celero
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Celero
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Celero {
fn id(&self) -> &'static str {
"celero"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.celero.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = celero::CeleroAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.expose().into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: celero::CeleroErrorResponse = res
.response
.parse_struct("CeleroErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
// Extract error details from the response
let error_details = celero::CeleroErrorDetails::from(response);
Ok(ErrorResponse {
status_code: res.status_code,
code: error_details
.error_code
.unwrap_or_else(|| "UNKNOWN_ERROR".to_string()),
message: error_details.error_message,
reason: error_details.decline_reason,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_decline_code: error_details.processor_response_code.clone(),
network_advice_code: None,
network_error_message: error_details.processor_response_code,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Celero {
fn validate_connector_against_payment_request(
&self,
capture_method: Option<enums::CaptureMethod>,
_payment_method: enums::PaymentMethod,
_pmt: Option<enums::PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
// CeleroCommerce supports both automatic (sale) and manual (authorize + capture) flows
let is_capture_method_supported = matches!(
capture_method,
enums::CaptureMethod::Automatic
| enums::CaptureMethod::Manual
| enums::CaptureMethod::SequentialAutomatic
);
if is_capture_method_supported {
Ok(())
} else {
Err(errors::ConnectorError::NotSupported {
message: capture_method.to_string(),
connector: self.id(),
}
.into())
}
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Celero {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Celero {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Celero {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Celero {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/api/transaction", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = celero::CeleroRouterData::try_from((amount, req))?;
let connector_req = celero::CeleroPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: celero::CeleroPaymentsResponse = res
.response
.parse_struct("Celero PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Celero {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
// CeleroCommerce uses search API for payment sync
Ok(format!(
"{}/api/transaction/search",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = celero::CeleroSearchRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: celero::CeleroPaymentsResponse = res
.response
.parse_struct("celero PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Celero {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/api/transaction/{}/capture",
self.base_url(connectors),
connector_payment_id
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = celero::CeleroRouterData::try_from((amount, req))?;
let connector_req = celero::CeleroCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: celero::CeleroCaptureResponse = res
.response
.parse_struct("Celero PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Celero {
fn get_headers(
&self,
req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/api/transaction/{}/void",
self.base_url(connectors),
connector_payment_id
))
}
fn build_request(
&self,
req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
errors::ConnectorError,
> {
let response: celero::CeleroVoidResponse = res
.response
.parse_struct("Celero PaymentsVoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Celero {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/api/transaction/{}/refund",
self.base_url(connectors),
connector_payment_id
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = celero::CeleroRouterData::try_from((refund_amount, req))?;
let connector_req = celero::CeleroRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: celero::CeleroRefundResponse = res
.response
.parse_struct("celero RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Celero {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
// CeleroCommerce uses search API for refund sync
Ok(format!(
"{}/api/transaction/search",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = celero::CeleroSearchRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: celero::CeleroRefundResponse = res
.response
.parse_struct("celero RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Celero {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static CELERO_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
];
let mut celero_supported_payment_methods = SupportedPaymentMethods::new();
celero_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
celero_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
celero_supported_payment_methods
});
static CELERO_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Celero",
description: "Celero is your trusted provider for payment processing technology and solutions, with a commitment to helping small to mid-sized businesses thrive",
connector_type: common_enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: common_enums::ConnectorIntegrationStatus::Alpha,
};
impl ConnectorSpecifications for Celero {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&CELERO_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*CELERO_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
None
}
}
|
crates__hyperswitch_connectors__src__connectors__celero__transformers.rs
|
use common_enums::{enums, Currency};
use common_utils::{id_type::CustomerId, pii::Email, types::MinorUnit};
use hyperswitch_domain_models::{
address::Address as DomainAddress,
payment_method_data::PaymentMethodData,
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
RouterData,
},
router_flow_types::{
payments::Capture,
refunds::{Execute, RSync},
},
router_request_types::{PaymentsCaptureData, ResponseId},
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
consts,
errors::{self},
};
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
get_unimplemented_payment_method_error_message, AddressDetailsData,
PaymentsAuthorizeRequestData, RefundsRequestData, RouterData as _,
},
};
//TODO: Fill the struct with respective fields
pub struct CeleroRouterData<T> {
pub amount: MinorUnit, // CeleroCommerce expects integer cents
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for CeleroRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
// CeleroCommerce Search Request for sync operations - POST /api/transaction/search
#[derive(Debug, Serialize, PartialEq)]
pub struct CeleroSearchRequest {
transaction_id: String,
}
impl TryFrom<&PaymentsSyncRouterData> for CeleroSearchRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let transaction_id = match &item.request.connector_transaction_id {
ResponseId::ConnectorTransactionId(id) => id.clone(),
_ => {
return Err(errors::ConnectorError::MissingConnectorTransactionID.into());
}
};
Ok(Self { transaction_id })
}
}
impl TryFrom<&RefundSyncRouterData> for CeleroSearchRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> {
Ok(Self {
transaction_id: item.request.get_connector_refund_id()?,
})
}
}
// CeleroCommerce Payment Request according to API specs
#[derive(Debug, Serialize, PartialEq)]
pub struct CeleroPaymentsRequest {
idempotency_key: String,
#[serde(rename = "type")]
transaction_type: TransactionType,
amount: MinorUnit, // CeleroCommerce expects integer cents
currency: Currency,
payment_method: CeleroPaymentMethod,
#[serde(skip_serializing_if = "Option::is_none")]
billing_address: Option<CeleroAddress>,
#[serde(skip_serializing_if = "Option::is_none")]
shipping_address: Option<CeleroAddress>,
#[serde(skip_serializing_if = "Option::is_none")]
create_vault_record: Option<bool>,
// CIT/MIT fields
#[serde(skip_serializing_if = "Option::is_none")]
card_on_file_indicator: Option<CardOnFileIndicator>,
#[serde(skip_serializing_if = "Option::is_none")]
initiated_by: Option<InitiatedBy>,
#[serde(skip_serializing_if = "Option::is_none")]
initial_transaction_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
stored_credential_indicator: Option<StoredCredentialIndicator>,
#[serde(skip_serializing_if = "Option::is_none")]
billing_method: Option<BillingMethod>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CeleroAddress {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address_line_1: Option<Secret<String>>,
address_line_2: Option<Secret<String>>,
city: Option<String>,
state: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
country: Option<common_enums::CountryAlpha2>,
phone: Option<Secret<String>>,
email: Option<Email>,
}
impl TryFrom<&DomainAddress> for CeleroAddress {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(address: &DomainAddress) -> Result<Self, Self::Error> {
let address_details = address.address.as_ref();
match address_details {
Some(address_details) => Ok(Self {
first_name: address_details.get_optional_first_name(),
last_name: address_details.get_optional_last_name(),
address_line_1: address_details.get_optional_line1(),
address_line_2: address_details.get_optional_line2(),
city: address_details.get_optional_city(),
state: address_details.get_optional_state(),
postal_code: address_details.get_optional_zip(),
country: address_details.get_optional_country(),
phone: address
.phone
.as_ref()
.and_then(|phone| phone.number.clone()),
email: address.email.clone(),
}),
None => Err(errors::ConnectorError::MissingRequiredField {
field_name: "address_details",
}
.into()),
}
}
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CeleroPaymentMethod {
Card(CeleroCard),
Customer(CeleroCustomer),
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CeleroCustomer {
id: Option<CustomerId>,
payment_method_id: Option<String>,
}
#[derive(Debug, Serialize, PartialEq, Clone, Copy)]
#[serde(rename_all = "lowercase")]
pub enum CeleroEntryType {
Keyed,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CeleroCard {
entry_type: CeleroEntryType,
number: cards::CardNumber,
expiration_date: Secret<String>,
cvc: Secret<String>,
}
impl TryFrom<&PaymentMethodData> for CeleroPaymentMethod {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentMethodData) -> Result<Self, Self::Error> {
match item {
PaymentMethodData::Card(req_card) => {
let card = CeleroCard {
entry_type: CeleroEntryType::Keyed,
number: req_card.card_number.clone(),
expiration_date: Secret::new(format!(
"{}/{}",
req_card.card_exp_month.peek(),
req_card.card_exp_year.peek()
)),
cvc: req_card.card_cvc.clone(),
};
Ok(Self::Card(card))
}
PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::MobilePayment(_) => Err(errors::ConnectorError::NotImplemented(
"Selected payment method through celero".to_string(),
)
.into()),
}
}
}
// Implementation for handling 3DS specifically
impl TryFrom<(&PaymentMethodData, bool)> for CeleroPaymentMethod {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((item, is_three_ds): (&PaymentMethodData, bool)) -> Result<Self, Self::Error> {
// If 3DS is requested, return an error
if is_three_ds {
return Err(errors::ConnectorError::NotSupported {
message: "Cards 3DS".to_string(),
connector: "celero",
}
.into());
}
// Otherwise, delegate to the standard implementation
Self::try_from(item)
}
}
impl TryFrom<&CeleroRouterData<&PaymentsAuthorizeRouterData>> for CeleroPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CeleroRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let is_auto_capture = item.router_data.request.is_auto_capture()?;
let transaction_type = if is_auto_capture {
TransactionType::Sale
} else {
TransactionType::Authorize
};
let billing_address: Option<CeleroAddress> = item
.router_data
.get_optional_billing()
.and_then(|address| address.try_into().ok());
let shipping_address: Option<CeleroAddress> = item
.router_data
.get_optional_shipping()
.and_then(|address| address.try_into().ok());
// Determine CIT/MIT fields based on mandate data
let (mandate_fields, payment_method) = determine_cit_mit_fields(item.router_data)?;
let request = Self {
idempotency_key: item.router_data.connector_request_reference_id.clone(),
transaction_type,
amount: item.amount,
currency: item.router_data.request.currency,
payment_method,
billing_address,
shipping_address,
create_vault_record: Some(false),
card_on_file_indicator: mandate_fields.card_on_file_indicator,
initiated_by: mandate_fields.initiated_by,
initial_transaction_id: mandate_fields.initial_transaction_id,
stored_credential_indicator: mandate_fields.stored_credential_indicator,
billing_method: mandate_fields.billing_method,
};
Ok(request)
}
}
// Define a struct to hold CIT/MIT fields to avoid complex tuple return type
#[derive(Debug, Default)]
pub struct CeleroMandateFields {
pub card_on_file_indicator: Option<CardOnFileIndicator>,
pub initiated_by: Option<InitiatedBy>,
pub initial_transaction_id: Option<String>,
pub stored_credential_indicator: Option<StoredCredentialIndicator>,
pub billing_method: Option<BillingMethod>,
}
// Helper function to determine CIT/MIT fields based on mandate data
fn determine_cit_mit_fields(
router_data: &PaymentsAuthorizeRouterData,
) -> Result<(CeleroMandateFields, CeleroPaymentMethod), error_stack::Report<errors::ConnectorError>>
{
// Default null values
let mut mandate_fields = CeleroMandateFields::default();
// First check if there's a mandate_id in the request
match router_data
.request
.mandate_id
.clone()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id)
{
// If there's a connector mandate ID, this is a MIT (Merchant Initiated Transaction)
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_id,
)) => {
mandate_fields.card_on_file_indicator = Some(CardOnFileIndicator::RecurringPayment);
mandate_fields.initiated_by = Some(InitiatedBy::Merchant); // This is a MIT
mandate_fields.stored_credential_indicator = Some(StoredCredentialIndicator::Used);
mandate_fields.billing_method = Some(BillingMethod::Recurring);
mandate_fields.initial_transaction_id =
connector_mandate_id.get_connector_mandate_request_reference_id();
Ok((
mandate_fields,
CeleroPaymentMethod::Customer(CeleroCustomer {
id: Some(router_data.get_customer_id()?),
payment_method_id: connector_mandate_id.get_payment_method_id(),
}),
))
}
// For other mandate types that might not be supported
Some(api_models::payments::MandateReferenceId::NetworkMandateId(_))
| Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_))
| Some(api_models::payments::MandateReferenceId::CardWithLimitedData) => {
// These might need different handling or return an error
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Celero"),
)
.into())
}
// If no mandate ID is present, check if it's a mandate payment
None => {
if router_data.request.is_mandate_payment() {
// This is a customer-initiated transaction for a recurring payment
mandate_fields.initiated_by = Some(InitiatedBy::Customer);
mandate_fields.card_on_file_indicator = Some(CardOnFileIndicator::RecurringPayment);
mandate_fields.billing_method = Some(BillingMethod::Recurring);
mandate_fields.stored_credential_indicator = Some(StoredCredentialIndicator::Used);
}
let is_three_ds = router_data.is_three_ds();
Ok((
mandate_fields,
CeleroPaymentMethod::try_from((
&router_data.request.payment_method_data,
is_three_ds,
))?,
))
}
}
}
// Auth Struct for CeleroCommerce API key authentication
pub struct CeleroAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for CeleroAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// CeleroCommerce API Response Structures
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum CeleroResponseStatus {
#[serde(alias = "success", alias = "Success", alias = "SUCCESS")]
Success,
#[serde(alias = "error", alias = "Error", alias = "ERROR")]
Error,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum CeleroTransactionStatus {
Approved,
Declined,
Error,
Pending,
PendingSettlement,
Settled,
Voided,
Reversed,
}
impl From<CeleroTransactionStatus> for common_enums::AttemptStatus {
fn from(item: CeleroTransactionStatus) -> Self {
match item {
CeleroTransactionStatus::Approved => Self::Authorized,
CeleroTransactionStatus::Settled => Self::Charged,
CeleroTransactionStatus::Declined | CeleroTransactionStatus::Error => Self::Failure,
CeleroTransactionStatus::Pending | CeleroTransactionStatus::PendingSettlement => {
Self::Pending
}
CeleroTransactionStatus::Voided | CeleroTransactionStatus::Reversed => Self::Voided,
}
}
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CeleroCardResponse {
pub status: CeleroTransactionStatus,
pub auth_code: Option<String>,
pub processor_response_code: Option<String>,
pub avs_response_code: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CeleroPaymentMethodResponse {
Card(CeleroCardResponse),
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum TransactionType {
Sale,
Authorize,
}
// CIT/MIT related enums
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum CardOnFileIndicator {
#[serde(rename = "C")]
GeneralPurposeStorage,
#[serde(rename = "R")]
RecurringPayment,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum InitiatedBy {
Customer,
Merchant,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum StoredCredentialIndicator {
Used,
Stored,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum BillingMethod {
Straight,
#[serde(rename = "initial_recurring")]
InitialRecurring,
Recurring,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde_with::skip_serializing_none]
pub struct CeleroTransactionResponseData {
pub id: String,
#[serde(rename = "type")]
pub transaction_type: TransactionType,
pub amount: i64,
pub currency: String,
pub response: CeleroPaymentMethodResponse,
pub billing_address: Option<CeleroAddressResponse>,
pub shipping_address: Option<CeleroAddressResponse>,
// Additional fields from the sample response
pub status: Option<String>,
pub response_code: Option<i32>,
pub customer_id: Option<String>,
pub payment_method_id: Option<String>,
}
impl CeleroTransactionResponseData {
pub fn get_mandate_reference(&self) -> Box<Option<MandateReference>> {
if self.payment_method_id.is_some() {
Box::new(Some(MandateReference {
connector_mandate_id: None,
payment_method_id: self.payment_method_id.clone(),
mandate_metadata: None,
connector_mandate_request_reference_id: Some(self.id.clone()),
}))
} else {
Box::new(None)
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct CeleroAddressResponse {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address_line_1: Option<Secret<String>>,
address_line_2: Option<Secret<String>>,
city: Option<String>,
state: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
country: Option<common_enums::CountryAlpha2>,
phone: Option<Secret<String>>,
email: Option<Secret<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct CeleroPaymentsResponse {
pub status: CeleroResponseStatus,
pub msg: String,
pub data: Option<CeleroTransactionResponseData>,
}
impl<F, T> TryFrom<ResponseRouterData<F, CeleroPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CeleroPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.status {
CeleroResponseStatus::Success => {
if let Some(data) = item.response.data {
let CeleroPaymentMethodResponse::Card(response) = &data.response;
// Check if transaction itself failed despite successful API call
match response.status {
CeleroTransactionStatus::Declined | CeleroTransactionStatus::Error => {
// Transaction failed - create error response with transaction details
let error_details = CeleroErrorDetails::from_transaction_response(
response,
item.response.msg,
);
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(
hyperswitch_domain_models::router_data::ErrorResponse {
code: error_details
.error_code
.unwrap_or_else(|| "TRANSACTION_FAILED".to_string()),
message: error_details.error_message,
reason: error_details.decline_reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(data.id),
connector_response_reference_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
},
),
..item.data
})
}
_ => {
let connector_response_data =
convert_to_additional_payment_method_connector_response(
response.avs_response_code.clone(),
)
.map(ConnectorResponseData::with_additional_payment_method_data);
let final_status: enums::AttemptStatus = response.status.into();
Ok(Self {
status: final_status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
data.id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: data.get_mandate_reference(),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: response.auth_code.clone(),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
connector_response: connector_response_data,
..item.data
})
}
}
} else {
// No transaction data in successful response
// We don't have a transaction ID in this case
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: "MISSING_DATA".to_string(),
message: "No transaction data in response".to_string(),
reason: Some(item.response.msg),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
CeleroResponseStatus::Error => {
// Top-level API error
let error_details =
CeleroErrorDetails::from_top_level_error(item.response.msg.clone());
// Extract transaction ID from the top-level data if available
let connector_transaction_id =
item.response.data.as_ref().map(|data| data.id.clone());
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: error_details
.error_code
.unwrap_or_else(|| "API_ERROR".to_string()),
message: error_details.error_message,
reason: error_details.decline_reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id,
connector_response_reference_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
}
// CAPTURE:
// Type definition for CaptureRequest
#[derive(Default, Debug, Serialize)]
pub struct CeleroCaptureRequest {
pub amount: MinorUnit,
#[serde(skip_serializing_if = "Option::is_none")]
pub order_id: Option<String>,
}
impl TryFrom<&CeleroRouterData<&PaymentsCaptureRouterData>> for CeleroCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &CeleroRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
order_id: Some(item.router_data.payment_id.clone()),
})
}
}
// CeleroCommerce Capture Response
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CeleroCaptureResponse {
pub status: CeleroResponseStatus,
pub msg: Option<String>,
pub data: Option<serde_json::Value>, // Usually null for capture responses
}
impl
TryFrom<
ResponseRouterData<
Capture,
CeleroCaptureResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
> for RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
Capture,
CeleroCaptureResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.status {
CeleroResponseStatus::Success => Ok(Self {
status: common_enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.data.request.connector_transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
}),
CeleroResponseStatus::Error => Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: "CAPTURE_FAILED".to_string(),
message: item
.response
.msg
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: None,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(
item.data.request.connector_transaction_id.clone(),
),
connector_response_reference_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
// CeleroCommerce Void Response - matches API spec format
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CeleroVoidResponse {
pub status: CeleroResponseStatus,
pub msg: String,
pub data: Option<serde_json::Value>, // Usually null for void responses
}
impl
TryFrom<
ResponseRouterData<
hyperswitch_domain_models::router_flow_types::payments::Void,
CeleroVoidResponse,
hyperswitch_domain_models::router_request_types::PaymentsCancelData,
PaymentsResponseData,
>,
>
for RouterData<
hyperswitch_domain_models::router_flow_types::payments::Void,
hyperswitch_domain_models::router_request_types::PaymentsCancelData,
PaymentsResponseData,
>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
hyperswitch_domain_models::router_flow_types::payments::Void,
CeleroVoidResponse,
hyperswitch_domain_models::router_request_types::PaymentsCancelData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.status {
CeleroResponseStatus::Success => Ok(Self {
status: common_enums::AttemptStatus::Voided,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.data.request.connector_transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
}),
CeleroResponseStatus::Error => Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: "VOID_FAILED".to_string(),
message: item.response.msg.clone(),
reason: Some(item.response.msg),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(
item.data.request.connector_transaction_id.clone(),
),
connector_response_reference_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct CeleroRefundRequest {
pub amount: MinorUnit,
pub surcharge: MinorUnit, // Required field as per API specification
}
impl<F> TryFrom<&CeleroRouterData<&RefundsRouterData<F>>> for CeleroRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &CeleroRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
surcharge: MinorUnit::zero(), // Default to 0 as per API specification
})
}
}
// CeleroCommerce Refund Response - matches API spec format
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CeleroRefundResponse {
pub status: CeleroResponseStatus,
pub msg: String,
pub data: Option<serde_json::Value>, // Usually null for refund responses
}
impl TryFrom<RefundsResponseRouterData<Execute, CeleroRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, CeleroRefundResponse>,
) -> Result<Self, Self::Error> {
match item.response.status {
CeleroResponseStatus::Success => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.data.request.refund_id.clone(),
refund_status: enums::RefundStatus::Success,
}),
..item.data
}),
CeleroResponseStatus::Error => Ok(Self {
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: "REFUND_FAILED".to_string(),
message: item.response.msg.clone(),
reason: Some(item.response.msg),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(
item.data.request.connector_transaction_id.clone(),
),
connector_response_reference_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
impl TryFrom<RefundsResponseRouterData<RSync, CeleroRefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, CeleroRefundResponse>,
) -> Result<Self, Self::Error> {
match item.response.status {
CeleroResponseStatus::Success => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.data.request.refund_id.clone(),
refund_status: enums::RefundStatus::Success,
}),
..item.data
}),
CeleroResponseStatus::Error => Ok(Self {
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: "REFUND_SYNC_FAILED".to_string(),
message: item.response.msg.clone(),
reason: Some(item.response.msg),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(
item.data.request.connector_transaction_id.clone(),
),
connector_response_reference_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
// CeleroCommerce Error Response Structures
// Main error response structure - matches API spec format
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CeleroErrorResponse {
pub status: CeleroResponseStatus,
pub msg: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<serde_json::Value>,
}
// Error details that can be extracted from various response fields
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CeleroErrorDetails {
pub error_code: Option<String>,
pub error_message: String,
pub processor_response_code: Option<String>,
pub decline_reason: Option<String>,
}
impl From<CeleroErrorResponse> for CeleroErrorDetails {
fn from(error_response: CeleroErrorResponse) -> Self {
Self {
error_code: Some("API_ERROR".to_string()),
error_message: error_response.msg,
processor_response_code: None,
decline_reason: None,
}
}
}
// Function to extract error details from transaction response data
impl CeleroErrorDetails {
pub fn from_transaction_response(response: &CeleroCardResponse, msg: String) -> Self {
// Map specific error codes based on common response patterns
let decline_reason = Self::map_processor_error(&response.processor_response_code, &msg);
Self {
error_code: None,
error_message: msg,
processor_response_code: response.processor_response_code.clone(),
decline_reason,
}
}
pub fn from_top_level_error(msg: String) -> Self {
// Map specific error codes from top-level API errors
Self {
error_code: None,
error_message: msg,
processor_response_code: None,
decline_reason: None,
}
}
/// Map processor response codes and messages to specific Hyperswitch error codes
fn map_processor_error(processor_code: &Option<String>, message: &str) -> Option<String> {
let message_lower = message.to_lowercase();
// Check processor response codes if available
if let Some(code) = processor_code {
match code.as_str() {
"05" => Some("TRANSACTION_DECLINED".to_string()),
"14" => Some("INVALID_CARD_DATA".to_string()),
"51" => Some("INSUFFICIENT_FUNDS".to_string()),
"54" => Some("EXPIRED_CARD".to_string()),
"55" => Some("INCORRECT_CVC".to_string()),
"61" => Some("Exceeds withdrawal amount limit".to_string()),
"62" => Some("TRANSACTION_DECLINED".to_string()),
"65" => Some("Exceeds withdrawal frequency limit".to_string()),
"78" => Some("INVALID_CARD_DATA".to_string()),
"91" => Some("PROCESSING_ERROR".to_string()),
"96" => Some("PROCESSING_ERROR".to_string()),
_ => {
router_env::logger::info!(
"Celero response error code ({:?}) is not mapped to any error state ",
code
);
Some("Transaction failed".to_string())
}
}
} else {
Some(message_lower)
}
}
}
pub fn get_avs_definition(code: &str) -> Option<&'static str> {
match code {
"0" => Some("AVS Not Available"),
"A" => Some("Address match only"),
"B" => Some("Address matches, ZIP not verified"),
"C" => Some("Incompatible format"),
"D" => Some("Exact match"),
"F" => Some("Exact match, UK-issued cards"),
"G" => Some("Non-U.S. Issuer does not participate"),
"I" => Some("Not verified"),
"M" => Some("Exact match"),
"N" => Some("No address or ZIP match"),
"P" => Some("Postal Code match"),
"R" => Some("Issuer system unavailable"),
"S" => Some("Service not supported"),
"U" => Some("Address unavailable"),
"W" => Some("9-character numeric ZIP match only"),
"X" => Some("Exact match, 9-character numeric ZIP"),
"Y" => Some("Exact match, 5-character numeric ZIP"),
"Z" => Some("5-character ZIP match only"),
"L" => Some("Partial match, Name and billing postal code match"),
"1" => Some("Cardholder name and ZIP match"),
"2" => Some("Cardholder name, address and ZIP match"),
"3" => Some("Cardholder name and address match"),
"4" => Some("Cardholder name matches"),
"5" => Some("Cardholder name incorrect, ZIP matches"),
"6" => Some("Cardholder name incorrect, address and zip match"),
"7" => Some("Cardholder name incorrect, address matches"),
"8" => Some("Cardholder name, address, and ZIP do not match"),
_ => {
router_env::logger::info!(
"Celero avs response code ({:?}) is not mapped to any definition.",
code
);
None
} // No definition found for the given code
}
}
fn convert_to_additional_payment_method_connector_response(
response_code: Option<String>,
) -> Option<AdditionalPaymentMethodConnectorResponse> {
match response_code {
None => None,
Some(code) => {
let description = get_avs_definition(&code);
let payment_checks = serde_json::json!({
"avs_result_code": code,
"description": description
});
Some(AdditionalPaymentMethodConnectorResponse::Card {
authentication_data: None,
payment_checks: Some(payment_checks),
card_network: None,
domestic_network: None,
auth_code: None,
})
}
}
}
|
crates__hyperswitch_connectors__src__connectors__chargebee.rs
|
pub mod transformers;
use api_models::subscription::SubscriptionItemType;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::ResultExt;
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
use hyperswitch_domain_models::{revenue_recovery, router_data_v2::RouterDataV2};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_data_v2::flow_common_types::{
GetSubscriptionItemPricesData, GetSubscriptionItemsData, SubscriptionCreateData,
SubscriptionCustomerData,
},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
revenue_recovery::InvoiceRecordBack,
subscriptions::{
GetSubscriptionEstimate, GetSubscriptionItemPrices, GetSubscriptionItems,
SubscriptionCancel, SubscriptionCreate, SubscriptionPause, SubscriptionResume,
},
CreateConnectorCustomer,
},
router_request_types::{
revenue_recovery::InvoiceRecordBackRequest,
subscriptions::{
GetSubscriptionEstimateRequest, GetSubscriptionItemPricesRequest,
GetSubscriptionItemsRequest, SubscriptionCancelRequest, SubscriptionCreateRequest,
SubscriptionPauseRequest, SubscriptionResumeRequest,
},
AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
revenue_recovery::InvoiceRecordBackResponse,
subscriptions::{
GetSubscriptionEstimateResponse, GetSubscriptionItemPricesResponse,
GetSubscriptionItemsResponse, SubscriptionCancelResponse, SubscriptionCreateResponse,
SubscriptionPauseResponse, SubscriptionResumeResponse,
},
ConnectorInfo, PaymentsResponseData, RefundsResponseData,
},
types::{
ConnectorCustomerRouterData, GetSubscriptionEstimateRouterData,
GetSubscriptionItemsRouterData, GetSubscriptionPlanPricesRouterData,
InvoiceRecordBackRouterData, PaymentsAuthorizeRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
SubscriptionCancelRouterData, SubscriptionCreateRouterData, SubscriptionPauseRouterData,
SubscriptionResumeRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self,
payments::ConnectorCustomer,
subscriptions_v2::{GetSubscriptionPlanPricesV2, GetSubscriptionPlansV2},
ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
connector_integration_v2::ConnectorIntegrationV2,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{Mask, PeekInterface, Secret};
use transformers as chargebee;
use crate::{
connectors::chargebee::transformers::{
ChargebeeGetPlanPricesResponse, ChargebeeListPlansResponse,
},
constants::headers,
types::ResponseRouterData,
utils,
};
#[derive(Clone)]
pub struct Chargebee {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Chargebee {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl ConnectorCustomer for Chargebee {}
impl api::Payment for Chargebee {}
impl api::PaymentSession for Chargebee {}
impl api::ConnectorAccessToken for Chargebee {}
impl api::MandateSetup for Chargebee {}
impl api::PaymentAuthorize for Chargebee {}
impl api::PaymentSync for Chargebee {}
impl api::PaymentCapture for Chargebee {}
impl api::PaymentVoid for Chargebee {}
impl api::Refund for Chargebee {}
impl api::RefundExecute for Chargebee {}
impl api::RefundSync for Chargebee {}
impl api::PaymentToken for Chargebee {}
impl api::subscriptions::Subscriptions for Chargebee {}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl api::revenue_recovery::RevenueRecoveryRecordBack for Chargebee {}
fn build_chargebee_url<Flow, Request, Response>(
connector: &Chargebee,
req: &RouterData<Flow, Request, Response>,
connectors: &Connectors,
path: &str,
) -> CustomResult<String, errors::ConnectorError> {
let metadata: chargebee::ChargebeeMetadata =
utils::to_connector_meta_from_secret(req.connector_meta_data.clone())?;
let site = metadata.site.peek();
let mut base = connector.base_url(connectors).to_string();
base = base.replace("{{merchant_endpoint_prefix}}", site);
base = base.replace("$", site);
if base.contains("{{merchant_endpoint_prefix}}") || base.contains('$') {
return Err(errors::ConnectorError::InvalidConnectorConfig {
config: "Chargebee base_url has an unresolved placeholder",
}
.into());
}
if !base.ends_with('/') {
base.push('/');
}
Ok(format!("{}{}", base, path))
}
macro_rules! impl_chargebee_integration {
(
flow: $flow:ty,
flow_type: $flow_type:ty,
request: $request:ty,
response: $response:ty,
router_data: $router_data:ty,
connector_response: $connector_response:ty,
url_path: |$req_param:ident| $url_path:expr,
method: $method:expr
$(, request_body: $request_body:expr)?
$(, query_params: $query_fn:expr)?
) => {
impl ConnectorIntegration<$flow, $request, $response> for Chargebee {
fn get_headers(
&self,
req: &$router_data,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
#[allow(unreachable_code)]
fn get_url(
&self,
req: &$router_data,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let $req_param = req;
let _base_path_opt: Option<String> = $url_path;
let _base_path = _base_path_opt.ok_or_else(|| {
errors::ConnectorError::NotImplemented(
format!("{} operation is not supported by Chargebee", stringify!($flow))
)
})?;
$(
let query = $query_fn(req)?;
let path = format!("{}{}", _base_path, query);
return build_chargebee_url(self, req, _connectors, &path);
)?
build_chargebee_url(self, req, _connectors, &_base_path)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
$(
// Only include get_request_body if request_body is specified
fn get_request_body(
&self,
req: &$router_data,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
$request_body(self, req)
}
)?
fn build_request(
&self,
req: &$router_data,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
#[allow(unused_mut)]
let mut builder = RequestBuilder::new()
.method($method)
.url(&<$flow_type>::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(<$flow_type>::get_headers(
self, req, connectors,
)?);
$(
let _ = $request_body; // Use the token to satisfy the macro
builder = builder.set_body(<$flow_type>::get_request_body(
self, req, connectors,
)?);
)?
Ok(Some(builder.build()))
}
fn handle_response(
&self,
data: &$router_data,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<$router_data, errors::ConnectorError> {
let response: $connector_response = res
.response
.parse_struct(stringify!($connector_response))
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
};
}
impl
ConnectorIntegrationV2<
SubscriptionCreate,
SubscriptionCreateData,
SubscriptionCreateRequest,
SubscriptionCreateResponse,
> for Chargebee
{
// Not Implemented (R)
}
impl
ConnectorIntegrationV2<
CreateConnectorCustomer,
SubscriptionCustomerData,
ConnectorCustomerData,
PaymentsResponseData,
> for Chargebee
{
// Not Implemented (R)
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Chargebee
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Chargebee
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.common_get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Chargebee {
fn id(&self) -> &'static str {
"chargebee"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.chargebee.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = chargebee::ChargebeeAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let encoded_api_key = BASE64_ENGINE.encode(auth.full_access_key_v1.peek());
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Basic {encoded_api_key}").into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: chargebee::ChargebeeErrorResponse = res
.response
.parse_struct("ChargebeeErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.api_error_code.clone(),
message: response.api_error_code.clone(),
reason: Some(response.message),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Chargebee {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Chargebee {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Chargebee {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Chargebee
{
}
// Payment flows are not implemented for Chargebee as it's a subscription billing connector
fn build_payments_authorize_request_body(
connector: &Chargebee,
req: &PaymentsAuthorizeRouterData,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
connector.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = chargebee::ChargebeeRouterData::from((amount, req));
let connector_req = chargebee::ChargebeePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
impl_chargebee_integration!(
flow: Authorize,
flow_type: types::PaymentsAuthorizeType,
request: PaymentsAuthorizeData,
response: PaymentsResponseData,
router_data: PaymentsAuthorizeRouterData,
connector_response: chargebee::ChargebeePaymentsResponse,
url_path: |_req| None,
method: Method::Post,
request_body: build_payments_authorize_request_body
);
impl_chargebee_integration!(
flow: PSync,
flow_type: types::PaymentsSyncType,
request: PaymentsSyncData,
response: PaymentsResponseData,
router_data: PaymentsSyncRouterData,
connector_response: chargebee::ChargebeePaymentsResponse,
url_path: |_req| None,
method: Method::Get
);
fn build_payments_capture_request_body(
_connector: &Chargebee,
_req: &PaymentsCaptureRouterData,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented(
"Payment capture not supported by Chargebee".to_string(),
)
.into())
}
impl_chargebee_integration!(
flow: Capture,
flow_type: types::PaymentsCaptureType,
request: PaymentsCaptureData,
response: PaymentsResponseData,
router_data: PaymentsCaptureRouterData,
connector_response: chargebee::ChargebeePaymentsResponse,
url_path: |_req| None,
method: Method::Post,
request_body: build_payments_capture_request_body
);
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Chargebee {}
fn build_refund_execute_request_body(
connector: &Chargebee,
req: &RefundsRouterData<Execute>,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
connector.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = chargebee::ChargebeeRouterData::from((refund_amount, req));
let connector_req = chargebee::ChargebeeRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
impl_chargebee_integration!(
flow: Execute,
flow_type: types::RefundExecuteType,
request: RefundsData,
response: RefundsResponseData,
router_data: RefundsRouterData<Execute>,
connector_response: chargebee::RefundResponse,
url_path: |_req| None,
method: Method::Post,
request_body: build_refund_execute_request_body
);
impl_chargebee_integration!(
flow: RSync,
flow_type: types::RefundSyncType,
request: RefundsData,
response: RefundsResponseData,
router_data: RefundSyncRouterData,
connector_response: chargebee::RefundResponse,
url_path: |_req| None,
method: Method::Get
);
fn build_subscription_create_request_body(
_connector: &Chargebee,
req: &SubscriptionCreateRouterData,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = chargebee::ChargebeeRouterData::from((MinorUnit::new(0), req));
let connector_req =
chargebee::ChargebeeSubscriptionCreateRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_connector_customer_request_body(
_connector: &Chargebee,
req: &ConnectorCustomerRouterData,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = chargebee::ChargebeeRouterData::from((MinorUnit::new(0), req));
let connector_req =
chargebee::ChargebeeCustomerCreateRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_invoice_record_back_request_body(
connector: &Chargebee,
req: &InvoiceRecordBackRouterData,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
connector.amount_converter,
req.request.amount,
req.request.currency,
)?;
let connector_router_data = chargebee::ChargebeeRouterData::from((amount, req));
let connector_req = chargebee::ChargebeeRecordPaymentRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_subscription_estimate_request_body(
_connector: &Chargebee,
req: &GetSubscriptionEstimateRouterData,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = chargebee::ChargebeeSubscriptionEstimateRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_subscription_pause_request_body(
_connector: &Chargebee,
req: &SubscriptionPauseRouterData,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = chargebee::ChargebeePauseSubscriptionRequest::from(req);
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_subscription_resume_request_body(
_connector: &Chargebee,
req: &SubscriptionResumeRouterData,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = chargebee::ChargebeeResumeSubscriptionRequest::from(req);
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_subscription_cancel_request_body(
_connector: &Chargebee,
req: &SubscriptionCancelRouterData,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = chargebee::ChargebeeCancelSubscriptionRequest::from(req);
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
impl api::subscriptions::SubscriptionCreate for Chargebee {}
impl_chargebee_integration!(
flow: SubscriptionCreate,
flow_type: types::SubscriptionCreateType,
request: SubscriptionCreateRequest,
response: SubscriptionCreateResponse,
router_data: SubscriptionCreateRouterData,
connector_response: chargebee::ChargebeeSubscriptionCreateResponse,
url_path: |req| Some(format!("v2/customers/{}/subscription_for_items", req.request.customer_id.get_string_repr())),
method: Method::Post,
request_body: build_subscription_create_request_body
);
impl_chargebee_integration!(
flow: InvoiceRecordBack,
flow_type: types::InvoiceRecordBackType,
request: InvoiceRecordBackRequest,
response: InvoiceRecordBackResponse,
router_data: InvoiceRecordBackRouterData,
connector_response: chargebee::ChargebeeRecordbackResponse,
url_path: |req| Some(format!("v2/invoices/{}/record_payment", req.request.merchant_reference_id.get_string_repr())),
method: Method::Post,
request_body: build_invoice_record_back_request_body
);
fn get_chargebee_subscription_items_query_params(
req: &GetSubscriptionItemsRouterData,
) -> CustomResult<String, errors::ConnectorError> {
// Try to get limit from request, else default to 10
let limit = req.request.limit.unwrap_or(10);
let offset = req.request.offset.unwrap_or(0);
let subscription_item_type = match req.request.item_type {
SubscriptionItemType::Plan => "plan",
SubscriptionItemType::Addon => "addon",
};
let param = format!(
"?limit={}&offset={}&type[is]={}",
limit, offset, subscription_item_type
);
Ok(param)
}
impl api::subscriptions::GetSubscriptionItemsFlow for Chargebee {}
impl api::subscriptions::SubscriptionRecordBackFlow for Chargebee {}
impl GetSubscriptionPlansV2 for Chargebee {}
impl
ConnectorIntegrationV2<
GetSubscriptionItems,
GetSubscriptionItemsData,
GetSubscriptionItemsRequest,
GetSubscriptionItemsResponse,
> for Chargebee
{
// Not implemented (R)
}
impl_chargebee_integration!(
flow: GetSubscriptionItems,
flow_type: types::GetSubscriptionPlansType,
request: GetSubscriptionItemsRequest,
response: GetSubscriptionItemsResponse,
router_data: GetSubscriptionItemsRouterData,
connector_response: ChargebeeListPlansResponse,
url_path: |_req| Some("v2/items".to_string()),
method: Method::Get,
query_params: get_chargebee_subscription_items_query_params
);
impl_chargebee_integration!(
flow: CreateConnectorCustomer,
flow_type: types::ConnectorCustomerType,
request: ConnectorCustomerData,
response: PaymentsResponseData,
router_data: ConnectorCustomerRouterData,
connector_response: chargebee::ChargebeeCustomerCreateResponse,
url_path: |_req| Some("v2/customers".to_string()),
method: Method::Post,
request_body: build_connector_customer_request_body
);
impl api::subscriptions::GetSubscriptionPlanPricesFlow for Chargebee {}
fn get_chargebee_plan_prices_query_params(
req: &GetSubscriptionPlanPricesRouterData,
) -> CustomResult<String, errors::ConnectorError> {
let item_id = req.request.item_price_id.to_string();
let params = format!("?item_id[is]={item_id}");
Ok(params)
}
impl_chargebee_integration!(
flow: GetSubscriptionItemPrices,
flow_type: types::GetSubscriptionPlanPricesType,
request: GetSubscriptionItemPricesRequest,
response: GetSubscriptionItemPricesResponse,
router_data: GetSubscriptionPlanPricesRouterData,
connector_response: ChargebeeGetPlanPricesResponse,
url_path: |_req| Some("v2/item_prices".to_string()),
method: Method::Get,
query_params: get_chargebee_plan_prices_query_params
);
impl GetSubscriptionPlanPricesV2 for Chargebee {}
impl
ConnectorIntegrationV2<
GetSubscriptionItemPrices,
GetSubscriptionItemPricesData,
GetSubscriptionItemPricesRequest,
GetSubscriptionItemPricesResponse,
> for Chargebee
{
// TODO: implement functions when support enabled
}
impl api::subscriptions::GetSubscriptionEstimateFlow for Chargebee {}
impl_chargebee_integration!(
flow: GetSubscriptionEstimate,
flow_type: types::GetSubscriptionEstimateType,
request: GetSubscriptionEstimateRequest,
response: GetSubscriptionEstimateResponse,
router_data: GetSubscriptionEstimateRouterData,
connector_response: chargebee::SubscriptionEstimateResponse,
url_path: |_req| Some("v2/estimates/create_subscription_for_items".to_string()),
method: Method::Post,
request_body: build_subscription_estimate_request_body
);
// Pause Subscription Implementation
impl api::subscriptions::SubscriptionPauseFlow for Chargebee {}
impl_chargebee_integration!(
flow: SubscriptionPause,
flow_type: types::SubscriptionPauseType,
request: SubscriptionPauseRequest,
response: SubscriptionPauseResponse,
router_data: SubscriptionPauseRouterData,
connector_response: chargebee::ChargebeePauseSubscriptionResponse,
url_path: |req| Some(format!("v2/subscriptions/{}/pause", req.request.subscription_id.get_string_repr())),
method: Method::Post,
request_body: build_subscription_pause_request_body
);
// Resume Subscription Implementation
impl api::subscriptions::SubscriptionResumeFlow for Chargebee {}
impl_chargebee_integration!(
flow: SubscriptionResume,
flow_type: types::SubscriptionResumeType,
request: SubscriptionResumeRequest,
response: SubscriptionResumeResponse,
router_data: SubscriptionResumeRouterData,
connector_response: chargebee::ChargebeeResumeSubscriptionResponse,
url_path: |req| Some(format!("v2/subscriptions/{}/resume", req.request.subscription_id.get_string_repr())),
method: Method::Post,
request_body: build_subscription_resume_request_body
);
// Cancel Subscription Implementation
impl api::subscriptions::SubscriptionCancelFlow for Chargebee {}
impl_chargebee_integration!(
flow: SubscriptionCancel,
flow_type: types::SubscriptionCancelType,
request: SubscriptionCancelRequest,
response: SubscriptionCancelResponse,
router_data: SubscriptionCancelRouterData,
connector_response: chargebee::ChargebeeCancelSubscriptionResponse,
url_path: |req| Some(format!("v2/subscriptions/{}/cancel_for_items", req.request.subscription_id.get_string_repr())),
method: Method::Post,
request_body: build_subscription_cancel_request_body
);
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Chargebee {
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let base64_signature = utils::get_header_key_value("authorization", request.headers)?;
let signature = base64_signature.as_bytes().to_owned();
Ok(signature)
}
async fn verify_webhook_source(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_label,
connector_webhook_details,
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let signature = self
.get_webhook_source_verification_signature(request, &connector_webhook_secrets)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let password = connector_webhook_secrets
.additional_secret
.ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Failed to get additional secrets")?;
let username = String::from_utf8(connector_webhook_secrets.secret.to_vec())
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Could not convert secret to UTF-8")?;
let secret_auth = format!(
"Basic {}",
base64::engine::general_purpose::STANDARD.encode(format!(
"{}:{}",
username,
password.peek()
))
);
let signature_auth = String::from_utf8(signature.to_vec())
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Could not convert secret to UTF-8")?;
Ok(signature_auth == secret_auth)
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook =
chargebee::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(api_models::webhooks::ObjectReferenceId::InvoiceId(
api_models::webhooks::InvoiceIdType::ConnectorInvoiceId(
webhook.content.invoice.id.get_string_repr().to_string(),
),
))
}
#[cfg(any(feature = "v1", not(all(feature = "revenue_recovery", feature = "v2"))))]
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook =
chargebee::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let subscription_id = webhook.content.invoice.subscription_id;
Ok(api_models::webhooks::ObjectReferenceId::SubscriptionId(
subscription_id,
))
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let webhook =
chargebee::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
let event = api_models::webhooks::IncomingWebhookEvent::from(webhook.event_type);
Ok(event)
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook =
chargebee::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(webhook))
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
fn get_revenue_recovery_attempt_details(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<revenue_recovery::RevenueRecoveryAttemptData, errors::ConnectorError> {
let webhook =
transformers::ChargebeeWebhookBody::get_webhook_object_from_body(request.body)?;
revenue_recovery::RevenueRecoveryAttemptData::try_from(webhook)
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
fn get_revenue_recovery_invoice_details(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<revenue_recovery::RevenueRecoveryInvoiceData, errors::ConnectorError> {
let webhook =
transformers::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)?;
revenue_recovery::RevenueRecoveryInvoiceData::try_from(webhook)
}
fn get_subscription_mit_payment_data(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
hyperswitch_domain_models::router_flow_types::SubscriptionMitPaymentData,
errors::ConnectorError,
> {
let webhook_body =
transformers::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)
.attach_printable("Failed to parse Chargebee invoice webhook body")?;
let chargebee_mit_data = transformers::ChargebeeMitPaymentData::try_from(webhook_body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)
.attach_printable("Failed to extract MIT payment data from Chargebee webhook")?;
// Convert Chargebee-specific data to generic domain model
Ok(
hyperswitch_domain_models::router_flow_types::SubscriptionMitPaymentData {
invoice_id: chargebee_mit_data.invoice_id,
amount_due: chargebee_mit_data.amount_due,
currency_code: chargebee_mit_data.currency_code,
status: chargebee_mit_data.status.map(|s| s.into()),
customer_id: chargebee_mit_data.customer_id,
subscription_id: chargebee_mit_data.subscription_id,
first_invoice: chargebee_mit_data.first_invoice,
},
)
}
}
static CHARGEBEE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Chargebee",
description: "Chargebee is a Revenue Growth Management (RGM) platform that helps subscription businesses manage subscriptions, billing, revenue recognition, collections, and customer retention, essentially streamlining the entire subscription lifecycle.",
connector_type: enums::HyperswitchConnectorCategory::RevenueGrowthManagementPlatform,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static CHARGEBEE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];
impl ConnectorSpecifications for Chargebee {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&CHARGEBEE_CONNECTOR_INFO)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&CHARGEBEE_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__chargebee__transformers.rs
|
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
use std::str::FromStr;
use api_models::subscription as api;
use common_enums::{connector_enums, enums};
use common_utils::{
errors::CustomResult,
ext_traits::ByteSliceExt,
id_type::{CustomerId, InvoiceId, SubscriptionId},
pii::{self, Email},
types::MinorUnit,
};
use error_stack::ResultExt;
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
use hyperswitch_domain_models::revenue_recovery;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{subscriptions::SubscriptionAutoCollection, ResponseId},
router_response_types::{
revenue_recovery::InvoiceRecordBackResponse,
subscriptions::{
self, GetSubscriptionEstimateResponse, GetSubscriptionItemPricesResponse,
GetSubscriptionItemsResponse, SubscriptionCancelResponse, SubscriptionCreateResponse,
SubscriptionInvoiceData, SubscriptionLineItem, SubscriptionPauseResponse,
SubscriptionResumeResponse, SubscriptionStatus,
},
ConnectorCustomerResponseData, PaymentsResponseData, RefundsResponseData,
},
types::{
GetSubscriptionEstimateRouterData, InvoiceRecordBackRouterData,
PaymentsAuthorizeRouterData, RefundsRouterData, SubscriptionCancelRouterData,
SubscriptionPauseRouterData, SubscriptionResumeRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{
convert_connector_response_to_domain_response,
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
// SubscriptionCreate structures
#[derive(Debug, Serialize)]
pub struct ChargebeeSubscriptionCreateRequest {
#[serde(rename = "id")]
pub subscription_id: SubscriptionId,
#[serde(rename = "subscription_items[item_price_id][0]")]
pub item_price_id: String,
#[serde(rename = "subscription_items[quantity][0]")]
pub quantity: Option<u32>,
#[serde(rename = "billing_address[line1]")]
pub billing_address_line1: Option<Secret<String>>,
#[serde(rename = "billing_address[city]")]
pub billing_address_city: Option<String>,
#[serde(rename = "billing_address[state]")]
pub billing_address_state: Option<Secret<String>>,
#[serde(rename = "billing_address[zip]")]
pub billing_address_zip: Option<Secret<String>>,
#[serde(rename = "billing_address[country]")]
pub billing_address_country: Option<common_enums::CountryAlpha2>,
pub auto_collection: ChargebeeAutoCollection,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeAutoCollection {
On,
Off,
}
impl From<SubscriptionAutoCollection> for ChargebeeAutoCollection {
fn from(auto_collection: SubscriptionAutoCollection) -> Self {
match auto_collection {
SubscriptionAutoCollection::On => Self::On,
SubscriptionAutoCollection::Off => Self::Off,
}
}
}
impl TryFrom<&ChargebeeRouterData<&hyperswitch_domain_models::types::SubscriptionCreateRouterData>>
for ChargebeeSubscriptionCreateRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ChargebeeRouterData<&hyperswitch_domain_models::types::SubscriptionCreateRouterData>,
) -> Result<Self, Self::Error> {
let req = &item.router_data.request;
let first_item =
req.subscription_items
.first()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "subscription_items",
})?;
Ok(Self {
subscription_id: req.subscription_id.clone(),
item_price_id: first_item.item_price_id.clone(),
quantity: first_item.quantity,
billing_address_line1: item.router_data.get_optional_billing_line1(),
billing_address_city: item.router_data.get_optional_billing_city(),
billing_address_state: item.router_data.get_optional_billing_state(),
billing_address_zip: item.router_data.get_optional_billing_zip(),
billing_address_country: item.router_data.get_optional_billing_country(),
auto_collection: req.auto_collection.clone().into(),
})
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ChargebeeSubscriptionCreateResponse {
pub subscription: ChargebeeSubscriptionDetails,
pub invoice: Option<ChargebeeInvoiceData>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ChargebeeSubscriptionDetails {
pub id: SubscriptionId,
pub status: ChargebeeSubscriptionStatus,
pub customer_id: CustomerId,
pub currency_code: enums::Currency,
pub total_dues: Option<MinorUnit>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub next_billing_at: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub created_at: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub pause_date: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
cancelled_at: Option<PrimitiveDateTime>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeSubscriptionStatus {
Future,
#[serde(rename = "in_trial")]
InTrial,
Active,
#[serde(rename = "non_renewing")]
NonRenewing,
Paused,
Cancelled,
Transferred,
}
impl From<ChargebeeSubscriptionStatus> for SubscriptionStatus {
fn from(status: ChargebeeSubscriptionStatus) -> Self {
match status {
ChargebeeSubscriptionStatus::Future => Self::Pending,
ChargebeeSubscriptionStatus::InTrial => Self::Trial,
ChargebeeSubscriptionStatus::Active => Self::Active,
ChargebeeSubscriptionStatus::NonRenewing => Self::Onetime,
ChargebeeSubscriptionStatus::Paused => Self::Paused,
ChargebeeSubscriptionStatus::Cancelled => Self::Cancelled,
ChargebeeSubscriptionStatus::Transferred => Self::Cancelled,
}
}
}
convert_connector_response_to_domain_response!(
ChargebeeSubscriptionCreateResponse,
SubscriptionCreateResponse,
|item: ResponseRouterData<_, ChargebeeSubscriptionCreateResponse, _, _>| {
let subscription = &item.response.subscription;
Ok(Self {
response: Ok(SubscriptionCreateResponse {
subscription_id: subscription.id.clone(),
status: subscription.status.clone().into(),
customer_id: subscription.customer_id.clone(),
currency_code: subscription.currency_code,
total_amount: subscription.total_dues.unwrap_or(MinorUnit::new(0)),
next_billing_at: subscription.next_billing_at,
created_at: subscription.created_at,
invoice_details: item.response.invoice.map(SubscriptionInvoiceData::from),
}),
..item.data
})
}
);
//TODO: Fill the struct with respective fields
pub struct ChargebeeRouterData<T> {
pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for ChargebeeRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct ChargebeePaymentsRequest {
amount: MinorUnit,
card: ChargebeeCard,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct ChargebeeCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&ChargebeeRouterData<&PaymentsAuthorizeRouterData>> for ChargebeePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ChargebeeRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = ChargebeeCard {
number: req_card.card_number,
expiry_month: req_card.card_exp_month,
expiry_year: req_card.card_exp_year,
cvc: req_card.card_cvc,
complete: item.router_data.request.is_auto_capture()?,
};
Ok(Self {
amount: item.amount,
card,
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
// Auth Struct
pub struct ChargebeeAuthType {
pub(super) full_access_key_v1: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ChargebeeMetadata {
pub(super) site: Secret<String>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for ChargebeeMetadata {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
impl TryFrom<&ConnectorAuthType> for ChargebeeAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
full_access_key_v1: api_key.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
//TODO: Append the remaining status flags
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ChargebeePaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<ChargebeePaymentStatus> for common_enums::AttemptStatus {
fn from(item: ChargebeePaymentStatus) -> Self {
match item {
ChargebeePaymentStatus::Succeeded => Self::Charged,
ChargebeePaymentStatus::Failed => Self::Failure,
ChargebeePaymentStatus::Processing => Self::Authorizing,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ChargebeePaymentsResponse {
status: ChargebeePaymentStatus,
id: String,
}
convert_connector_response_to_domain_response!(
ChargebeePaymentsResponse,
PaymentsResponseData,
|item: ResponseRouterData<_, ChargebeePaymentsResponse, _, _>| {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
);
//TODO: Fill the struct with respective fields
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct ChargebeeRefundRequest {
pub amount: MinorUnit,
}
impl<F> TryFrom<&ChargebeeRouterData<&RefundsRouterData<F>>> for ChargebeeRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ChargebeeRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct ChargebeeErrorResponse {
pub api_error_code: String,
pub message: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeWebhookBody {
pub content: ChargebeeWebhookContent,
pub event_type: ChargebeeEventType,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeInvoiceBody {
pub content: ChargebeeInvoiceContent,
pub event_type: ChargebeeEventType,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeInvoiceContent {
pub invoice: ChargebeeInvoiceData,
pub subscription: Option<ChargebeeSubscriptionData>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeWebhookContent {
pub transaction: ChargebeeTransactionData,
pub invoice: ChargebeeInvoiceData,
pub customer: Option<ChargebeeCustomer>,
pub subscription: Option<ChargebeeSubscriptionData>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeSubscriptionData {
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub current_term_start: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub next_billing_at: Option<PrimitiveDateTime>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeEventType {
PaymentSucceeded,
PaymentFailed,
InvoiceDeleted,
InvoiceGenerated,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ChargebeeInvoiceData {
// invoice id
pub id: InvoiceId,
pub total: MinorUnit,
pub currency_code: enums::Currency,
pub status: Option<ChargebeeInvoiceStatus>,
pub billing_address: Option<ChargebeeInvoiceBillingAddress>,
pub linked_payments: Option<Vec<ChargebeeInvoicePayments>>,
pub customer_id: CustomerId,
pub subscription_id: SubscriptionId,
pub first_invoice: Option<bool>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ChargebeeInvoicePayments {
pub txn_status: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeTransactionData {
id_at_gateway: Option<String>,
status: ChargebeeTranasactionStatus,
error_code: Option<String>,
error_text: Option<String>,
gateway_account_id: String,
currency_code: enums::Currency,
amount: MinorUnit,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
date: Option<PrimitiveDateTime>,
payment_method: ChargebeeTransactionPaymentMethod,
payment_method_details: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeTransactionPaymentMethod {
Card,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeePaymentMethodDetails {
card: ChargebeeCardDetails,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeCardDetails {
funding_type: ChargebeeFundingType,
brand: common_enums::CardNetwork,
iin: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeFundingType {
Credit,
Debit,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeTranasactionStatus {
// Waiting for response from the payment gateway.
InProgress,
// The transaction is successful.
Success,
// Transaction failed.
Failure,
// No response received while trying to charge the card.
Timeout,
// Indicates that a successful payment transaction has failed now due to a late failure notification from the payment gateway,
// typically caused by issues like insufficient funds or a closed bank account.
LateFailure,
// Connection with Gateway got terminated abruptly. So, status of this transaction needs to be resolved manually
NeedsAttention,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeCustomer {
pub payment_method: ChargebeePaymentMethod,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ChargebeeInvoiceBillingAddress {
pub line1: Option<Secret<String>>,
pub line2: Option<Secret<String>>,
pub line3: Option<Secret<String>>,
pub state: Option<Secret<String>>,
pub country: Option<enums::CountryAlpha2>,
pub zip: Option<Secret<String>>,
pub city: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeePaymentMethod {
pub reference_id: String,
pub gateway: ChargebeeGateway,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeGateway {
Stripe,
Braintree,
}
impl ChargebeeWebhookBody {
pub fn get_webhook_object_from_body(body: &[u8]) -> CustomResult<Self, errors::ConnectorError> {
let webhook_body = body
.parse_struct::<Self>("ChargebeeWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(webhook_body)
}
}
impl ChargebeeInvoiceBody {
pub fn get_invoice_webhook_data_from_body(
body: &[u8],
) -> CustomResult<Self, errors::ConnectorError> {
let webhook_body = body
.parse_struct::<Self>("ChargebeeInvoiceBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(webhook_body)
}
}
// Structure to extract MIT payment data from invoice_generated webhook
#[derive(Debug, Clone)]
pub struct ChargebeeMitPaymentData {
pub invoice_id: InvoiceId,
pub amount_due: MinorUnit,
pub currency_code: enums::Currency,
pub status: Option<ChargebeeInvoiceStatus>,
pub customer_id: CustomerId,
pub subscription_id: SubscriptionId,
pub first_invoice: bool,
}
impl TryFrom<ChargebeeInvoiceBody> for ChargebeeMitPaymentData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(webhook_body: ChargebeeInvoiceBody) -> Result<Self, Self::Error> {
let invoice = webhook_body.content.invoice;
Ok(Self {
invoice_id: invoice.id,
amount_due: invoice.total,
currency_code: invoice.currency_code,
status: invoice.status,
customer_id: invoice.customer_id,
subscription_id: invoice.subscription_id,
first_invoice: invoice.first_invoice.unwrap_or(false),
})
}
}
pub struct ChargebeeMandateDetails {
pub customer_id: String,
pub mandate_id: String,
}
impl ChargebeeCustomer {
// the logic to find connector customer id & mandate id is different for different gateways, reference : https://apidocs.chargebee.com/docs/api/customers?prod_cat_ver=2#customer_payment_method_reference_id .
pub fn find_connector_ids(&self) -> Result<ChargebeeMandateDetails, errors::ConnectorError> {
match self.payment_method.gateway {
ChargebeeGateway::Stripe | ChargebeeGateway::Braintree => {
let mut parts = self.payment_method.reference_id.split('/');
let customer_id = parts
.next()
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?
.to_string();
let mandate_id = parts
.next_back()
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?
.to_string();
Ok(ChargebeeMandateDetails {
customer_id,
mandate_id,
})
}
}
}
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
impl TryFrom<ChargebeeWebhookBody> for revenue_recovery::RevenueRecoveryAttemptData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: ChargebeeWebhookBody) -> Result<Self, Self::Error> {
let amount = item.content.transaction.amount;
let currency = item.content.transaction.currency_code.to_owned();
let merchant_reference_id = common_utils::id_type::PaymentReferenceId::from_str(
item.content.invoice.id.get_string_repr(),
)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let connector_transaction_id = item
.content
.transaction
.id_at_gateway
.map(common_utils::types::ConnectorTransactionId::TxnId);
let error_code = item.content.transaction.error_code.clone();
let error_message = item.content.transaction.error_text.clone();
let connector_mandate_details = item
.content
.customer
.as_ref()
.map(|customer| customer.find_connector_ids())
.transpose()?
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_details",
})?;
let connector_account_reference_id = item.content.transaction.gateway_account_id.clone();
let transaction_created_at = item.content.transaction.date;
let status = enums::AttemptStatus::from(item.content.transaction.status);
let payment_method_type =
enums::PaymentMethod::from(item.content.transaction.payment_method);
let payment_method_details: ChargebeePaymentMethodDetails =
serde_json::from_str(&item.content.transaction.payment_method_details)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let payment_method_sub_type =
enums::PaymentMethodType::from(payment_method_details.card.funding_type);
// Chargebee retry count will always be less than u16 always. Chargebee can have maximum 12 retry attempts
#[allow(clippy::as_conversions)]
let retry_count = item
.content
.invoice
.linked_payments
.map(|linked_payments| linked_payments.len() as u16);
let invoice_next_billing_time = item
.content
.subscription
.as_ref()
.and_then(|subscription| subscription.next_billing_at);
let invoice_billing_started_at_time = item
.content
.subscription
.as_ref()
.and_then(|subscription| subscription.current_term_start);
Ok(Self {
amount,
currency,
merchant_reference_id,
connector_transaction_id,
error_code,
error_message,
processor_payment_method_token: connector_mandate_details.mandate_id,
connector_customer_id: connector_mandate_details.customer_id,
connector_account_reference_id,
transaction_created_at,
status,
payment_method_type,
payment_method_sub_type,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
retry_count,
invoice_next_billing_time,
invoice_billing_started_at_time,
// This field is none because it is specific to stripebilling.
charge_id: None,
// Need to populate these card info field
card_info: api_models::payments::AdditionalCardInfo {
card_network: Some(payment_method_details.card.brand),
card_isin: Some(payment_method_details.card.iin),
card_issuer: None,
card_type: None,
card_issuing_country: None,
card_issuing_country_code: None,
bank_code: None,
last4: None,
card_extended_bin: None,
card_exp_month: None,
card_exp_year: None,
card_holder_name: None,
payment_checks: None,
authentication_data: None,
is_regulated: None,
signature_network: None,
auth_code: None,
},
})
}
}
impl From<ChargebeeTranasactionStatus> for enums::AttemptStatus {
fn from(status: ChargebeeTranasactionStatus) -> Self {
match status {
ChargebeeTranasactionStatus::InProgress
| ChargebeeTranasactionStatus::NeedsAttention => Self::Pending,
ChargebeeTranasactionStatus::Success => Self::Charged,
ChargebeeTranasactionStatus::Failure
| ChargebeeTranasactionStatus::Timeout
| ChargebeeTranasactionStatus::LateFailure => Self::Failure,
}
}
}
impl From<ChargebeeTransactionPaymentMethod> for enums::PaymentMethod {
fn from(payment_method: ChargebeeTransactionPaymentMethod) -> Self {
match payment_method {
ChargebeeTransactionPaymentMethod::Card => Self::Card,
}
}
}
impl From<ChargebeeFundingType> for enums::PaymentMethodType {
fn from(funding_type: ChargebeeFundingType) -> Self {
match funding_type {
ChargebeeFundingType::Credit => Self::Credit,
ChargebeeFundingType::Debit => Self::Debit,
}
}
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
impl From<ChargebeeEventType> for api_models::webhooks::IncomingWebhookEvent {
fn from(event: ChargebeeEventType) -> Self {
match event {
ChargebeeEventType::PaymentSucceeded => Self::RecoveryPaymentSuccess,
ChargebeeEventType::PaymentFailed => Self::RecoveryPaymentFailure,
ChargebeeEventType::InvoiceDeleted => Self::RecoveryInvoiceCancel,
ChargebeeEventType::InvoiceGenerated => Self::InvoiceGenerated,
}
}
}
#[cfg(feature = "v1")]
impl From<ChargebeeEventType> for api_models::webhooks::IncomingWebhookEvent {
fn from(event: ChargebeeEventType) -> Self {
match event {
ChargebeeEventType::PaymentSucceeded => Self::PaymentIntentSuccess,
ChargebeeEventType::PaymentFailed => Self::PaymentIntentFailure,
ChargebeeEventType::InvoiceDeleted => Self::EventNotSupported,
ChargebeeEventType::InvoiceGenerated => Self::InvoiceGenerated,
}
}
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
impl TryFrom<ChargebeeInvoiceBody> for revenue_recovery::RevenueRecoveryInvoiceData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: ChargebeeInvoiceBody) -> Result<Self, Self::Error> {
let merchant_reference_id = common_utils::id_type::PaymentReferenceId::from_str(
item.content.invoice.id.get_string_repr(),
)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
// The retry count will never exceed u16 limit in a billing connector. It can have maximum of 12 in case of charge bee so its ok to suppress this
#[allow(clippy::as_conversions)]
let retry_count = item
.content
.invoice
.linked_payments
.as_ref()
.map(|linked_payments| linked_payments.len() as u16);
let invoice_next_billing_time = item
.content
.subscription
.as_ref()
.and_then(|subscription| subscription.next_billing_at);
let billing_started_at = item
.content
.subscription
.as_ref()
.and_then(|subscription| subscription.current_term_start);
Ok(Self {
amount: item.content.invoice.total,
currency: item.content.invoice.currency_code,
merchant_reference_id,
billing_address: Some(api_models::payments::Address::from(item.content.invoice)),
retry_count,
next_billing_at: invoice_next_billing_time,
billing_started_at,
metadata: None,
// TODO! This field should be handled for billing connnector integrations
enable_partial_authorization: None,
})
}
}
impl From<ChargebeeInvoiceData> for api_models::payments::Address {
fn from(item: ChargebeeInvoiceData) -> Self {
Self {
address: item
.billing_address
.map(api_models::payments::AddressDetails::from),
phone: None,
email: None,
}
}
}
impl From<ChargebeeInvoiceBillingAddress> for api_models::payments::AddressDetails {
fn from(item: ChargebeeInvoiceBillingAddress) -> Self {
Self {
city: item.city,
country: item.country,
state: item.state,
zip: item.zip,
line1: item.line1,
line2: item.line2,
line3: item.line3,
first_name: None,
last_name: None,
origin_zip: None,
}
}
}
#[derive(Debug, Serialize)]
pub struct ChargebeeRecordPaymentRequest {
#[serde(rename = "transaction[amount]")]
pub amount: MinorUnit,
#[serde(rename = "transaction[payment_method]")]
pub payment_method: ChargebeeRecordPaymentMethod,
#[serde(rename = "transaction[id_at_gateway]")]
pub connector_payment_id: Option<String>,
#[serde(rename = "transaction[status]")]
pub status: ChargebeeRecordStatus,
}
#[derive(Debug, Serialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeRecordPaymentMethod {
Other,
}
#[derive(Debug, Serialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeRecordStatus {
Success,
Failure,
}
impl TryFrom<&ChargebeeRouterData<&InvoiceRecordBackRouterData>> for ChargebeeRecordPaymentRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ChargebeeRouterData<&InvoiceRecordBackRouterData>,
) -> Result<Self, Self::Error> {
let req = &item.router_data.request;
Ok(Self {
amount: req.amount,
payment_method: ChargebeeRecordPaymentMethod::Other,
connector_payment_id: req
.connector_transaction_id
.as_ref()
.map(|connector_payment_id| connector_payment_id.get_id().to_string()),
status: ChargebeeRecordStatus::try_from(req.attempt_status)?,
})
}
}
impl TryFrom<enums::AttemptStatus> for ChargebeeRecordStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(status: enums::AttemptStatus) -> Result<Self, Self::Error> {
match status {
enums::AttemptStatus::Charged
| enums::AttemptStatus::PartialCharged
| enums::AttemptStatus::PartialChargedAndChargeable => Ok(Self::Success),
enums::AttemptStatus::Failure
| enums::AttemptStatus::CaptureFailed
| enums::AttemptStatus::RouterDeclined => Ok(Self::Failure),
enums::AttemptStatus::AuthenticationFailed
| enums::AttemptStatus::Started
| enums::AttemptStatus::AuthenticationPending
| enums::AttemptStatus::AuthenticationSuccessful
| enums::AttemptStatus::Authorized
| enums::AttemptStatus::PartiallyAuthorized
| enums::AttemptStatus::AuthorizationFailed
| enums::AttemptStatus::Authorizing
| enums::AttemptStatus::CodInitiated
| enums::AttemptStatus::Voided
| enums::AttemptStatus::VoidedPostCharge
| enums::AttemptStatus::VoidInitiated
| enums::AttemptStatus::CaptureInitiated
| enums::AttemptStatus::VoidFailed
| enums::AttemptStatus::AutoRefunded
| enums::AttemptStatus::Unresolved
| enums::AttemptStatus::Pending
| enums::AttemptStatus::PaymentMethodAwaited
| enums::AttemptStatus::ConfirmationAwaited
| enums::AttemptStatus::DeviceDataCollectionPending
| enums::AttemptStatus::IntegrityFailure
| enums::AttemptStatus::Expired => Err(errors::ConnectorError::NotSupported {
message: "Record back flow is only supported for terminal status".to_string(),
connector: "chargebee",
}
.into()),
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ChargebeeRecordbackResponse {
pub invoice: ChargebeeRecordbackInvoice,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ChargebeeRecordbackInvoice {
pub id: common_utils::id_type::PaymentReferenceId,
}
convert_connector_response_to_domain_response!(
ChargebeeRecordbackResponse,
InvoiceRecordBackResponse,
|item: ResponseRouterData<_, ChargebeeRecordbackResponse, _, _>| {
let merchant_reference_id = item.response.invoice.id;
Ok(Self {
response: Ok(InvoiceRecordBackResponse {
merchant_reference_id,
}),
..item.data
})
}
);
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChargebeeListPlansResponse {
pub list: Vec<ChargebeeItemList>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChargebeeItemList {
pub item: ChargebeeItem,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChargebeeItem {
pub id: String,
pub name: String,
#[serde(rename = "type")]
pub plan_type: String,
pub is_giftable: bool,
pub enabled_for_checkout: bool,
pub enabled_in_portal: bool,
pub metered: bool,
pub deleted: bool,
pub description: Option<String>,
}
convert_connector_response_to_domain_response!(
SubscriptionEstimateResponse,
GetSubscriptionEstimateResponse,
|item: ResponseRouterData<_, SubscriptionEstimateResponse, _, _>| {
let estimate = item.response.estimate;
Ok(Self {
response: Ok(GetSubscriptionEstimateResponse {
sub_total: estimate.invoice_estimate.sub_total,
total: estimate.invoice_estimate.total,
amount_paid: Some(estimate.invoice_estimate.amount_paid),
amount_due: Some(estimate.invoice_estimate.amount_due),
currency: estimate.subscription_estimate.currency_code,
next_billing_at: estimate.subscription_estimate.next_billing_at,
credits_applied: Some(estimate.invoice_estimate.credits_applied),
customer_id: Some(estimate.invoice_estimate.customer_id),
line_items: estimate
.invoice_estimate
.line_items
.into_iter()
.map(|line_item| SubscriptionLineItem {
item_id: line_item.entity_id,
item_type: line_item.entity_type,
description: line_item.description,
amount: line_item.amount,
currency: estimate.invoice_estimate.currency_code,
unit_amount: Some(line_item.unit_amount),
quantity: line_item.quantity,
pricing_model: Some(line_item.pricing_model),
})
.collect(),
}),
..item.data
})
}
);
convert_connector_response_to_domain_response!(
ChargebeeListPlansResponse,
GetSubscriptionItemsResponse,
|item: ResponseRouterData<_, ChargebeeListPlansResponse, _, _>| {
let plans = item
.response
.list
.into_iter()
.map(|plan| subscriptions::SubscriptionItems {
subscription_provider_item_id: plan.item.id,
name: plan.item.name,
description: plan.item.description,
})
.collect();
Ok(Self {
response: Ok(GetSubscriptionItemsResponse { list: plans }),
..item.data
})
}
);
#[derive(Debug, Serialize)]
pub struct ChargebeeCustomerCreateRequest {
#[serde(rename = "id")]
pub customer_id: CustomerId,
#[serde(rename = "first_name")]
pub name: Option<Secret<String>>,
pub email: Option<Email>,
#[serde(rename = "billing_address[first_name]")]
pub billing_address_first_name: Option<Secret<String>>,
#[serde(rename = "billing_address[last_name]")]
pub billing_address_last_name: Option<Secret<String>>,
#[serde(rename = "billing_address[line1]")]
pub billing_address_line1: Option<Secret<String>>,
#[serde(rename = "billing_address[city]")]
pub billing_address_city: Option<String>,
#[serde(rename = "billing_address[state]")]
pub billing_address_state: Option<Secret<String>>,
#[serde(rename = "billing_address[zip]")]
pub billing_address_zip: Option<Secret<String>>,
#[serde(rename = "billing_address[country]")]
pub billing_address_country: Option<String>,
}
impl TryFrom<&ChargebeeRouterData<&hyperswitch_domain_models::types::ConnectorCustomerRouterData>>
for ChargebeeCustomerCreateRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ChargebeeRouterData<&hyperswitch_domain_models::types::ConnectorCustomerRouterData>,
) -> Result<Self, Self::Error> {
let req = &item.router_data.request;
Ok(Self {
customer_id: req
.customer_id
.as_ref()
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "customer_id",
})?
.clone(),
name: req.name.clone(),
email: req.email.clone(),
billing_address_first_name: req
.billing_address
.as_ref()
.and_then(|address| address.first_name.clone()),
billing_address_last_name: req
.billing_address
.as_ref()
.and_then(|address| address.last_name.clone()),
billing_address_line1: req
.billing_address
.as_ref()
.and_then(|addr| addr.line1.clone()),
billing_address_city: req
.billing_address
.as_ref()
.and_then(|addr| addr.city.clone()),
billing_address_country: req
.billing_address
.as_ref()
.and_then(|addr| addr.country.map(|country| country.to_string())),
billing_address_state: req
.billing_address
.as_ref()
.and_then(|addr| addr.state.clone()),
billing_address_zip: req
.billing_address
.as_ref()
.and_then(|addr| addr.zip.clone()),
})
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ChargebeeCustomerCreateResponse {
pub customer: ChargebeeCustomerDetails,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ChargebeeCustomerDetails {
pub id: String,
#[serde(rename = "first_name")]
pub name: Option<Secret<String>>,
pub email: Option<Email>,
pub billing_address: Option<api_models::payments::AddressDetails>,
}
convert_connector_response_to_domain_response!(
ChargebeeCustomerCreateResponse,
PaymentsResponseData,
|item: ResponseRouterData<_, ChargebeeCustomerCreateResponse, _, _>| {
let customer_response = &item.response.customer;
Ok(Self {
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new(
customer_response.id.clone(),
customer_response
.name
.as_ref()
.map(|name| name.clone().expose()),
customer_response
.email
.as_ref()
.map(|email| email.clone().expose().expose()),
customer_response.billing_address.clone(),
),
)),
..item.data
})
}
);
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChargebeeSubscriptionEstimateRequest {
#[serde(rename = "subscription_items[item_price_id][0]")]
pub price_id: String,
}
impl TryFrom<&GetSubscriptionEstimateRouterData> for ChargebeeSubscriptionEstimateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &GetSubscriptionEstimateRouterData) -> Result<Self, Self::Error> {
let price_id = item.request.price_id.to_owned();
Ok(Self { price_id })
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChargebeeGetPlanPricesResponse {
pub list: Vec<ChargebeeGetPlanPriceList>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChargebeeGetPlanPriceList {
pub item_price: ChargebeePlanPriceItem,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChargebeePlanPriceItem {
pub id: String,
pub name: String,
pub currency_code: common_enums::Currency,
pub free_quantity: i64,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub created_at: Option<PrimitiveDateTime>,
pub deleted: bool,
pub item_id: Option<String>,
pub period: i64,
pub period_unit: ChargebeePeriodUnit,
pub trial_period: Option<i64>,
pub trial_period_unit: Option<ChargebeeTrialPeriodUnit>,
pub price: MinorUnit,
pub pricing_model: ChargebeePricingModel,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeePricingModel {
FlatFee,
PerUnit,
Tiered,
Volume,
Stairstep,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeePeriodUnit {
Day,
Week,
Month,
Year,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeTrialPeriodUnit {
Day,
Month,
}
convert_connector_response_to_domain_response!(
ChargebeeGetPlanPricesResponse,
GetSubscriptionItemPricesResponse,
|item: ResponseRouterData<_, ChargebeeGetPlanPricesResponse, _, _>| {
let plan_prices = item
.response
.list
.into_iter()
.map(|prices| subscriptions::SubscriptionItemPrices {
price_id: prices.item_price.id,
item_id: prices.item_price.item_id,
amount: prices.item_price.price,
currency: prices.item_price.currency_code,
interval: match prices.item_price.period_unit {
ChargebeePeriodUnit::Day => subscriptions::PeriodUnit::Day,
ChargebeePeriodUnit::Week => subscriptions::PeriodUnit::Week,
ChargebeePeriodUnit::Month => subscriptions::PeriodUnit::Month,
ChargebeePeriodUnit::Year => subscriptions::PeriodUnit::Year,
},
interval_count: prices.item_price.period,
trial_period: prices.item_price.trial_period,
trial_period_unit: match prices.item_price.trial_period_unit {
Some(ChargebeeTrialPeriodUnit::Day) => Some(subscriptions::PeriodUnit::Day),
Some(ChargebeeTrialPeriodUnit::Month) => Some(subscriptions::PeriodUnit::Month),
None => None,
},
})
.collect();
Ok(Self {
response: Ok(GetSubscriptionItemPricesResponse { list: plan_prices }),
..item.data
})
}
);
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubscriptionEstimateResponse {
pub estimate: ChargebeeEstimate,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChargebeeEstimate {
pub created_at: i64,
/// type of the object will be `estimate`
pub object: String,
pub subscription_estimate: SubscriptionEstimate,
pub invoice_estimate: InvoiceEstimate,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubscriptionEstimate {
pub status: String,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub next_billing_at: Option<PrimitiveDateTime>,
/// type of the object will be `subscription_estimate`
pub object: String,
pub currency_code: enums::Currency,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InvoiceEstimate {
pub recurring: bool,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub date: Option<PrimitiveDateTime>,
pub price_type: String,
pub sub_total: MinorUnit,
pub total: MinorUnit,
pub credits_applied: MinorUnit,
pub amount_paid: MinorUnit,
pub amount_due: MinorUnit,
/// type of the object will be `invoice_estimate`
pub object: String,
pub customer_id: CustomerId,
pub line_items: Vec<LineItem>,
pub currency_code: enums::Currency,
pub round_off_amount: MinorUnit,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineItem {
pub id: String,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub date_from: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub date_to: Option<PrimitiveDateTime>,
pub unit_amount: MinorUnit,
pub quantity: i64,
pub amount: MinorUnit,
pub pricing_model: String,
pub is_taxed: bool,
pub tax_amount: MinorUnit,
/// type of the object will be `line_item`
pub object: String,
pub customer_id: String,
pub description: String,
pub entity_type: String,
pub entity_id: String,
pub discount_amount: MinorUnit,
pub item_level_discount_amount: MinorUnit,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeInvoiceStatus {
Paid,
Posted,
PaymentDue,
NotPaid,
Voided,
#[serde(other)]
Pending,
}
impl From<ChargebeeInvoiceData> for SubscriptionInvoiceData {
fn from(item: ChargebeeInvoiceData) -> Self {
Self {
billing_address: Some(api_models::payments::Address::from(item.clone())),
id: item.id,
total: item.total,
currency_code: item.currency_code,
status: item.status.map(connector_enums::InvoiceStatus::from),
}
}
}
impl From<ChargebeeInvoiceStatus> for connector_enums::InvoiceStatus {
fn from(status: ChargebeeInvoiceStatus) -> Self {
match status {
ChargebeeInvoiceStatus::Paid => Self::InvoicePaid,
ChargebeeInvoiceStatus::Posted => Self::PaymentPendingTimeout,
ChargebeeInvoiceStatus::PaymentDue => Self::PaymentPending,
ChargebeeInvoiceStatus::NotPaid => Self::PaymentFailed,
ChargebeeInvoiceStatus::Voided => Self::Voided,
ChargebeeInvoiceStatus::Pending => Self::InvoiceCreated,
}
}
}
// Pause Subscription structures
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct ChargebeePauseSubscriptionRequest {
#[serde(rename = "pause_option")]
pub pause_option: Option<api::PauseOption>,
#[serde(rename = "resume_date", skip_serializing_if = "Option::is_none")]
pub resume_date: Option<i64>,
}
impl From<&SubscriptionPauseRouterData> for ChargebeePauseSubscriptionRequest {
fn from(req: &SubscriptionPauseRouterData) -> Self {
Self {
pause_option: req.request.pause_option.clone(),
resume_date: req
.request
.pause_date
.map(|date| date.assume_utc().unix_timestamp()),
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ChargebeePauseSubscriptionResponse {
pub subscription: ChargebeeSubscriptionDetails,
}
// Resume Subscription structures
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct ChargebeeResumeSubscriptionRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub resume_option: Option<api::ResumeOption>,
#[serde(skip_serializing_if = "Option::is_none")]
pub resume_date: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub charges_handling: Option<api::ChargesHandling>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unpaid_invoices_handling: Option<api::UnpaidInvoicesHandling>,
}
impl From<&SubscriptionResumeRouterData> for ChargebeeResumeSubscriptionRequest {
fn from(req: &SubscriptionResumeRouterData) -> Self {
Self {
resume_option: req.request.resume_option.clone(),
resume_date: req
.request
.resume_date
.map(|date| date.assume_utc().unix_timestamp()),
charges_handling: req.request.charges_handling.clone(),
unpaid_invoices_handling: req.request.unpaid_invoices_handling.clone(),
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ChargebeeResumeSubscriptionResponse {
pub subscription: ChargebeeSubscriptionDetails,
}
// Cancel Subscription structures
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct ChargebeeCancelSubscriptionRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub cancel_at: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cancel_option: Option<api::CancelOption>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unbilled_charges_option: Option<api::UnbilledChargesOption>,
#[serde(skip_serializing_if = "Option::is_none")]
pub credit_option_for_current_term_charges: Option<api::CreditOption>,
#[serde(skip_serializing_if = "Option::is_none")]
pub account_receivables_handling: Option<api::AccountReceivablesHandling>,
#[serde(skip_serializing_if = "Option::is_none")]
pub refundable_credits_handling: Option<api::RefundableCreditsHandling>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cancel_reason_code: Option<String>,
}
impl From<&SubscriptionCancelRouterData> for ChargebeeCancelSubscriptionRequest {
fn from(req: &SubscriptionCancelRouterData) -> Self {
Self {
cancel_at: req
.request
.cancel_date
.map(|date| date.assume_utc().unix_timestamp()),
cancel_option: req.request.cancel_option.clone(),
unbilled_charges_option: req.request.unbilled_charges_option.clone(),
credit_option_for_current_term_charges: req
.request
.credit_option_for_current_term_charges
.clone(),
account_receivables_handling: req.request.account_receivables_handling.clone(),
refundable_credits_handling: req.request.refundable_credits_handling.clone(),
cancel_reason_code: req.request.cancel_reason_code.clone(),
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ChargebeeCancelSubscriptionResponse {
pub subscription: ChargebeeSubscriptionDetails,
}
convert_connector_response_to_domain_response!(
ChargebeePauseSubscriptionResponse,
SubscriptionPauseResponse,
|item: ResponseRouterData<_, ChargebeePauseSubscriptionResponse, _, _>| {
let subscription = item.response.subscription;
Ok(Self {
response: Ok(SubscriptionPauseResponse {
subscription_id: subscription.id.clone(),
status: subscription.status.clone().into(),
paused_at: subscription.pause_date,
}),
..item.data
})
}
);
convert_connector_response_to_domain_response!(
ChargebeeResumeSubscriptionResponse,
SubscriptionResumeResponse,
|item: ResponseRouterData<_, ChargebeeResumeSubscriptionResponse, _, _>| {
let subscription = item.response.subscription;
Ok(Self {
response: Ok(SubscriptionResumeResponse {
subscription_id: subscription.id.clone(),
status: subscription.status.clone().into(),
next_billing_at: subscription.next_billing_at,
}),
..item.data
})
}
);
convert_connector_response_to_domain_response!(
ChargebeeCancelSubscriptionResponse,
SubscriptionCancelResponse,
|item: ResponseRouterData<_, ChargebeeCancelSubscriptionResponse, _, _>| {
let subscription = item.response.subscription;
Ok(Self {
response: Ok(SubscriptionCancelResponse {
subscription_id: subscription.id.clone(),
status: subscription.status.clone().into(),
cancelled_at: subscription.cancelled_at,
}),
..item.data
})
}
);
|
crates__hyperswitch_connectors__src__connectors__checkbook.rs
|
pub mod transformers;
use std::sync::LazyLock;
use api_models::{enums, payments::PaymentIdType};
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask};
use transformers as checkbook;
use crate::{constants::headers, types::ResponseRouterData};
#[derive(Clone)]
pub struct Checkbook {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Checkbook {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Checkbook {}
impl api::PaymentSession for Checkbook {}
impl api::ConnectorAccessToken for Checkbook {}
impl api::MandateSetup for Checkbook {}
impl api::PaymentAuthorize for Checkbook {}
impl api::PaymentSync for Checkbook {}
impl api::PaymentCapture for Checkbook {}
impl api::PaymentVoid for Checkbook {}
impl api::Refund for Checkbook {}
impl api::RefundExecute for Checkbook {}
impl api::RefundSync for Checkbook {}
impl api::PaymentToken for Checkbook {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Checkbook
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Checkbook
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Checkbook {
fn id(&self) -> &'static str {
"checkbook"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.checkbook.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = checkbook::CheckbookAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_key = format!(
"{}:{}",
auth.publishable_key.expose(),
auth.secret_key.expose()
);
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth_key.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: checkbook::CheckbookErrorResponse = res
.response
.parse_struct("CheckbookErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code,
message: response.message,
reason: response.reason,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Checkbook {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Checkbook {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Checkbook {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Checkbook
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Checkbook {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/v3/invoice", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = self
.amount_converter
.convert(req.request.minor_amount, req.request.currency)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let connector_req = checkbook::CheckbookPaymentsRequest::try_from((amount, req))?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: checkbook::CheckbookPaymentsResponse = res
.response
.parse_struct("Checkbook PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Checkbook {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_txn_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/v3/invoice/{}",
self.base_url(connectors),
connector_txn_id
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: checkbook::CheckbookPaymentsResponse = res
.response
.parse_struct("checkbook PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Checkbook {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Checkbook {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}v3/invoice/{}",
self.base_url(connectors),
req.request.connector_transaction_id
))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Delete)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: checkbook::CheckbookPaymentsResponse = res
.response
.parse_struct("Checkbook PaymentsCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Checkbook {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "Refunds are not supported".to_string(),
connector: "checkbook",
}
.into())
}
fn get_request_body(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "Refunds are not supported".to_string(),
connector: "checkbook",
}
.into())
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
_data: &RefundsRouterData<Execute>,
_event_builder: Option<&mut ConnectorEvent>,
_res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("Refunds are not supported".to_string()).into())
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Checkbook {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
_data: &RefundSyncRouterData,
_event_builder: Option<&mut ConnectorEvent>,
_res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("Refunds are not supported".to_string()).into())
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Checkbook {
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let details: checkbook::CheckbookPaymentsResponse = request
.body
.parse_struct("CheckbookWebhookResponse")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
PaymentIdType::ConnectorTransactionId(details.id),
))
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let details: checkbook::CheckbookPaymentsResponse = request
.body
.parse_struct("CheckbookWebhookResponse")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(api_models::webhooks::IncomingWebhookEvent::from(
details.status,
))
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let details: checkbook::CheckbookPaymentsResponse = request
.body
.parse_struct("CheckbookWebhookResponse")
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(details))
}
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let header_value = request
.headers
.get("signature")
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)
.attach_printable("Failed to get signature for checkbook")?
.to_str()
.map_err(|_| errors::ConnectorError::WebhookSignatureNotFound)
.attach_printable("Failed to get signature for checkbook")?;
let signature = header_value
.split(',')
.find_map(|s| s.strip_prefix("signature="))
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)?;
hex::decode(signature)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)
.attach_printable("Failed to decrypt checkbook webhook payload for verification")
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let header_value = request
.headers
.get("signature")
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)?
.to_str()
.map_err(|_| errors::ConnectorError::WebhookSignatureNotFound)?;
let nonce = header_value
.split(',')
.find_map(|s| s.strip_prefix("nonce="))
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)?;
let message = format!("{}{}", String::from_utf8_lossy(request.body), nonce);
Ok(message.into_bytes())
}
}
static CHECKBOOK_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![enums::CaptureMethod::Automatic];
let mut checkbook_supported_payment_methods = SupportedPaymentMethods::new();
checkbook_supported_payment_methods.add(
enums::PaymentMethod::BankTransfer,
enums::PaymentMethodType::Ach,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods,
specific_features: None,
},
);
checkbook_supported_payment_methods
});
static CHECKBOOK_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Checkbook",
description:
"Checkbook is a payment platform that allows users to send and receive digital checks.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: common_enums::ConnectorIntegrationStatus::Beta,
};
static CHECKBOOK_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];
impl ConnectorSpecifications for Checkbook {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&CHECKBOOK_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*CHECKBOOK_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&CHECKBOOK_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__checkout.rs
|
pub mod transformers;
use std::{convert::TryFrom, sync::LazyLock};
use common_enums::{enums, CallConnectorAction, PaymentAction};
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{
AmountConvertor, MinorUnit, MinorUnitForConnector, StringMinorUnit,
StringMinorUnitForConnector,
},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
Accept, Defend, Evidence, Retrieve, Upload,
},
router_request_types::{
AcceptDisputeRequestData, AccessTokenRequestData, DefendDisputeRequestData,
PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData,
PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData,
RetrieveFileRequestData, SetupMandateRequestData, SubmitEvidenceRequestData,
SyncRequestType, UploadFileRequestData,
},
router_response_types::{
AcceptDisputeResponse, ConnectorInfo, DefendDisputeResponse, PaymentMethodDetails,
PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse,
SupportedPaymentMethods, SupportedPaymentMethodsExt, UploadFileResponse,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundsRouterData, SetupMandateRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self,
disputes::{AcceptDispute, DefendDispute, Dispute, SubmitEvidence},
files::{FilePurpose, FileUpload, RetrieveFile, UploadFile},
CaptureSyncMethod, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration,
ConnectorSpecifications, ConnectorValidation, MandateSetup,
},
configs::Connectors,
consts,
disputes::DisputePayload,
errors,
events::connector_api_logs::ConnectorEvent,
types::{
AcceptDisputeType, DefendDisputeType, PaymentsAuthorizeType, PaymentsCaptureType,
PaymentsSyncType, PaymentsVoidType, RefundExecuteType, RefundSyncType, Response,
SetupMandateType, SubmitEvidenceType, TokenizationType, UploadFileType,
},
webhooks,
};
use masking::{Mask, Maskable, PeekInterface};
use transformers::CheckoutErrorResponse;
use self::transformers as checkout;
use crate::{
constants::headers,
types::{
AcceptDisputeRouterData, DefendDisputeRouterData, ResponseRouterData,
SubmitEvidenceRouterData, UploadFileRouterData,
},
utils::{
self, is_mandate_supported, ConnectorErrorType, PaymentMethodDataType, RefundsRequestData,
},
};
#[derive(Clone)]
pub struct Checkout {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
amount_converter_webhooks: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Checkout {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
amount_converter_webhooks: &StringMinorUnitForConnector,
}
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Checkout
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Checkout {
fn id(&self) -> &'static str {
"checkout"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = checkout::CheckoutAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", auth.api_secret.peek()).into_masked(),
)])
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.checkout.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: CheckoutErrorResponse = if res.response.is_empty() {
let (error_codes, error_type) = if res.status_code == 401 {
(
Some(vec!["Invalid api key".to_string()]),
Some("invalid_api_key".to_string()),
)
} else {
(None, None)
};
CheckoutErrorResponse {
request_id: None,
error_codes,
error_type,
}
} else {
res.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?
};
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let errors_list = response.error_codes.clone().unwrap_or_default();
let option_error_code_message = utils::get_error_code_error_message_based_on_priority(
self.clone(),
errors_list
.into_iter()
.map(|errors| errors.into())
.collect(),
);
Ok(ErrorResponse {
status_code: res.status_code,
code: option_error_code_message
.clone()
.map(|error_code_message| error_code_message.error_code)
.unwrap_or(consts::NO_ERROR_CODE.to_string()),
message: option_error_code_message
.map(|error_code_message| error_code_message.error_message)
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: response
.error_codes
.map(|errors| errors.join(" & "))
.or(response.error_type),
attempt_status: None,
connector_transaction_id: response.request_id,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Checkout {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::NetworkTransactionIdAndCardDetails,
PaymentMethodDataType::GooglePay,
PaymentMethodDataType::ApplePay,
]);
is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
fn validate_connector_against_payment_request(
&self,
capture_method: Option<enums::CaptureMethod>,
_payment_method: enums::PaymentMethod,
_pmt: Option<enums::PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
match capture_method {
enums::CaptureMethod::Automatic
| enums::CaptureMethod::SequentialAutomatic
| enums::CaptureMethod::Manual
| enums::CaptureMethod::ManualMultiple => Ok(()),
enums::CaptureMethod::Scheduled => Err(utils::construct_not_implemented_error_report(
capture_method,
self.id(),
)),
}
}
}
impl api::Payment for Checkout {}
impl api::PaymentAuthorize for Checkout {}
impl api::PaymentSync for Checkout {}
impl api::PaymentVoid for Checkout {}
impl api::PaymentCapture for Checkout {}
impl api::PaymentSession for Checkout {}
impl api::ConnectorAccessToken for Checkout {}
impl AcceptDispute for Checkout {}
impl api::PaymentToken for Checkout {}
impl Dispute for Checkout {}
impl RetrieveFile for Checkout {}
impl DefendDispute for Checkout {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Checkout
{
fn get_headers(
&self,
req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.common_get_content_type().to_string().into(),
)];
let api_key = checkout::CheckoutAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let mut auth = vec![(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", api_key.api_key.peek()).into_masked(),
)];
header.append(&mut auth);
Ok(header)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}tokens", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = checkout::TokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(TokenizationType::get_headers(self, req, connectors)?)
.set_body(TokenizationType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &TokenizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<TokenizationRouterData, errors::ConnectorError>
where
PaymentsResponseData: Clone,
{
let response: checkout::CheckoutTokenResponse = res
.response
.parse_struct("CheckoutTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Checkout {
// Not Implemented (R)
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Checkout {
// Not Implemented (R)
}
impl MandateSetup for Checkout {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Checkout
{
fn get_headers(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
_req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "payments"))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let authorize_req = utils::convert_payment_authorize_router_response((
req,
utils::convert_setup_mandate_router_data_to_authorize_router_data(req),
));
let amount = utils::convert_amount(
self.amount_converter,
authorize_req.request.minor_amount,
authorize_req.request.currency,
)?;
let connector_router_data = checkout::CheckoutRouterData::from((amount, &authorize_req));
let connector_req = checkout::PaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(SetupMandateType::get_headers(self, req, connectors)?)
.set_body(SetupMandateType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
errors::ConnectorError,
> {
let response: checkout::PaymentsResponse = res
.response
.parse_struct("PaymentIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Checkout {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req.request.connector_transaction_id.as_str();
Ok(format!(
"{}payments/{id}/captures",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = checkout::CheckoutRouterData::from((amount, req));
let connector_req = checkout::PaymentCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
.set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: checkout::PaymentCaptureResponse = res
.response
.parse_struct("CaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Checkout {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let suffix = match req.request.sync_type {
SyncRequestType::MultipleCaptureSync(_) => "/actions",
SyncRequestType::SinglePaymentSync => "",
};
Ok(format!(
"{}{}{}{}",
self.base_url(connectors),
"payments/",
req.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
suffix
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError>
where
PSync: Clone,
PaymentsSyncData: Clone,
PaymentsResponseData: Clone,
{
match &data.request.sync_type {
SyncRequestType::MultipleCaptureSync(_) => {
let response: checkout::PaymentsResponseEnum = res
.response
.parse_struct("checkout::PaymentsResponseEnum")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
SyncRequestType::SinglePaymentSync => {
let response: checkout::PaymentsResponse = res
.response
.parse_struct("PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
}
}
fn get_multiple_capture_sync_method(
&self,
) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> {
Ok(CaptureSyncMethod::Bulk)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Checkout {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "payments"))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = checkout::CheckoutRouterData::from((amount, req));
let connector_req = checkout::PaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: checkout::PaymentsResponse = res
.response
.parse_struct("PaymentIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Checkout {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}payments/{}/voids",
self.base_url(connectors),
&req.request.connector_transaction_id
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = checkout::PaymentVoidRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let mut response: checkout::PaymentVoidResponse = res
.response
.parse_struct("PaymentVoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
response.status = res.status_code;
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::Refund for Checkout {}
impl api::RefundExecute for Checkout {}
impl api::RefundSync for Checkout {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Checkout {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}payments/{}/refunds",
self.base_url(connectors),
id
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = checkout::CheckoutRouterData::from((amount, req));
let connector_req = checkout::RefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: checkout::RefundResponse = res
.response
.parse_struct("checkout::RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let response = checkout::CheckoutRefundResponse {
response,
status: res.status_code,
};
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Checkout {
fn get_headers(
&self,
req: &RefundsRouterData<RSync>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &RefundsRouterData<RSync>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/payments/{}/actions",
self.base_url(connectors),
id
))
}
fn build_request(
&self,
req: &RefundsRouterData<RSync>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundsRouterData<RSync>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<RSync>, errors::ConnectorError> {
let refund_action_id = data.request.get_connector_refund_id()?;
let response: Vec<checkout::ActionResponse> = res
.response
.parse_struct("checkout::CheckoutRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let response = response
.iter()
.find(|&x| x.action_id.clone() == refund_action_id)
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse> for Checkout {
fn get_headers(
&self,
req: &AcceptDisputeRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
AcceptDisputeType::get_content_type(self).to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_url(
&self,
req: &AcceptDisputeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}{}",
self.base_url(connectors),
"disputes/",
req.request.connector_dispute_id,
"/accept"
))
}
fn build_request(
&self,
req: &AcceptDisputeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&AcceptDisputeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(AcceptDisputeType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &AcceptDisputeRouterData,
_event_builder: Option<&mut ConnectorEvent>,
_res: Response,
) -> CustomResult<AcceptDisputeRouterData, errors::ConnectorError> {
Ok(AcceptDisputeRouterData {
response: Ok(AcceptDisputeResponse {
dispute_status: enums::DisputeStatus::DisputeAccepted,
connector_status: None,
}),
..data.clone()
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl UploadFile for Checkout {}
impl ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse> for Checkout {}
#[async_trait::async_trait]
impl FileUpload for Checkout {
fn validate_file_upload(
&self,
purpose: FilePurpose,
file_size: i32,
file_type: mime::Mime,
) -> CustomResult<(), errors::ConnectorError> {
match purpose {
FilePurpose::DisputeEvidence => {
let supported_file_types =
["image/jpeg", "image/jpg", "image/png", "application/pdf"];
// 4 Megabytes (MB)
if file_size > 4000000 {
Err(errors::ConnectorError::FileValidationFailed {
reason: "file_size exceeded the max file size of 4MB".to_owned(),
})?
}
if !supported_file_types.contains(&file_type.to_string().as_str()) {
Err(errors::ConnectorError::FileValidationFailed {
reason: "file_type does not match JPEG, JPG, PNG, or PDF format".to_owned(),
})?
}
}
}
Ok(())
}
}
impl ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse> for Checkout {
fn get_headers(
&self,
req: &RouterData<Upload, UploadFileRequestData, UploadFileResponse>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.get_auth_header(&req.connector_auth_type)
}
fn get_content_type(&self) -> &'static str {
"multipart/form-data"
}
fn get_url(
&self,
_req: &UploadFileRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "files"))
}
fn get_request_body(
&self,
req: &UploadFileRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
transformers::construct_file_upload_request(req.clone())
}
fn build_request(
&self,
req: &UploadFileRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&UploadFileType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(UploadFileType::get_headers(self, req, connectors)?)
.set_body(UploadFileType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &UploadFileRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<Upload, UploadFileRequestData, UploadFileResponse>,
errors::ConnectorError,
> {
let response: checkout::FileUploadResponse = res
.response
.parse_struct("Checkout FileUploadResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(UploadFileRouterData {
response: Ok(UploadFileResponse {
provider_file_id: response.file_id,
}),
..data.clone()
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl SubmitEvidence for Checkout {}
impl ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>
for Checkout
{
fn get_headers(
&self,
req: &SubmitEvidenceRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
SubmitEvidenceType::get_content_type(self)
.to_string()
.into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_url(
&self,
req: &SubmitEvidenceRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}disputes/{}/evidence",
self.base_url(connectors),
req.request.connector_dispute_id,
))
}
fn get_request_body(
&self,
req: &SubmitEvidenceRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = checkout::Evidence::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &SubmitEvidenceRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Put)
.url(&SubmitEvidenceType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(SubmitEvidenceType::get_headers(self, req, connectors)?)
.set_body(SubmitEvidenceType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &SubmitEvidenceRouterData,
_event_builder: Option<&mut ConnectorEvent>,
_res: Response,
) -> CustomResult<SubmitEvidenceRouterData, errors::ConnectorError> {
Ok(SubmitEvidenceRouterData {
response: Ok(SubmitEvidenceResponse {
dispute_status: api_models::enums::DisputeStatus::DisputeChallenged,
connector_status: None,
}),
..data.clone()
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse> for Checkout {
fn get_headers(
&self,
req: &DefendDisputeRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
DefendDisputeType::get_content_type(self).to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_url(
&self,
req: &DefendDisputeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}disputes/{}/evidence",
self.base_url(connectors),
req.request.connector_dispute_id,
))
}
fn build_request(
&self,
req: &DefendDisputeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&DefendDisputeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(DefendDisputeType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &DefendDisputeRouterData,
_event_builder: Option<&mut ConnectorEvent>,
_res: Response,
) -> CustomResult<DefendDisputeRouterData, errors::ConnectorError> {
Ok(DefendDisputeRouterData {
response: Ok(DefendDisputeResponse {
dispute_status: enums::DisputeStatus::DisputeChallenged,
connector_status: None,
}),
..data.clone()
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Checkout {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let signature = utils::get_header_key_value("cko-signature", request.headers)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
hex::decode(signature).change_context(errors::ConnectorError::WebhookSignatureNotFound)
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(format!("{}", String::from_utf8_lossy(request.body)).into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let details: checkout::CheckoutWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let ref_id: api_models::webhooks::ObjectReferenceId =
if checkout::is_chargeback_event(&details.transaction_type) {
let reference = match details.data.reference {
Some(reference) => {
api_models::payments::PaymentIdType::PaymentAttemptId(reference)
}
None => api_models::payments::PaymentIdType::ConnectorTransactionId(
details
.data
.payment_id
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?,
),
};
api_models::webhooks::ObjectReferenceId::PaymentId(reference)
} else if checkout::is_refund_event(&details.transaction_type) {
let refund_reference = match details.data.reference {
Some(reference) => api_models::webhooks::RefundIdType::RefundId(reference),
None => api_models::webhooks::RefundIdType::ConnectorRefundId(
details
.data
.action_id
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?,
),
};
api_models::webhooks::ObjectReferenceId::RefundId(refund_reference)
} else {
let reference_id = match details.data.reference {
Some(reference) => {
api_models::payments::PaymentIdType::PaymentAttemptId(reference)
}
None => {
api_models::payments::PaymentIdType::ConnectorTransactionId(details.data.id)
}
};
api_models::webhooks::ObjectReferenceId::PaymentId(reference_id)
};
Ok(ref_id)
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let details: checkout::CheckoutWebhookEventTypeBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(api_models::webhooks::IncomingWebhookEvent::from(
details.transaction_type,
))
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let event_type_data: checkout::CheckoutWebhookEventTypeBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
if checkout::is_chargeback_event(&event_type_data.transaction_type) {
let dispute_webhook_body: checkout::CheckoutDisputeWebhookBody = request
.body
.parse_struct("CheckoutDisputeWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Box::new(dispute_webhook_body.data))
} else if checkout::is_refund_event(&event_type_data.transaction_type) {
Ok(Box::new(checkout::RefundResponse::try_from(request)?))
} else {
Ok(Box::new(checkout::PaymentsResponse::try_from(request)?))
}
}
fn get_dispute_details(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<DisputePayload, errors::ConnectorError> {
let dispute_details: checkout::CheckoutDisputeWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let amount = utils::convert_amount(
self.amount_converter_webhooks,
dispute_details.data.amount,
dispute_details.data.currency,
)?;
Ok(DisputePayload {
amount,
currency: dispute_details.data.currency,
dispute_stage: api_models::enums::DisputeStage::from(
dispute_details.transaction_type.clone(),
),
connector_dispute_id: dispute_details.data.id,
connector_reason: None,
connector_reason_code: dispute_details.data.reason_code,
challenge_required_by: dispute_details.data.evidence_required_by,
connector_status: dispute_details.transaction_type.to_string(),
created_at: dispute_details.created_on,
updated_at: dispute_details.data.date,
})
}
}
impl api::ConnectorRedirectResponse for Checkout {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
action: PaymentAction,
) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
match action {
PaymentAction::PSync
| PaymentAction::CompleteAuthorize
| PaymentAction::PaymentAuthenticateCompleteAuthorize => {
Ok(CallConnectorAction::Trigger)
}
}
}
}
impl utils::ConnectorErrorTypeMapping for Checkout {
fn get_connector_error_type(
&self,
error_code: String,
_error_message: String,
) -> ConnectorErrorType {
match error_code.as_str() {
"action_failure_limit_exceeded" => ConnectorErrorType::BusinessError,
"address_invalid" => ConnectorErrorType::UserError,
"amount_exceeds_balance" => ConnectorErrorType::BusinessError,
"amount_invalid" => ConnectorErrorType::UserError,
"api_calls_quota_exceeded" => ConnectorErrorType::TechnicalError,
"billing_descriptor_city_invalid" => ConnectorErrorType::UserError,
"billing_descriptor_city_required" => ConnectorErrorType::UserError,
"billing_descriptor_name_invalid" => ConnectorErrorType::UserError,
"billing_descriptor_name_required" => ConnectorErrorType::UserError,
"business_invalid" => ConnectorErrorType::BusinessError,
"business_settings_missing" => ConnectorErrorType::BusinessError,
"capture_value_greater_than_authorized" => ConnectorErrorType::BusinessError,
"capture_value_greater_than_remaining_authorized" => ConnectorErrorType::BusinessError,
"card_authorization_failed" => ConnectorErrorType::UserError,
"card_disabled" => ConnectorErrorType::UserError,
"card_expired" => ConnectorErrorType::UserError,
"card_expiry_month_invalid" => ConnectorErrorType::UserError,
"card_expiry_month_required" => ConnectorErrorType::UserError,
"card_expiry_year_invalid" => ConnectorErrorType::UserError,
"card_expiry_year_required" => ConnectorErrorType::UserError,
"card_holder_invalid" => ConnectorErrorType::UserError,
"card_not_found" => ConnectorErrorType::UserError,
"card_number_invalid" => ConnectorErrorType::UserError,
"card_number_required" => ConnectorErrorType::UserError,
"channel_details_invalid" => ConnectorErrorType::BusinessError,
"channel_url_missing" => ConnectorErrorType::BusinessError,
"charge_details_invalid" => ConnectorErrorType::BusinessError,
"city_invalid" => ConnectorErrorType::BusinessError,
"country_address_invalid" => ConnectorErrorType::UserError,
"country_invalid" => ConnectorErrorType::UserError,
"country_phone_code_invalid" => ConnectorErrorType::UserError,
"country_phone_code_length_invalid" => ConnectorErrorType::UserError,
"currency_invalid" => ConnectorErrorType::UserError,
"currency_required" => ConnectorErrorType::UserError,
"customer_already_exists" => ConnectorErrorType::BusinessError,
"customer_email_invalid" => ConnectorErrorType::UserError,
"customer_id_invalid" => ConnectorErrorType::BusinessError,
"customer_not_found" => ConnectorErrorType::BusinessError,
"customer_number_invalid" => ConnectorErrorType::UserError,
"customer_plan_edit_failed" => ConnectorErrorType::BusinessError,
"customer_plan_id_invalid" => ConnectorErrorType::BusinessError,
"cvv_invalid" => ConnectorErrorType::UserError,
"email_in_use" => ConnectorErrorType::BusinessError,
"email_invalid" => ConnectorErrorType::UserError,
"email_required" => ConnectorErrorType::UserError,
"endpoint_invalid" => ConnectorErrorType::TechnicalError,
"expiry_date_format_invalid" => ConnectorErrorType::UserError,
"fail_url_invalid" => ConnectorErrorType::TechnicalError,
"first_name_required" => ConnectorErrorType::UserError,
"last_name_required" => ConnectorErrorType::UserError,
"ip_address_invalid" => ConnectorErrorType::UserError,
"issuer_network_unavailable" => ConnectorErrorType::TechnicalError,
"metadata_key_invalid" => ConnectorErrorType::BusinessError,
"parameter_invalid" => ConnectorErrorType::UserError,
"password_invalid" => ConnectorErrorType::UserError,
"payment_expired" => ConnectorErrorType::BusinessError,
"payment_invalid" => ConnectorErrorType::BusinessError,
"payment_method_invalid" => ConnectorErrorType::UserError,
"payment_source_required" => ConnectorErrorType::UserError,
"payment_type_invalid" => ConnectorErrorType::UserError,
"phone_number_invalid" => ConnectorErrorType::UserError,
"phone_number_length_invalid" => ConnectorErrorType::UserError,
"previous_payment_id_invalid" => ConnectorErrorType::BusinessError,
"recipient_account_number_invalid" => ConnectorErrorType::BusinessError,
"recipient_account_number_required" => ConnectorErrorType::UserError,
"recipient_dob_required" => ConnectorErrorType::UserError,
"recipient_last_name_required" => ConnectorErrorType::UserError,
"recipient_zip_invalid" => ConnectorErrorType::UserError,
"recipient_zip_required" => ConnectorErrorType::UserError,
"recurring_plan_exists" => ConnectorErrorType::BusinessError,
"recurring_plan_not_exist" => ConnectorErrorType::BusinessError,
"recurring_plan_removal_failed" => ConnectorErrorType::BusinessError,
"request_invalid" => ConnectorErrorType::UserError,
"request_json_invalid" => ConnectorErrorType::UserError,
"risk_enabled_required" => ConnectorErrorType::BusinessError,
"server_api_not_allowed" => ConnectorErrorType::TechnicalError,
"source_email_invalid" => ConnectorErrorType::UserError,
"source_email_required" => ConnectorErrorType::UserError,
"source_id_invalid" => ConnectorErrorType::BusinessError,
"source_id_or_email_required" => ConnectorErrorType::UserError,
"source_id_required" => ConnectorErrorType::UserError,
"source_id_unknown" => ConnectorErrorType::BusinessError,
"source_invalid" => ConnectorErrorType::BusinessError,
"source_or_destination_required" => ConnectorErrorType::BusinessError,
"source_token_invalid" => ConnectorErrorType::BusinessError,
"source_token_required" => ConnectorErrorType::UserError,
"source_token_type_required" => ConnectorErrorType::UserError,
"source_token_type_invalid" => ConnectorErrorType::BusinessError,
"source_type_required" => ConnectorErrorType::UserError,
"sub_entities_count_invalid" => ConnectorErrorType::BusinessError,
"success_url_invalid" => ConnectorErrorType::BusinessError,
"3ds_malfunction" => ConnectorErrorType::TechnicalError,
"3ds_not_configured" => ConnectorErrorType::BusinessError,
"3ds_not_enabled_for_card" => ConnectorErrorType::BusinessError,
"3ds_not_supported" => ConnectorErrorType::BusinessError,
"3ds_payment_required" => ConnectorErrorType::BusinessError,
"token_expired" => ConnectorErrorType::BusinessError,
"token_in_use" => ConnectorErrorType::BusinessError,
"token_invalid" => ConnectorErrorType::BusinessError,
"token_required" => ConnectorErrorType::UserError,
"token_type_required" => ConnectorErrorType::UserError,
"token_used" => ConnectorErrorType::BusinessError,
"void_amount_invalid" => ConnectorErrorType::BusinessError,
"wallet_id_invalid" => ConnectorErrorType::BusinessError,
"zip_invalid" => ConnectorErrorType::UserError,
"processing_key_required" => ConnectorErrorType::BusinessError,
"processing_value_required" => ConnectorErrorType::BusinessError,
"3ds_version_invalid" => ConnectorErrorType::BusinessError,
"3ds_version_not_supported" => ConnectorErrorType::BusinessError,
"processing_error" => ConnectorErrorType::TechnicalError,
"service_unavailable" => ConnectorErrorType::TechnicalError,
"token_type_invalid" => ConnectorErrorType::UserError,
"token_data_invalid" => ConnectorErrorType::UserError,
_ => ConnectorErrorType::UnknownError,
}
}
}
static CHECKOUT_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
enums::CaptureMethod::ManualMultiple,
];
let supported_card_network = vec![
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::UnionPay,
];
let mut checkout_supported_payment_methods = SupportedPaymentMethods::new();
checkout_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
checkout_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
checkout_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
checkout_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
checkout_supported_payment_methods
});
static CHECKOUT_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Checkout",
description:
"Checkout.com is a British multinational financial technology company that processes payments for other companies.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static CHECKOUT_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [
enums::EventClass::Payments,
enums::EventClass::Refunds,
enums::EventClass::Disputes,
];
impl ConnectorSpecifications for Checkout {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&CHECKOUT_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*CHECKOUT_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&CHECKOUT_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__checkout__transformers.rs
|
use common_enums::{
enums::{self, AttemptStatus, PaymentChannel},
CountryAlpha2,
};
use common_utils::{
errors::{CustomResult, ParsingError},
ext_traits::ByteSliceExt,
request::{Method, RequestContent},
types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
payment_methods::storage_enums::MitCategory,
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ErrorResponse, PaymentMethodToken, RouterData,
},
router_flow_types::{Execute, RSync, SetupMandate},
router_request_types::{ResponseId, SetupMandateRequestData},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundsRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{consts, errors, webhooks};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::json;
use serde_with::skip_serializing_none;
use time::PrimitiveDateTime;
use url::Url;
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
ResponseRouterData, SubmitEvidenceRouterData, UploadFileRouterData,
},
unimplemented_payment_method,
utils::{
self, AdditionalCardInfo, PaymentsAuthorizeRequestData, PaymentsCaptureRequestData,
PaymentsSyncRequestData, RouterData as OtherRouterData, WalletData as OtherWalletData,
},
};
#[derive(Debug, Serialize)]
pub struct CheckoutRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for CheckoutRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
#[serde(tag = "type", content = "token_data")]
pub enum TokenRequest {
Googlepay(CheckoutGooglePayData),
Applepay(CheckoutApplePayData),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
#[serde(tag = "type", content = "token_data")]
pub enum PreDecryptedTokenRequest {
Applepay(Box<CheckoutApplePayData>),
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckoutGooglePayData {
protocol_version: Secret<String>,
signature: Secret<String>,
signed_message: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckoutApplePayData {
version: Secret<String>,
data: Secret<String>,
signature: Secret<String>,
header: CheckoutApplePayHeader,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckoutApplePayHeader {
ephemeral_public_key: Secret<String>,
public_key_hash: Secret<String>,
transaction_id: Secret<String>,
}
impl TryFrom<&TokenizationRouterData> for TokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Wallet(wallet_data) => match wallet_data.clone() {
WalletData::GooglePay(_data) => {
let json_wallet_data: CheckoutGooglePayData =
wallet_data.get_wallet_token_as_json("Google Pay".to_string())?;
Ok(Self::Googlepay(json_wallet_data))
}
WalletData::ApplePay(_data) => {
let json_wallet_data: CheckoutApplePayData =
wallet_data.get_wallet_token_as_json("Apple Pay".to_string())?;
Ok(Self::Applepay(json_wallet_data))
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::WeChatPayQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)
.into()),
},
PaymentMethodData::Card(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)
.into())
}
}
}
}
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct CheckoutTokenResponse {
token: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, CheckoutTokenResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CheckoutTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.token.expose(),
}),
..item.data
})
}
}
#[skip_serializing_none]
#[derive(Debug, Serialize)]
pub struct CheckoutAddress {
pub address_line1: Option<Secret<String>>,
pub address_line2: Option<Secret<String>>,
pub city: Option<String>,
pub state: Option<Secret<String>>,
pub zip: Option<Secret<String>>,
pub country: Option<CountryAlpha2>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize)]
pub struct CheckoutAccountHolderDetails {
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct CardSource {
#[serde(rename = "type")]
pub source_type: CheckoutSourceTypes,
pub number: cards::CardNumber,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
pub cvv: Option<Secret<String>>,
pub billing_address: Option<CheckoutAddress>,
pub account_holder: Option<CheckoutAccountHolderDetails>,
}
#[derive(Debug, Serialize)]
pub struct WalletSource {
#[serde(rename = "type")]
pub source_type: CheckoutSourceTypes,
pub token: Secret<String>,
pub billing_address: Option<CheckoutAddress>,
}
#[derive(Debug, Serialize)]
pub struct MandateSource {
#[serde(rename = "type")]
pub source_type: CheckoutSourceTypes,
#[serde(rename = "id")]
pub source_id: Option<String>,
pub billing_address: Option<CheckoutAddress>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymentSource {
Card(CardSource),
Wallets(WalletSource),
ApplePayPredecrypt(Box<ApplePayPredecrypt>),
MandatePayment(MandateSource),
GooglePayPredecrypt(Box<GooglePayPredecrypt>),
DecryptedWalletToken(DecryptedWalletToken),
}
#[derive(Debug, Serialize)]
pub struct DecryptedWalletToken {
#[serde(rename = "type")]
decrypt_type: String,
token: cards::CardNumber,
token_type: String,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
pub billing_address: Option<CheckoutAddress>,
}
#[derive(Debug, Serialize)]
pub struct GooglePayPredecrypt {
#[serde(rename = "type")]
_type: String,
token: cards::CardNumber,
token_type: String,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
eci: String,
cryptogram: Option<Secret<String>>,
pub billing_address: Option<CheckoutAddress>,
}
#[derive(Debug, Serialize)]
pub struct ApplePayPredecrypt {
token: cards::CardNumber,
#[serde(rename = "type")]
decrypt_type: String,
token_type: String,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
eci: Option<String>,
cryptogram: Secret<String>,
pub billing_address: Option<CheckoutAddress>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CheckoutSourceTypes {
Card,
Token,
NetworkToken,
#[serde(rename = "id")]
SourceId,
}
#[derive(Debug, Serialize)]
pub enum CheckoutPaymentType {
Regular,
Unscheduled,
#[serde(rename = "MOTO")]
Moto,
Installment,
Recurring,
}
pub struct CheckoutAuthType {
pub(super) api_key: Secret<String>,
pub(super) processing_channel_id: Secret<String>,
pub(super) api_secret: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct ReturnUrl {
pub success_url: Option<String>,
pub failure_url: Option<String>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutCustomer {
pub name: Option<Secret<String>>,
pub email: Option<common_utils::pii::Email>,
pub phone: Option<CheckoutPhoneDetails>,
pub tax_number: Option<Secret<String>>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutPhoneDetails {
pub country_code: Option<String>,
pub number: Option<Secret<String>>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutProcessing {
pub order_id: Option<String>,
pub tax_amount: Option<MinorUnit>,
pub discount_amount: Option<MinorUnit>,
pub duty_amount: Option<MinorUnit>,
pub shipping_amount: Option<MinorUnit>,
pub shipping_tax_amount: Option<MinorUnit>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutShipping {
pub address: Option<CheckoutAddress>,
pub from_address_zip: Option<String>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutLineItem {
pub commodity_code: Option<String>,
pub discount_amount: Option<MinorUnit>,
pub name: Option<String>,
pub quantity: Option<u16>,
pub reference: Option<String>,
pub tax_exempt: Option<bool>,
pub tax_amount: Option<MinorUnit>,
pub total_amount: Option<MinorUnit>,
pub unit_of_measure: Option<String>,
pub unit_price: Option<MinorUnit>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutBillingDescriptor {
pub name: Option<Secret<String>>,
pub city: Option<Secret<String>>,
pub reference: Option<String>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize)]
pub struct PaymentsRequest {
pub source: PaymentSource,
pub amount: MinorUnit,
pub currency: String,
pub processing_channel_id: Secret<String>,
#[serde(rename = "3ds")]
pub three_ds: CheckoutThreeDS,
#[serde(flatten)]
pub return_url: ReturnUrl,
pub capture: bool,
pub reference: String,
#[serde(skip_serializing_if = "is_metadata_empty")]
pub metadata: Option<Secret<serde_json::Value>>,
pub payment_type: CheckoutPaymentType,
pub merchant_initiated: Option<bool>,
pub previous_payment_id: Option<String>,
pub store_for_future_use: Option<bool>,
pub billing_descriptor: Option<CheckoutBillingDescriptor>,
// Level 2/3 data fields
pub customer: Option<CheckoutCustomer>,
pub processing: Option<CheckoutProcessing>,
pub shipping: Option<CheckoutShipping>,
pub items: Option<Vec<CheckoutLineItem>>,
pub partial_authorization: Option<CheckoutPartialAuthorization>,
pub payment_ip: Option<Secret<String, common_utils::pii::IpAddress>>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutPartialAuthorization {
pub enabled: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckoutMeta {
pub psync_flow: CheckoutPaymentIntent,
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum CheckoutPaymentIntent {
Capture,
Authorize,
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum CheckoutChallengeIndicator {
NoPreference,
ChallengeRequestedMandate,
ChallengeRequested,
NoChallengeRequested,
}
#[derive(Debug, Serialize)]
pub struct CheckoutThreeDS {
enabled: bool,
force_3ds: bool,
eci: Option<String>,
cryptogram: Option<Secret<String>>,
xid: Option<String>,
version: Option<String>,
challenge_indicator: CheckoutChallengeIndicator,
}
impl TryFrom<&ConnectorAuthType> for CheckoutAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
api_secret,
key1,
} = auth_type
{
Ok(Self {
api_key: api_key.to_owned(),
api_secret: api_secret.to_owned(),
processing_channel_id: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
fn split_account_holder_name(
card_holder_name: Option<Secret<String>>,
) -> (Option<Secret<String>>, Option<Secret<String>>) {
let account_holder_name = card_holder_name
.as_ref()
.map(|name| name.clone().expose().trim().to_string());
match account_holder_name {
Some(name) if !name.is_empty() => match name.rsplit_once(' ') {
Some((first, last)) => (
Some(Secret::new(first.to_string())),
Some(Secret::new(last.to_string())),
),
None => (Some(Secret::new(name)), None),
},
_ => (None, None),
}
}
fn build_metadata(
item: &CheckoutRouterData<&PaymentsAuthorizeRouterData>,
) -> Option<Secret<serde_json::Value>> {
// get metadata or create empty json object
let mut metadata_json = item
.router_data
.request
.metadata
.clone()
.unwrap_or_else(|| json!({}));
// get udf5 value (name or integrator)
let udf5 = item
.router_data
.request
.partner_merchant_identifier_details
.as_ref()
.and_then(|p| p.partner_details.as_ref())
.and_then(|e| e.name.clone().or(e.integrator.clone()));
// insert udf5 if present
if let Some(v) = udf5 {
if let Some(obj) = metadata_json.as_object_mut() {
obj.insert("udf5".to_string(), json!(v));
} else {
metadata_json = json!({ "udf5": v });
}
}
Some(Secret::new(metadata_json))
}
fn is_metadata_empty(val: &Option<Secret<serde_json::Value>>) -> bool {
match val {
None => true,
Some(secret) => {
let inner = secret.clone().expose();
match inner {
serde_json::Value::Null => true,
serde_json::Value::Object(map) => map.is_empty(),
_ => false,
}
}
}
}
impl TryFrom<&CheckoutRouterData<&PaymentsAuthorizeRouterData>> for PaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CheckoutRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let capture = matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
);
let payment_type = if matches!(
item.router_data.request.payment_channel,
Some(PaymentChannel::MailOrder | PaymentChannel::TelephoneOrder)
) {
CheckoutPaymentType::Moto
} else if item.router_data.request.is_mandate_payment() {
CheckoutPaymentType::Unscheduled
} else {
CheckoutPaymentType::Regular
};
let (challenge_indicator, store_for_future_use) =
if item.router_data.request.is_mandate_payment() {
(
CheckoutChallengeIndicator::ChallengeRequestedMandate,
Some(true),
)
} else {
(CheckoutChallengeIndicator::ChallengeRequested, None)
};
let billing_details = Some(CheckoutAddress {
city: item.router_data.get_optional_billing_city(),
address_line1: item.router_data.get_optional_billing_line1(),
address_line2: item.router_data.get_optional_billing_line2(),
state: item.router_data.get_optional_billing_state(),
zip: item.router_data.get_optional_billing_zip(),
country: item.router_data.get_optional_billing_country(),
});
let (
source_var,
previous_payment_id,
merchant_initiated,
payment_type,
store_for_future_use,
) = match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => {
let (first_name, last_name) = split_account_holder_name(ccard.card_holder_name);
let payment_source = PaymentSource::Card(CardSource {
source_type: CheckoutSourceTypes::Card,
number: ccard.card_number.clone(),
expiry_month: ccard.card_exp_month.clone(),
expiry_year: ccard.card_exp_year.clone(),
cvv: Some(ccard.card_cvc),
billing_address: billing_details,
account_holder: Some(CheckoutAccountHolderDetails {
first_name,
last_name,
}),
});
Ok((
payment_source,
None,
Some(false),
payment_type,
store_for_future_use,
))
}
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::GooglePay(_) => {
let p_source = match item.router_data.get_payment_method_token()? {
PaymentMethodToken::Token(token) => PaymentSource::Wallets(WalletSource {
source_type: CheckoutSourceTypes::Token,
token,
billing_address: billing_details,
}),
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Checkout"),
)?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Checkout"))?
}
PaymentMethodToken::GooglePayDecrypt(google_pay_decrypted_data) => {
let token = google_pay_decrypted_data
.application_primary_account_number
.clone();
let expiry_month = google_pay_decrypted_data
.get_expiry_month()
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_month",
})?;
let expiry_year = google_pay_decrypted_data
.get_four_digit_expiry_year()
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_year",
})?;
let cryptogram = google_pay_decrypted_data.cryptogram.clone();
PaymentSource::GooglePayPredecrypt(Box::new(GooglePayPredecrypt {
_type: "network_token".to_string(),
token,
token_type: "googlepay".to_string(),
expiry_month,
expiry_year,
eci: "06".to_string(),
cryptogram,
billing_address: billing_details,
}))
}
};
Ok((
p_source,
None,
Some(false),
payment_type,
store_for_future_use,
))
}
WalletData::ApplePay(_) => {
let payment_method_token = item.router_data.get_payment_method_token()?;
match payment_method_token {
PaymentMethodToken::Token(apple_pay_payment_token) => {
let p_source = PaymentSource::Wallets(WalletSource {
source_type: CheckoutSourceTypes::Token,
token: apple_pay_payment_token,
billing_address: billing_details,
});
Ok((
p_source,
None,
Some(false),
payment_type,
store_for_future_use,
))
}
PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
let exp_month = decrypt_data.get_expiry_month().change_context(
errors::ConnectorError::InvalidDataFormat {
field_name: "expiration_month",
},
)?;
let expiry_year_4_digit = decrypt_data.get_four_digit_expiry_year();
let p_source =
PaymentSource::ApplePayPredecrypt(Box::new(ApplePayPredecrypt {
token: decrypt_data.application_primary_account_number,
decrypt_type: "network_token".to_string(),
token_type: "applepay".to_string(),
expiry_month: exp_month,
expiry_year: expiry_year_4_digit,
eci: decrypt_data.payment_data.eci_indicator,
cryptogram: decrypt_data.payment_data.online_payment_cryptogram,
billing_address: billing_details,
}));
Ok((
p_source,
None,
Some(false),
payment_type,
store_for_future_use,
))
}
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Checkout"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Checkout"))?
}
}
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)),
},
PaymentMethodData::MandatePayment => {
let mandate_source = PaymentSource::MandatePayment(MandateSource {
source_type: CheckoutSourceTypes::SourceId,
source_id: item.router_data.request.connector_mandate_id(),
billing_address: billing_details,
});
let previous_id = Some(
item.router_data
.request
.get_connector_mandate_request_reference_id()?,
);
let p_type = match item.router_data.request.mit_category {
Some(MitCategory::Installment) => CheckoutPaymentType::Installment,
Some(MitCategory::Recurring) => CheckoutPaymentType::Recurring,
Some(MitCategory::Unscheduled) | None => CheckoutPaymentType::Unscheduled,
_ => CheckoutPaymentType::Unscheduled,
};
Ok((mandate_source, previous_id, Some(true), p_type, None))
}
PaymentMethodData::CardDetailsForNetworkTransactionId(ccard) => {
let (first_name, last_name) = split_account_holder_name(ccard.card_holder_name);
let payment_source = PaymentSource::Card(CardSource {
source_type: CheckoutSourceTypes::Card,
number: ccard.card_number.clone(),
expiry_month: ccard.card_exp_month.clone(),
expiry_year: ccard.card_exp_year.clone(),
cvv: None,
billing_address: billing_details,
account_holder: Some(CheckoutAccountHolderDetails {
first_name,
last_name,
}),
});
let previous_id = Some(
item.router_data
.request
.get_optional_network_transaction_id()
.ok_or_else(utils::missing_field_err("network_transaction_id"))
.attach_printable("Checkout unable to find NTID for MIT")?,
);
let p_type = match item.router_data.request.mit_category {
Some(MitCategory::Installment) => CheckoutPaymentType::Installment,
Some(MitCategory::Recurring) => CheckoutPaymentType::Recurring,
Some(MitCategory::Unscheduled) | None => CheckoutPaymentType::Unscheduled,
_ => CheckoutPaymentType::Unscheduled,
};
Ok((payment_source, previous_id, Some(true), p_type, None))
}
PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(
network_token_data,
) => {
let previous_id = Some(
item.router_data
.request
.get_optional_network_transaction_id()
.ok_or_else(utils::missing_field_err("network_transaction_id"))
.attach_printable("Checkout unable to find NTID for MIT")?,
);
let p_type = match item.router_data.request.mit_category {
Some(MitCategory::Installment) => CheckoutPaymentType::Installment,
Some(MitCategory::Recurring) => CheckoutPaymentType::Recurring,
Some(MitCategory::Unscheduled) | None => CheckoutPaymentType::Unscheduled,
_ => CheckoutPaymentType::Unscheduled,
};
let token_type = match network_token_data.token_source {
Some(common_types::payments::TokenSource::ApplePay) => "applepay".to_string(),
Some(common_types::payments::TokenSource::GooglePay) => "googlepay".to_string(),
None => Err(errors::ConnectorError::MissingRequiredField {
field_name: "token_source",
})?,
};
let exp_month = network_token_data.token_exp_month.clone();
let expiry_year_4_digit = network_token_data.get_card_expiry_year_4_digit()?;
let payment_source = PaymentSource::DecryptedWalletToken(DecryptedWalletToken {
token: cards::CardNumber::from(network_token_data.decrypted_token.clone()),
decrypt_type: "network_token".to_string(),
token_type,
expiry_month: exp_month,
expiry_year: expiry_year_4_digit,
billing_address: billing_details,
});
Ok((
payment_source,
previous_id,
Some(true),
p_type,
store_for_future_use,
))
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)),
}?;
let authentication_data = item.router_data.request.authentication_data.as_ref();
let three_ds = match item.router_data.auth_type {
enums::AuthenticationType::ThreeDs => CheckoutThreeDS {
enabled: true,
force_3ds: true,
eci: authentication_data.and_then(|auth| auth.eci.clone()),
cryptogram: authentication_data.map(|auth| auth.cavv.clone()),
xid: authentication_data
.and_then(|auth| auth.threeds_server_transaction_id.clone()),
version: authentication_data.and_then(|auth| {
auth.message_version
.clone()
.map(|version| version.to_string())
}),
challenge_indicator,
},
enums::AuthenticationType::NoThreeDs => CheckoutThreeDS {
enabled: false,
force_3ds: false,
eci: None,
cryptogram: None,
xid: None,
version: None,
challenge_indicator: CheckoutChallengeIndicator::NoPreference,
},
};
let return_url = ReturnUrl {
success_url: item
.router_data
.request
.router_return_url
.as_ref()
.map(|return_url| format!("{return_url}?status=success")),
failure_url: item
.router_data
.request
.router_return_url
.as_ref()
.map(|return_url| format!("{return_url}?status=failure")),
};
let connector_auth = &item.router_data.connector_auth_type;
let auth_type: CheckoutAuthType = connector_auth.try_into()?;
let processing_channel_id = auth_type.processing_channel_id;
let metadata = build_metadata(item);
let (customer, processing, shipping, items) = if let Some(l2l3_data) =
&item.router_data.l2_l3_data
{
(
l2l3_data.customer_info.as_ref().map(|_| CheckoutCustomer {
name: l2l3_data.get_customer_name(),
email: l2l3_data.get_customer_email(),
phone: Some(CheckoutPhoneDetails {
country_code: l2l3_data.get_customer_phone_country_code(),
number: l2l3_data.get_customer_phone_number(),
}),
tax_number: l2l3_data.get_customer_tax_registration_id(),
}),
l2l3_data.order_info.as_ref().map(|_| CheckoutProcessing {
order_id: l2l3_data.get_merchant_order_reference_id(),
tax_amount: l2l3_data.get_order_tax_amount(),
discount_amount: l2l3_data.get_discount_amount(),
duty_amount: l2l3_data.get_duty_amount(),
shipping_amount: l2l3_data.get_shipping_cost(),
shipping_tax_amount: l2l3_data.get_shipping_amount_tax(),
}),
Some(CheckoutShipping {
address: Some(CheckoutAddress {
country: l2l3_data.get_shipping_country(),
address_line1: l2l3_data.get_shipping_address_line1(),
address_line2: l2l3_data.get_shipping_address_line2(),
city: l2l3_data.get_shipping_city(),
state: l2l3_data.get_shipping_state(),
zip: l2l3_data.get_shipping_zip(),
}),
from_address_zip: l2l3_data.get_shipping_origin_zip().map(|zip| zip.expose()),
}),
l2l3_data.get_order_details().map(|details| {
details
.iter()
.map(|item| CheckoutLineItem {
commodity_code: item.commodity_code.clone(),
discount_amount: item.unit_discount_amount,
name: Some(item.product_name.clone()),
quantity: Some(item.quantity),
reference: item.product_id.clone(),
tax_exempt: None,
tax_amount: item.total_tax_amount,
total_amount: item.total_amount,
unit_of_measure: item.unit_of_measure.clone(),
unit_price: Some(item.amount),
})
.collect()
}),
)
} else {
(None, None, None, None)
};
let partial_authorization = item.router_data.request.enable_partial_authorization.map(
|enable_partial_authorization| CheckoutPartialAuthorization {
enabled: *enable_partial_authorization,
},
);
let payment_ip = item.router_data.request.get_ip_address_as_optional();
let billing_descriptor = item
.router_data
.request
.billing_descriptor
.as_ref()
.and_then(|descriptor| {
(descriptor.name.is_some()
|| descriptor.city.is_some()
|| descriptor.reference.is_some())
.then(|| CheckoutBillingDescriptor {
name: descriptor.name.clone(),
city: descriptor.city.clone(),
reference: descriptor.reference.clone(),
})
});
let request = Self {
source: source_var,
amount: item.amount.to_owned(),
currency: item.router_data.request.currency.to_string(),
processing_channel_id,
three_ds,
return_url,
capture,
reference: item.router_data.connector_request_reference_id.clone(),
metadata,
payment_type,
merchant_initiated,
previous_payment_id,
store_for_future_use,
customer,
processing,
shipping,
items,
partial_authorization,
payment_ip,
billing_descriptor,
};
Ok(request)
}
}
#[derive(Default, Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub enum CheckoutPaymentStatus {
Authorized,
#[default]
Pending,
#[serde(rename = "Card Verified")]
CardVerified,
Declined,
Captured,
#[serde(rename = "Retry Scheduled")]
RetryScheduled,
Voided,
#[serde(rename = "Partially Captured")]
PartiallyCaptured,
#[serde(rename = "Partially Refunded")]
PartiallyRefunded,
Refunded,
Canceled,
Expired,
}
impl TryFrom<CheckoutWebhookEventType> for CheckoutPaymentStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: CheckoutWebhookEventType) -> Result<Self, Self::Error> {
match value {
CheckoutWebhookEventType::PaymentApproved => Ok(Self::Authorized),
CheckoutWebhookEventType::PaymentCaptured => Ok(Self::Captured),
CheckoutWebhookEventType::PaymentDeclined => Ok(Self::Declined),
CheckoutWebhookEventType::AuthenticationStarted
| CheckoutWebhookEventType::AuthenticationApproved
| CheckoutWebhookEventType::AuthenticationAttempted => Ok(Self::Pending),
CheckoutWebhookEventType::AuthenticationExpired
| CheckoutWebhookEventType::AuthenticationFailed
| CheckoutWebhookEventType::PaymentAuthenticationFailed
| CheckoutWebhookEventType::PaymentCaptureDeclined => Ok(Self::Declined),
CheckoutWebhookEventType::PaymentCanceled => Ok(Self::Canceled),
CheckoutWebhookEventType::PaymentVoided => Ok(Self::Voided),
CheckoutWebhookEventType::PaymentRefunded
| CheckoutWebhookEventType::PaymentRefundDeclined
| CheckoutWebhookEventType::DisputeReceived
| CheckoutWebhookEventType::DisputeExpired
| CheckoutWebhookEventType::DisputeAccepted
| CheckoutWebhookEventType::DisputeCanceled
| CheckoutWebhookEventType::DisputeEvidenceSubmitted
| CheckoutWebhookEventType::DisputeEvidenceAcknowledgedByScheme
| CheckoutWebhookEventType::DisputeEvidenceRequired
| CheckoutWebhookEventType::DisputeArbitrationLost
| CheckoutWebhookEventType::DisputeArbitrationWon
| CheckoutWebhookEventType::DisputeWon
| CheckoutWebhookEventType::DisputeLost
| CheckoutWebhookEventType::Unknown => {
Err(errors::ConnectorError::WebhookEventTypeNotFound.into())
}
}
}
}
fn get_attempt_status_cap(
item: (CheckoutPaymentStatus, Option<enums::CaptureMethod>),
) -> AttemptStatus {
let (status, capture_method) = item;
match status {
CheckoutPaymentStatus::Authorized => {
if capture_method == Some(enums::CaptureMethod::Automatic) || capture_method.is_none() {
AttemptStatus::Charged
} else {
AttemptStatus::Authorized
}
}
CheckoutPaymentStatus::Captured
| CheckoutPaymentStatus::PartiallyRefunded
| CheckoutPaymentStatus::Refunded
| CheckoutPaymentStatus::CardVerified => AttemptStatus::Charged,
CheckoutPaymentStatus::PartiallyCaptured => AttemptStatus::PartialCharged,
CheckoutPaymentStatus::Declined
| CheckoutPaymentStatus::Expired
| CheckoutPaymentStatus::Canceled => AttemptStatus::Failure,
CheckoutPaymentStatus::Pending => AttemptStatus::AuthenticationPending,
CheckoutPaymentStatus::RetryScheduled => AttemptStatus::Pending,
CheckoutPaymentStatus::Voided => AttemptStatus::Voided,
}
}
fn get_attempt_status_intent(
item: (CheckoutPaymentStatus, CheckoutPaymentIntent),
) -> AttemptStatus {
let (status, psync_flow) = item;
match status {
CheckoutPaymentStatus::Authorized => {
if psync_flow == CheckoutPaymentIntent::Capture {
AttemptStatus::Charged
} else {
AttemptStatus::Authorized
}
}
CheckoutPaymentStatus::Captured
| CheckoutPaymentStatus::PartiallyRefunded
| CheckoutPaymentStatus::Refunded
| CheckoutPaymentStatus::CardVerified => AttemptStatus::Charged,
CheckoutPaymentStatus::PartiallyCaptured => AttemptStatus::PartialCharged,
CheckoutPaymentStatus::Declined
| CheckoutPaymentStatus::Expired
| CheckoutPaymentStatus::Canceled => AttemptStatus::Failure,
CheckoutPaymentStatus::Pending => AttemptStatus::AuthenticationPending,
CheckoutPaymentStatus::RetryScheduled => AttemptStatus::Pending,
CheckoutPaymentStatus::Voided => AttemptStatus::Voided,
}
}
fn get_attempt_status_bal(item: (CheckoutPaymentStatus, Option<Balances>)) -> AttemptStatus {
let (status, balances) = item;
match status {
CheckoutPaymentStatus::Authorized => {
if let Some(Balances {
available_to_capture: 0,
}) = balances
{
AttemptStatus::Charged
} else {
AttemptStatus::Authorized
}
}
CheckoutPaymentStatus::Captured
| CheckoutPaymentStatus::PartiallyRefunded
| CheckoutPaymentStatus::Refunded => AttemptStatus::Charged,
CheckoutPaymentStatus::PartiallyCaptured => AttemptStatus::PartialCharged,
CheckoutPaymentStatus::Declined
| CheckoutPaymentStatus::Expired
| CheckoutPaymentStatus::Canceled => AttemptStatus::Failure,
CheckoutPaymentStatus::Pending => AttemptStatus::AuthenticationPending,
CheckoutPaymentStatus::CardVerified | CheckoutPaymentStatus::RetryScheduled => {
AttemptStatus::Pending
}
CheckoutPaymentStatus::Voided => AttemptStatus::Voided,
}
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Href {
#[serde(rename = "href")]
redirection_url: Url,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct Links {
redirect: Option<Href>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct Source {
id: Option<String>,
avs_check: Option<String>,
cvv_check: Option<String>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct PaymentsResponse {
id: String,
amount: Option<MinorUnit>,
currency: Option<String>,
scheme_id: Option<String>,
processing: Option<PaymentProcessingDetails>,
action_id: Option<String>,
status: CheckoutPaymentStatus,
#[serde(rename = "_links")]
links: Links,
balances: Option<Balances>,
reference: Option<String>,
response_code: Option<String>,
response_summary: Option<String>,
approved: Option<bool>,
processed_on: Option<String>,
source: Option<Source>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct PaymentProcessingDetails {
/// The Merchant Advice Code (MAC) provided by Mastercard, which contains additional information about the transaction.
pub partner_merchant_advice_code: Option<String>,
/// The original authorization response code sent by the scheme.
pub partner_response_code: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum PaymentsResponseEnum {
ActionResponse(Vec<ActionResponse>),
PaymentResponse(Box<PaymentsResponse>),
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct Balances {
available_to_capture: i32,
}
fn get_connector_meta(
capture_method: enums::CaptureMethod,
) -> CustomResult<serde_json::Value, errors::ConnectorError> {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::SequentialAutomatic => {
Ok(serde_json::json!(CheckoutMeta {
psync_flow: CheckoutPaymentIntent::Capture,
}))
}
enums::CaptureMethod::Manual | enums::CaptureMethod::ManualMultiple => {
Ok(serde_json::json!(CheckoutMeta {
psync_flow: CheckoutPaymentIntent::Authorize,
}))
}
enums::CaptureMethod::Scheduled => {
Err(errors::ConnectorError::CaptureMethodNotSupported.into())
}
}
}
impl TryFrom<PaymentsResponseRouterData<PaymentsResponse>> for PaymentsAuthorizeRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: PaymentsResponseRouterData<PaymentsResponse>) -> Result<Self, Self::Error> {
let status =
get_attempt_status_cap((item.response.status, item.data.request.capture_method));
if status == AttemptStatus::Failure {
let error_response = ErrorResponse {
status_code: item.http_code,
code: item
.response
.response_code
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: item
.response
.response_summary
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: item.response.response_summary,
attempt_status: None,
connector_transaction_id: Some(item.response.id.clone()),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
};
return Ok(Self {
status,
response: Err(error_response),
..item.data
});
}
let connector_meta =
get_connector_meta(item.data.request.capture_method.unwrap_or_default())?;
let redirection_data = item
.response
.links
.redirect
.map(|href| RedirectForm::from((href.redirection_url, Method::Get)));
let mandate_reference = if item.data.request.is_mandate_payment() {
item.response
.source
.as_ref()
.and_then(|src| src.id.clone())
.map(|id| MandateReference {
connector_mandate_id: Some(id),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: Some(item.response.id.clone()),
})
} else {
None
};
let additional_information =
convert_to_additional_payment_method_connector_response(item.response.source.as_ref())
.map(ConnectorResponseData::with_additional_payment_method_data);
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: Some(connector_meta),
network_txn_id: item.response.scheme_id.clone(),
connector_response_reference_id: Some(
item.response.reference.unwrap_or(item.response.id),
),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
};
let (amount_captured, minor_amount_capturable) = match item.data.request.capture_method {
Some(enums::CaptureMethod::Manual) | Some(enums::CaptureMethod::ManualMultiple) => {
(None, item.response.amount)
}
_ => (item.response.amount.map(MinorUnit::get_amount_as_i64), None),
};
let authorized_amount = item
.data
.request
.enable_partial_authorization
.filter(|flag| flag.is_true())
.and(item.response.amount);
Ok(Self {
status,
response: Ok(payments_response_data),
connector_response: additional_information,
authorized_amount,
amount_captured,
minor_amount_capturable,
..item.data
})
}
}
impl
TryFrom<
ResponseRouterData<
SetupMandate,
PaymentsResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
> for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
SetupMandate,
PaymentsResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let connector_meta =
get_connector_meta(item.data.request.capture_method.unwrap_or_default())?;
let redirection_data = item
.response
.links
.redirect
.map(|href| RedirectForm::from((href.redirection_url, Method::Get)));
let status =
get_attempt_status_cap((item.response.status, item.data.request.capture_method));
let network_advice_code = item
.response
.processing
.as_ref()
.and_then(|processing| {
processing
.partner_merchant_advice_code
.as_ref()
.or(processing.partner_response_code.as_ref())
})
.cloned();
let error_response = if status == AttemptStatus::Failure {
Some(ErrorResponse {
status_code: item.http_code,
code: item
.response
.response_code
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: item
.response
.response_summary
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: item.response.response_summary,
attempt_status: None,
connector_transaction_id: Some(item.response.id.clone()),
connector_response_reference_id: None,
network_advice_code,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
let mandate_reference = item
.response
.source
.as_ref()
.and_then(|src| src.id.clone())
.map(|id| MandateReference {
connector_mandate_id: Some(id),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: Some(item.response.id.clone()),
});
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: Some(connector_meta),
network_txn_id: item.response.scheme_id.clone(),
connector_response_reference_id: Some(
item.response.reference.unwrap_or(item.response.id),
),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
};
Ok(Self {
status,
response: error_response.map_or_else(|| Ok(payments_response_data), Err),
..item.data
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<PaymentsResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<PaymentsResponse>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.links
.redirect
.map(|href| RedirectForm::from((href.redirection_url, Method::Get)));
let checkout_meta: CheckoutMeta =
utils::to_connector_meta(item.data.request.connector_meta.clone())?;
let status = get_attempt_status_intent((item.response.status, checkout_meta.psync_flow));
let error_response = if status == AttemptStatus::Failure {
Some(ErrorResponse {
status_code: item.http_code,
code: item
.response
.response_code
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: item
.response
.response_summary
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: item.response.response_summary,
attempt_status: None,
connector_transaction_id: Some(item.response.id.clone()),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
let mandate_reference = if item.data.request.is_mandate_payment() {
item.response
.source
.as_ref()
.and_then(|src| src.id.clone())
.map(|id| MandateReference {
connector_mandate_id: Some(id),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: Some(item.response.id.clone()),
})
} else {
None
};
let additional_information =
convert_to_additional_payment_method_connector_response(item.response.source.as_ref())
.map(ConnectorResponseData::with_additional_payment_method_data);
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: item.response.scheme_id.clone(),
connector_response_reference_id: Some(
item.response.reference.unwrap_or(item.response.id),
),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
};
Ok(Self {
status,
response: error_response.map_or_else(|| Ok(payments_response_data), Err),
connector_response: additional_information,
..item.data
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<PaymentsResponseEnum>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<PaymentsResponseEnum>,
) -> Result<Self, Self::Error> {
let capture_sync_response_list = match item.response {
PaymentsResponseEnum::PaymentResponse(payments_response) => {
// for webhook consumption flow
utils::construct_captures_response_hashmap(vec![payments_response])?
}
PaymentsResponseEnum::ActionResponse(action_list) => {
// for captures sync
utils::construct_captures_response_hashmap(action_list)?
}
};
Ok(Self {
response: Ok(PaymentsResponseData::MultipleCaptureResponse {
capture_sync_response_list,
}),
..item.data
})
}
}
#[derive(Clone, Default, Debug, Eq, PartialEq, Serialize)]
pub struct PaymentVoidRequest {
reference: String,
}
#[derive(Clone, Default, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct PaymentVoidResponse {
#[serde(skip)]
pub(super) status: u16,
action_id: String,
reference: String,
scheme_id: Option<String>,
}
impl From<&PaymentVoidResponse> for AttemptStatus {
fn from(item: &PaymentVoidResponse) -> Self {
if item.status == 202 {
Self::Voided
} else {
Self::VoidFailed
}
}
}
impl TryFrom<PaymentsCancelResponseRouterData<PaymentVoidResponse>> for PaymentsCancelRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<PaymentVoidResponse>,
) -> Result<Self, Self::Error> {
let response = &item.response;
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.action_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: item.response.scheme_id.clone(),
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
status: response.into(),
..item.data
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for PaymentVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Ok(Self {
reference: item.request.connector_transaction_id.clone(),
})
}
}
#[derive(Debug, Serialize)]
pub enum CaptureType {
Final,
NonFinal,
}
#[derive(Debug, Serialize)]
pub struct PaymentCaptureRequest {
pub amount: Option<MinorUnit>,
pub capture_type: Option<CaptureType>,
pub processing_channel_id: Secret<String>,
pub reference: Option<String>,
}
impl TryFrom<&CheckoutRouterData<&PaymentsCaptureRouterData>> for PaymentCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CheckoutRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let connector_auth = &item.router_data.connector_auth_type;
let auth_type: CheckoutAuthType = connector_auth.try_into()?;
let processing_channel_id = auth_type.processing_channel_id;
let capture_type = if item.router_data.request.is_multiple_capture() {
CaptureType::NonFinal
} else {
CaptureType::Final
};
let reference = item
.router_data
.request
.multiple_capture_data
.as_ref()
.map(|multiple_capture_data| multiple_capture_data.capture_reference.clone());
Ok(Self {
amount: Some(item.amount.to_owned()),
capture_type: Some(capture_type),
processing_channel_id,
reference, // hyperswitch's reference for this capture
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaymentCaptureResponse {
pub action_id: String,
pub reference: Option<String>,
pub scheme_id: Option<String>,
}
impl TryFrom<PaymentsCaptureResponseRouterData<PaymentCaptureResponse>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<PaymentCaptureResponse>,
) -> Result<Self, Self::Error> {
let connector_meta = serde_json::json!(CheckoutMeta {
psync_flow: CheckoutPaymentIntent::Capture,
});
let (status, amount_captured) = if item.http_code == 202 {
(
AttemptStatus::Charged,
Some(item.data.request.amount_to_capture),
)
} else {
(AttemptStatus::Pending, None)
};
// if multiple capture request, return capture action_id so that it will be updated in the captures table.
// else return previous connector_transaction_id.
let resource_id = if item.data.request.is_multiple_capture() {
item.response.action_id
} else {
item.data.request.connector_transaction_id.to_owned()
};
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(resource_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: item.response.scheme_id.clone(),
connector_response_reference_id: item.response.reference,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
status,
amount_captured,
..item.data
})
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RefundRequest {
amount: Option<MinorUnit>,
reference: String,
}
impl<F> TryFrom<&CheckoutRouterData<&RefundsRouterData<F>>> for RefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &CheckoutRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let reference = item.router_data.request.refund_id.clone();
Ok(Self {
amount: Some(item.amount.to_owned()),
reference,
})
}
}
#[allow(dead_code)]
#[derive(Deserialize, Debug, Serialize)]
pub struct RefundResponse {
action_id: String,
reference: String,
}
#[derive(Deserialize)]
pub struct CheckoutRefundResponse {
pub(super) status: u16,
pub(super) response: RefundResponse,
}
impl From<&CheckoutRefundResponse> for enums::RefundStatus {
fn from(item: &CheckoutRefundResponse) -> Self {
if item.status == 202 {
Self::Success
} else {
Self::Failure
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, CheckoutRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, CheckoutRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(&item.response);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.response.action_id.clone(),
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, CheckoutRefundResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, CheckoutRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(&item.response);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.response.action_id.clone(),
refund_status,
}),
..item.data
})
}
}
#[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct CheckoutErrorResponse {
pub request_id: Option<String>,
pub error_type: Option<String>,
pub error_codes: Option<Vec<String>>,
}
#[derive(Deserialize, Debug, PartialEq, Serialize)]
pub enum ActionType {
Authorization,
Void,
Capture,
Refund,
Payout,
Return,
#[serde(rename = "Card Verification")]
CardVerification,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct ActionResponse {
#[serde(rename = "id")]
pub action_id: String,
pub amount: MinorUnit,
#[serde(rename = "type")]
pub action_type: ActionType,
pub approved: Option<bool>,
pub reference: Option<String>,
}
impl From<&ActionResponse> for enums::RefundStatus {
fn from(item: &ActionResponse) -> Self {
match item.approved {
Some(true) => Self::Success,
Some(false) => Self::Failure,
None => Self::Pending,
}
}
}
impl utils::MultipleCaptureSyncResponse for ActionResponse {
fn get_connector_capture_id(&self) -> String {
self.action_id.clone()
}
fn get_capture_attempt_status(&self) -> AttemptStatus {
match self.approved {
Some(true) => AttemptStatus::Charged,
Some(false) => AttemptStatus::Failure,
None => AttemptStatus::Pending,
}
}
fn get_connector_reference_id(&self) -> Option<String> {
self.reference.clone()
}
fn is_capture_response(&self) -> bool {
self.action_type == ActionType::Capture
}
fn get_amount_captured(&self) -> Result<Option<MinorUnit>, error_stack::Report<ParsingError>> {
Ok(Some(self.amount))
}
}
impl utils::MultipleCaptureSyncResponse for Box<PaymentsResponse> {
fn get_connector_capture_id(&self) -> String {
self.action_id.clone().unwrap_or("".into())
}
fn get_capture_attempt_status(&self) -> AttemptStatus {
get_attempt_status_bal((self.status.clone(), self.balances.clone()))
}
fn get_connector_reference_id(&self) -> Option<String> {
self.reference.clone()
}
fn is_capture_response(&self) -> bool {
self.status == CheckoutPaymentStatus::Captured
}
fn get_amount_captured(&self) -> Result<Option<MinorUnit>, error_stack::Report<ParsingError>> {
Ok(self.amount)
}
}
#[derive(Debug, Clone, serde::Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CheckoutRedirectResponseStatus {
Success,
Failure,
}
#[derive(Debug, Clone, serde::Deserialize, Eq, PartialEq)]
pub struct CheckoutRedirectResponse {
pub status: Option<CheckoutRedirectResponseStatus>,
#[serde(rename = "cko-session-id")]
pub cko_session_id: Option<String>,
}
impl TryFrom<RefundsResponseRouterData<Execute, &ActionResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, &ActionResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.action_id.clone(),
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, &ActionResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, &ActionResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.action_id.clone(),
refund_status,
}),
..item.data
})
}
}
impl From<CheckoutRedirectResponseStatus> for AttemptStatus {
fn from(item: CheckoutRedirectResponseStatus) -> Self {
match item {
CheckoutRedirectResponseStatus::Success => Self::AuthenticationSuccessful,
CheckoutRedirectResponseStatus::Failure => Self::Failure,
}
}
}
pub fn is_refund_event(event_code: &CheckoutWebhookEventType) -> bool {
matches!(
event_code,
CheckoutWebhookEventType::PaymentRefunded | CheckoutWebhookEventType::PaymentRefundDeclined
)
}
pub fn is_chargeback_event(event_code: &CheckoutWebhookEventType) -> bool {
matches!(
event_code,
CheckoutWebhookEventType::DisputeReceived
| CheckoutWebhookEventType::DisputeExpired
| CheckoutWebhookEventType::DisputeAccepted
| CheckoutWebhookEventType::DisputeCanceled
| CheckoutWebhookEventType::DisputeEvidenceSubmitted
| CheckoutWebhookEventType::DisputeEvidenceAcknowledgedByScheme
| CheckoutWebhookEventType::DisputeEvidenceRequired
| CheckoutWebhookEventType::DisputeArbitrationLost
| CheckoutWebhookEventType::DisputeArbitrationWon
| CheckoutWebhookEventType::DisputeWon
| CheckoutWebhookEventType::DisputeLost
)
}
#[derive(Debug, Deserialize, strum::Display, Clone)]
#[serde(rename_all = "snake_case")]
pub enum CheckoutWebhookEventType {
AuthenticationStarted,
AuthenticationApproved,
AuthenticationAttempted,
AuthenticationExpired,
AuthenticationFailed,
PaymentApproved,
PaymentCaptured,
PaymentDeclined,
PaymentRefunded,
PaymentRefundDeclined,
PaymentAuthenticationFailed,
PaymentCanceled,
PaymentCaptureDeclined,
PaymentVoided,
DisputeReceived,
DisputeExpired,
DisputeAccepted,
DisputeCanceled,
DisputeEvidenceSubmitted,
DisputeEvidenceAcknowledgedByScheme,
DisputeEvidenceRequired,
DisputeArbitrationLost,
DisputeArbitrationWon,
DisputeWon,
DisputeLost,
#[serde(other)]
Unknown,
}
#[derive(Debug, Deserialize)]
pub struct CheckoutWebhookEventTypeBody {
#[serde(rename = "type")]
pub transaction_type: CheckoutWebhookEventType,
}
#[derive(Debug, Deserialize)]
pub struct CheckoutWebhookData {
pub id: String,
pub payment_id: Option<String>,
pub action_id: Option<String>,
pub reference: Option<String>,
pub amount: MinorUnit,
pub balances: Option<Balances>,
pub response_code: Option<String>,
pub response_summary: Option<String>,
pub currency: String,
pub processed_on: Option<String>,
pub approved: Option<bool>,
}
#[derive(Debug, Deserialize)]
pub struct CheckoutWebhookBody {
#[serde(rename = "type")]
pub transaction_type: CheckoutWebhookEventType,
pub data: CheckoutWebhookData,
#[serde(rename = "_links")]
pub links: Links,
pub source: Option<Source>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckoutDisputeWebhookData {
pub id: String,
pub payment_id: Option<String>,
pub action_id: Option<String>,
pub amount: MinorUnit,
pub currency: enums::Currency,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub evidence_required_by: Option<PrimitiveDateTime>,
pub reason_code: Option<String>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub date: Option<PrimitiveDateTime>,
}
#[derive(Debug, Deserialize)]
pub struct CheckoutDisputeWebhookBody {
#[serde(rename = "type")]
pub transaction_type: CheckoutDisputeTransactionType,
pub data: CheckoutDisputeWebhookData,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub created_on: Option<PrimitiveDateTime>,
}
#[derive(Debug, Deserialize, strum::Display, Clone)]
#[serde(rename_all = "snake_case")]
pub enum CheckoutDisputeTransactionType {
DisputeReceived,
DisputeExpired,
DisputeAccepted,
DisputeCanceled,
DisputeEvidenceSubmitted,
DisputeEvidenceAcknowledgedByScheme,
DisputeEvidenceRequired,
DisputeArbitrationLost,
DisputeArbitrationWon,
DisputeWon,
DisputeLost,
}
impl From<CheckoutWebhookEventType> for api_models::webhooks::IncomingWebhookEvent {
fn from(transaction_type: CheckoutWebhookEventType) -> Self {
match transaction_type {
CheckoutWebhookEventType::AuthenticationStarted
| CheckoutWebhookEventType::AuthenticationApproved
| CheckoutWebhookEventType::AuthenticationAttempted => Self::EventNotSupported,
CheckoutWebhookEventType::AuthenticationExpired
| CheckoutWebhookEventType::AuthenticationFailed
| CheckoutWebhookEventType::PaymentAuthenticationFailed => {
Self::PaymentIntentAuthorizationFailure
}
CheckoutWebhookEventType::PaymentApproved => Self::EventNotSupported,
CheckoutWebhookEventType::PaymentCaptured => Self::PaymentIntentSuccess,
CheckoutWebhookEventType::PaymentDeclined => Self::PaymentIntentFailure,
CheckoutWebhookEventType::PaymentRefunded => Self::RefundSuccess,
CheckoutWebhookEventType::PaymentRefundDeclined => Self::RefundFailure,
CheckoutWebhookEventType::PaymentCanceled => Self::PaymentIntentCancelFailure,
CheckoutWebhookEventType::PaymentCaptureDeclined => Self::PaymentIntentCaptureFailure,
CheckoutWebhookEventType::PaymentVoided => Self::PaymentIntentCancelled,
CheckoutWebhookEventType::DisputeReceived
| CheckoutWebhookEventType::DisputeEvidenceRequired => Self::DisputeOpened,
CheckoutWebhookEventType::DisputeExpired => Self::DisputeExpired,
CheckoutWebhookEventType::DisputeAccepted => Self::DisputeAccepted,
CheckoutWebhookEventType::DisputeCanceled => Self::DisputeCancelled,
CheckoutWebhookEventType::DisputeEvidenceSubmitted
| CheckoutWebhookEventType::DisputeEvidenceAcknowledgedByScheme => {
Self::DisputeChallenged
}
CheckoutWebhookEventType::DisputeWon
| CheckoutWebhookEventType::DisputeArbitrationWon => Self::DisputeWon,
CheckoutWebhookEventType::DisputeLost
| CheckoutWebhookEventType::DisputeArbitrationLost => Self::DisputeLost,
CheckoutWebhookEventType::Unknown => Self::EventNotSupported,
}
}
}
impl From<CheckoutDisputeTransactionType> for api_models::enums::DisputeStage {
fn from(code: CheckoutDisputeTransactionType) -> Self {
match code {
CheckoutDisputeTransactionType::DisputeArbitrationLost
| CheckoutDisputeTransactionType::DisputeArbitrationWon => Self::PreArbitration,
CheckoutDisputeTransactionType::DisputeReceived
| CheckoutDisputeTransactionType::DisputeExpired
| CheckoutDisputeTransactionType::DisputeAccepted
| CheckoutDisputeTransactionType::DisputeCanceled
| CheckoutDisputeTransactionType::DisputeEvidenceSubmitted
| CheckoutDisputeTransactionType::DisputeEvidenceAcknowledgedByScheme
| CheckoutDisputeTransactionType::DisputeEvidenceRequired
| CheckoutDisputeTransactionType::DisputeWon
| CheckoutDisputeTransactionType::DisputeLost => Self::Dispute,
}
}
}
#[derive(Debug, Deserialize)]
pub struct CheckoutWebhookObjectResource {
pub data: serde_json::Value,
}
#[derive(Debug, Serialize)]
pub struct CheckoutFileRequest {
pub purpose: &'static str,
#[serde(skip)]
pub file: Vec<u8>,
#[serde(skip)]
pub file_key: String,
#[serde(skip)]
pub file_type: String,
}
pub fn construct_file_upload_request(
file_upload_router_data: UploadFileRouterData,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let request = file_upload_router_data.request;
let checkout_file_request = CheckoutFileRequest {
purpose: "dispute_evidence",
file: request.file.clone(),
file_key: request.file_key.clone(),
file_type: request.file_type.to_string(),
};
let mut multipart = reqwest::multipart::Form::new();
multipart = multipart.text("purpose", "dispute_evidence");
let file_data = reqwest::multipart::Part::bytes(request.file)
.file_name(format!(
"{}.{}",
request.file_key,
request
.file_type
.as_ref()
.split('/')
.next_back()
.unwrap_or_default()
))
.mime_str(request.file_type.as_ref())
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failure in constructing file data")?;
multipart = multipart.part("file", file_data);
Ok(RequestContent::FormData((
multipart,
Box::new(checkout_file_request),
)))
}
#[derive(Debug, Deserialize, Serialize)]
pub struct FileUploadResponse {
#[serde(rename = "id")]
pub file_id: String,
}
#[derive(Default, Debug, Serialize)]
pub struct Evidence {
pub proof_of_delivery_or_service_file: Option<String>,
pub invoice_or_receipt_file: Option<String>,
pub invoice_showing_distinct_transactions_file: Option<String>,
pub customer_communication_file: Option<String>,
pub refund_or_cancellation_policy_file: Option<String>,
pub recurring_transaction_agreement_file: Option<String>,
pub additional_evidence_file: Option<String>,
}
impl TryFrom<&webhooks::IncomingWebhookRequestDetails<'_>> for PaymentsResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> Result<Self, Self::Error> {
let details: CheckoutWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let data = details.data;
let psync_struct = Self {
id: data.payment_id.unwrap_or(data.id),
amount: Some(data.amount),
status: CheckoutPaymentStatus::try_from(details.transaction_type)?,
links: details.links,
balances: data.balances,
reference: data.reference,
response_code: data.response_code,
response_summary: data.response_summary,
action_id: data.action_id,
currency: Some(data.currency),
processed_on: data.processed_on,
approved: data.approved,
source: Some(Source {
id: details.source.clone().and_then(|src| src.id),
avs_check: details.source.clone().and_then(|src| src.avs_check),
cvv_check: details.source.clone().and_then(|src| src.cvv_check),
}),
scheme_id: None,
processing: None,
};
Ok(psync_struct)
}
}
impl TryFrom<&webhooks::IncomingWebhookRequestDetails<'_>> for RefundResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> Result<Self, Self::Error> {
let details: CheckoutWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let data = details.data;
let refund_struct = Self {
action_id: data
.action_id
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?,
reference: data
.reference
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?,
};
Ok(refund_struct)
}
}
impl TryFrom<&SubmitEvidenceRouterData> for Evidence {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SubmitEvidenceRouterData) -> Result<Self, Self::Error> {
let submit_evidence_request_data = item.request.clone();
Ok(Self {
proof_of_delivery_or_service_file: submit_evidence_request_data
.shipping_documentation_provider_file_id,
invoice_or_receipt_file: submit_evidence_request_data.receipt_provider_file_id,
invoice_showing_distinct_transactions_file: submit_evidence_request_data
.invoice_showing_distinct_transactions_provider_file_id,
customer_communication_file: submit_evidence_request_data
.customer_communication_provider_file_id,
refund_or_cancellation_policy_file: submit_evidence_request_data
.refund_policy_provider_file_id,
recurring_transaction_agreement_file: submit_evidence_request_data
.recurring_transaction_agreement_provider_file_id,
additional_evidence_file: submit_evidence_request_data
.uncategorized_file_provider_file_id,
})
}
}
impl From<String> for utils::ErrorCodeAndMessage {
fn from(error: String) -> Self {
Self {
error_code: error.clone(),
error_message: error,
}
}
}
fn convert_to_additional_payment_method_connector_response(
source: Option<&Source>,
) -> Option<AdditionalPaymentMethodConnectorResponse> {
source.map(|code| {
let payment_checks = serde_json::json!({
"avs_result": code.avs_check,
"card_validation_result": code.cvv_check,
});
AdditionalPaymentMethodConnectorResponse::Card {
authentication_data: None,
payment_checks: Some(payment_checks),
card_network: None,
domestic_network: None,
auth_code: None,
}
})
}
|
crates__hyperswitch_connectors__src__connectors__coinbase.rs
|
pub mod transformers;
use common_enums::enums;
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
connector_endpoints::Connectors,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
errors,
events::connector_api_logs::ConnectorEvent,
types::{PaymentsAuthorizeType, PaymentsSyncType, Response},
webhooks,
};
use lazy_static::lazy_static;
use masking::Mask;
use transformers as coinbase;
use self::coinbase::CoinbaseWebhookDetails;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, convert_amount},
};
#[derive(Clone)]
pub struct Coinbase {
amount_convertor: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Coinbase {
pub fn new() -> &'static Self {
&Self {
amount_convertor: &StringMajorUnitForConnector,
}
}
}
impl api::Payment for Coinbase {}
impl api::PaymentToken for Coinbase {}
impl api::PaymentSession for Coinbase {}
impl api::ConnectorAccessToken for Coinbase {}
impl api::MandateSetup for Coinbase {}
impl api::PaymentAuthorize for Coinbase {}
impl api::PaymentSync for Coinbase {}
impl api::PaymentCapture for Coinbase {}
impl api::PaymentVoid for Coinbase {}
impl api::Refund for Coinbase {}
impl api::RefundExecute for Coinbase {}
impl api::RefundSync for Coinbase {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Coinbase
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![
(
headers::CONTENT_TYPE.to_string(),
self.common_get_content_type().to_string().into(),
),
(
headers::X_CC_VERSION.to_string(),
"2018-03-22".to_string().into(),
),
];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Coinbase {
fn id(&self) -> &'static str {
"coinbase"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.coinbase.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth: coinbase::CoinbaseAuthType = coinbase::CoinbaseAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::X_CC_API_KEY.to_string(),
auth.api_key.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: coinbase::CoinbaseErrorResponse = res
.response
.parse_struct("CoinbaseErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.error_type,
message: response.error.message,
reason: response.error.code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Coinbase {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Coinbase
{
// Not Implemented (R)
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Coinbase {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Coinbase {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Coinbase
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Coinbase".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Coinbase {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/charges", self.base_url(_connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = coinbase::CoinbaseRouterData::from((amount, req));
let connector_req = coinbase::CoinbasePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: coinbase::CoinbasePaymentsResponse = res
.response
.parse_struct("Coinbase PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Coinbase {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_id = _req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/charges/{}",
self.base_url(_connectors),
connector_id
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: coinbase::CoinbasePaymentsResponse = res
.response
.parse_struct("coinbase PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Coinbase {
fn build_request(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Coinbase".to_string(),
}
.into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Coinbase {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Coinbase {
fn build_request(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refund".to_string(),
connector: "Coinbase".to_string(),
}
.into())
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Coinbase {
// default implementation of build_request method will be executed
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Coinbase {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let base64_signature =
utils::get_header_key_value("X-CC-Webhook-Signature", request.headers)?;
hex::decode(base64_signature)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let message = std::str::from_utf8(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
Ok(message.to_string().into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
.parse_struct("CoinbaseWebhookDetails")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(notif.event.data.id),
))
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
.parse_struct("CoinbaseWebhookDetails")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
match notif.event.event_type {
coinbase::WebhookEventType::Confirmed | coinbase::WebhookEventType::Resolved => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
coinbase::WebhookEventType::Failed => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired)
}
coinbase::WebhookEventType::Pending => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)
}
coinbase::WebhookEventType::Unknown | coinbase::WebhookEventType::Created => {
Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
}
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
.parse_struct("CoinbaseWebhookDetails")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Box::new(notif.event))
}
}
lazy_static! {
static ref COINBASE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Coinbase",
description:
"Coinbase is a place for people and businesses to buy, sell, and manage crypto.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Beta,
};
static ref COINBASE_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let mut coinbase_supported_payment_methods = SupportedPaymentMethods::new();
coinbase_supported_payment_methods.add(
enums::PaymentMethod::Crypto,
enums::PaymentMethodType::CryptoCurrency,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::NotSupported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
coinbase_supported_payment_methods
};
static ref COINBASE_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> =
vec![enums::EventClass::Payments, enums::EventClass::Refunds,];
}
impl ConnectorSpecifications for Coinbase {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*COINBASE_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*COINBASE_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*COINBASE_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__coingate.rs
|
pub mod transformers;
use std::sync::LazyLock;
use common_enums::{enums, CaptureMethod, PaymentMethod, PaymentMethodType};
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt, ValueExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask, PeekInterface};
use transformers::{self as coingate, CoingateWebhookBody};
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, RefundsRequestData},
};
#[derive(Clone)]
pub struct Coingate {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Coingate {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl api::Payment for Coingate {}
impl api::PaymentSession for Coingate {}
impl api::ConnectorAccessToken for Coingate {}
impl api::MandateSetup for Coingate {}
impl api::PaymentAuthorize for Coingate {}
impl api::PaymentSync for Coingate {}
impl api::PaymentCapture for Coingate {}
impl api::PaymentVoid for Coingate {}
impl api::Refund for Coingate {}
impl api::RefundExecute for Coingate {}
impl api::RefundSync for Coingate {}
impl api::PaymentToken for Coingate {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Coingate
{
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Coingate
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Coingate {
fn id(&self) -> &'static str {
"coingate"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.coingate.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = coingate::CoingateAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", auth.api_key.peek()).into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: coingate::CoingateErrorResponse = res
.response
.parse_struct("CoingateErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let reason = match &response.errors {
Some(errors) => errors.join(" & "),
None => response.reason.clone(),
};
Ok(ErrorResponse {
status_code: res.status_code,
code: response.message.to_string(),
message: response.message.clone(),
reason: Some(reason),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Coingate {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Coingate {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Coingate
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Coingate {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "/api/v2/orders"))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = coingate::CoingateRouterData::from((amount, req));
let connector_req = coingate::CoingatePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: coingate::CoingatePaymentsResponse = res
.response
.parse_struct("Coingate PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Coingate {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/{}{}",
self.base_url(connectors),
"api/v2/orders/",
connector_id
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: coingate::CoingateSyncResponse = res
.response
.parse_struct("coingate PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Coingate {
fn build_request(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Coingate".to_string(),
}
.into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Coingate {
fn build_request(
&self,
_req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Void".to_string(),
connector: "Coingate".to_string(),
}
.into())
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Coingate {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/api/v2/orders/{connector_payment_id}/refunds",
self.base_url(connectors),
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = coingate::CoingateRouterData::from((amount, req));
let connector_req = coingate::CoingateRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: coingate::CoingateRefundResponse = res
.response
.parse_struct("coingate RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Coingate {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let order_id = req.request.connector_transaction_id.clone();
let id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}/api/v2/orders/{order_id}/refunds/{id}",
self.base_url(connectors),
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
req: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: coingate::CoingateRefundResponse = res
.response
.parse_struct("coingate RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: req.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorValidation for Coingate {}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Coingate {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let message = std::str::from_utf8(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
Ok(message.to_string().into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif: CoingateWebhookBody = request
.body
.parse_struct("CoingateWebhookBody")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(notif.id.to_string()),
))
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif: CoingateWebhookBody = request
.body
.parse_struct("CoingateWebhookBody")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
match notif.status {
transformers::CoingatePaymentStatus::Pending => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)
}
transformers::CoingatePaymentStatus::Confirming
| transformers::CoingatePaymentStatus::New => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired)
}
transformers::CoingatePaymentStatus::Paid => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
transformers::CoingatePaymentStatus::Invalid
| transformers::CoingatePaymentStatus::Expired
| transformers::CoingatePaymentStatus::Canceled => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure)
}
}
}
async fn verify_webhook_source(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
connector_account_details: crypto::Encryptable<masking::Secret<serde_json::Value>>,
_connector_label: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_account_details: ConnectorAuthType = connector_account_details
.parse_value::<ConnectorAuthType>("ConnectorAuthType")
.change_context_lazy(|| errors::ConnectorError::WebhookSourceVerificationFailed)?;
let auth_type = coingate::CoingateAuthType::try_from(&connector_account_details)?;
let secret_key = auth_type.merchant_token.expose();
let request_body: CoingateWebhookBody = request
.body
.parse_struct("CoingateWebhookBody")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let token = request_body.token.expose();
Ok(secret_key == token)
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif: CoingateWebhookBody = request
.body
.parse_struct("CoingateWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Box::new(notif))
}
}
static COINGATE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods =
vec![CaptureMethod::Automatic, CaptureMethod::SequentialAutomatic];
let mut coingate_supported_payment_methods = SupportedPaymentMethods::new();
coingate_supported_payment_methods.add(
PaymentMethod::Crypto,
PaymentMethodType::CryptoCurrency,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
coingate_supported_payment_methods
});
static COINGATE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Coingate",
description: "CoinGate's online payment solution makes it easy for businesses to accept Bitcoin, Ethereum, stablecoins and other cryptocurrencies for payments on any website.",
connector_type: enums::HyperswitchConnectorCategory::AlternativePaymentMethod,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static COINGATE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];
impl ConnectorSpecifications for Coingate {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&COINGATE_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*COINGATE_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&COINGATE_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__cryptopay.rs
|
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
crypto::{self, GenerateDigest, SignMessage},
date_time,
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::ResultExt;
use hex::encode;
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{PaymentsAuthorizeType, PaymentsSyncType, Response},
webhooks,
};
use masking::{Mask, PeekInterface};
use transformers as cryptopay;
use self::cryptopay::CryptopayWebhookDetails;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, ForeignTryFrom},
};
#[derive(Clone)]
pub struct Cryptopay {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Cryptopay {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl api::Payment for Cryptopay {}
impl api::PaymentSession for Cryptopay {}
impl api::ConnectorAccessToken for Cryptopay {}
impl api::MandateSetup for Cryptopay {}
impl api::PaymentAuthorize for Cryptopay {}
impl api::PaymentSync for Cryptopay {}
impl api::PaymentCapture for Cryptopay {}
impl api::PaymentVoid for Cryptopay {}
impl api::Refund for Cryptopay {}
impl api::RefundExecute for Cryptopay {}
impl api::RefundSync for Cryptopay {}
impl api::PaymentToken for Cryptopay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Cryptopay
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Cryptopay
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let method = self.get_http_method();
let payload = match method {
Method::Get => String::default(),
Method::Post | Method::Put | Method::Delete | Method::Patch => {
let body = self
.get_request_body(req, connectors)?
.get_inner_value()
.peek()
.to_owned();
let md5_payload = crypto::Md5
.generate_digest(body.as_bytes())
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
encode(md5_payload)
}
};
let api_method = method.to_string();
let now = date_time::date_as_yyyymmddthhmmssmmmz()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let date = format!("{}+00:00", now.split_at(now.len() - 5).0);
let content_type = self.get_content_type().to_string();
let api = (self.get_url(req, connectors)?).replace(self.base_url(connectors), "");
let auth = cryptopay::CryptopayAuthType::try_from(&req.connector_auth_type)?;
let sign_req: String = format!("{api_method}\n{payload}\n{content_type}\n{date}\n{api}");
let authz = crypto::HmacSha1::sign_message(
&crypto::HmacSha1,
auth.api_secret.peek().as_bytes(),
sign_req.as_bytes(),
)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to sign the message")?;
let authz = common_utils::consts::BASE64_ENGINE.encode(authz);
let auth_string: String = format!("HMAC {}:{}", auth.api_key.peek(), authz);
let headers = vec![
(
headers::AUTHORIZATION.to_string(),
auth_string.into_masked(),
),
(headers::DATE.to_string(), date.into()),
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
];
Ok(headers)
}
}
impl ConnectorCommon for Cryptopay {
fn id(&self) -> &'static str {
"cryptopay"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.cryptopay.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = cryptopay::CryptopayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.peek().to_owned().into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cryptopay::CryptopayErrorResponse = res
.response
.parse_struct("CryptopayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.code,
message: response.error.message,
reason: response.error.reason,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cryptopay {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cryptopay {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Cryptopay
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Cryptopay".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cryptopay {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/api/invoices", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = cryptopay::CryptopayRouterData::from((amount, req));
let connector_req = cryptopay::CryptopayPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: cryptopay::CryptopayPaymentsResponse = res
.response
.parse_struct("Cryptopay PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let capture_amount_in_minor_units = match response.data.price_amount {
Some(ref amount) => Some(utils::convert_back_amount_to_minor_units(
self.amount_converter,
amount.clone(),
data.request.currency,
)?),
None => None,
};
RouterData::foreign_try_from((
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
capture_amount_in_minor_units,
))
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorValidation for Cryptopay {
fn validate_psync_reference_id(
&self,
_data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
// since we can make psync call with our reference_id, having connector_transaction_id is not an mandatory criteria
Ok(())
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cryptopay {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let custom_id = req.connector_request_reference_id.clone();
Ok(format!(
"{}/api/invoices/custom_id/{custom_id}",
self.base_url(connectors)
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: cryptopay::CryptopayPaymentsResponse = res
.response
.parse_struct("cryptopay PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let capture_amount_in_minor_units = match response.data.price_amount {
Some(ref amount) => Some(utils::convert_back_amount_to_minor_units(
self.amount_converter,
amount.clone(),
data.request.currency,
)?),
None => None,
};
RouterData::foreign_try_from((
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
capture_amount_in_minor_units,
))
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cryptopay {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cryptopay {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cryptopay {}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cryptopay {}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Cryptopay {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let base64_signature =
utils::get_header_key_value("X-Cryptopay-Signature", request.headers)?;
hex::decode(base64_signature)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let message = std::str::from_utf8(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
Ok(message.to_string().into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif: CryptopayWebhookDetails =
request
.body
.parse_struct("CryptopayWebhookDetails")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
match notif.data.custom_id {
Some(custom_id) => Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::PaymentAttemptId(custom_id),
)),
None => Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(notif.data.id),
)),
}
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif: CryptopayWebhookDetails =
request
.body
.parse_struct("CryptopayWebhookDetails")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
match notif.data.status {
cryptopay::CryptopayPaymentStatus::Completed => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
cryptopay::CryptopayPaymentStatus::Unresolved => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired)
}
cryptopay::CryptopayPaymentStatus::Cancelled => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure)
}
_ => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported),
}
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif: CryptopayWebhookDetails =
request
.body
.parse_struct("CryptopayWebhookDetails")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Box::new(notif))
}
}
static CRYPTOPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::SequentialAutomatic,
];
let mut cryptopay_supported_payment_methods = SupportedPaymentMethods::new();
cryptopay_supported_payment_methods.add(
enums::PaymentMethod::Crypto,
enums::PaymentMethodType::CryptoCurrency,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods,
specific_features: None,
},
);
cryptopay_supported_payment_methods
});
static CRYPTOPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Cryptopay",
description: "Simple and secure solution to buy and manage crypto. Make quick international transfers, spend your BTC, ETH and other crypto assets.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static CRYPTOPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];
impl ConnectorSpecifications for Cryptopay {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&CRYPTOPAY_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*CRYPTOPAY_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&CRYPTOPAY_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__custombilling.rs
|
pub mod transformers;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use transformers as custombilling;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Custombilling {
amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Custombilling {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Custombilling {}
impl api::PaymentSession for Custombilling {}
impl api::ConnectorAccessToken for Custombilling {}
impl api::MandateSetup for Custombilling {}
impl api::PaymentAuthorize for Custombilling {}
impl api::PaymentSync for Custombilling {}
impl api::PaymentCapture for Custombilling {}
impl api::PaymentVoid for Custombilling {}
impl api::Refund for Custombilling {}
impl api::RefundExecute for Custombilling {}
impl api::RefundSync for Custombilling {}
impl api::PaymentToken for Custombilling {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Custombilling
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Custombilling
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Custombilling {
fn id(&self) -> &'static str {
"custombilling"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
// TODO! Check connector documentation, on which unit they are processing the currency.
// If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
// if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, _connectors: &'a Connectors) -> &'a str {
""
}
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: custombilling::CustombillingErrorResponse = res
.response
.parse_struct("CustombillingErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code,
message: response.message,
reason: response.reason,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Custombilling {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Custombilling {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Custombilling {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Custombilling
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for Custombilling
{
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = custombilling::CustombillingRouterData::from((amount, req));
let connector_req =
custombilling::CustombillingPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: custombilling::CustombillingPaymentsResponse = res
.response
.parse_struct("Custombilling PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Custombilling {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: custombilling::CustombillingPaymentsResponse = res
.response
.parse_struct("custombilling PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Custombilling {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: custombilling::CustombillingPaymentsResponse = res
.response
.parse_struct("Custombilling PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Custombilling {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Custombilling {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data =
custombilling::CustombillingRouterData::from((refund_amount, req));
let connector_req =
custombilling::CustombillingRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: custombilling::RefundResponse = res
.response
.parse_struct("custombilling RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Custombilling {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: custombilling::RefundResponse = res
.response
.parse_struct("custombilling RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Custombilling {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
impl ConnectorSpecifications for Custombilling {}
|
crates__hyperswitch_connectors__src__connectors__cybersource.rs
|
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
mandate_revoke::MandateRevoke,
payments::{
Authorize, Capture, CompleteAuthorize, IncrementalAuthorization, PSync,
PaymentMethodToken, Session, SetupMandate, Void,
},
refunds::{Execute, RSync},
Authenticate, PostAuthenticate, PreAuthenticate, PreProcessing,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, MandateRevokeRequestData,
PaymentMethodTokenizationData, PaymentsAuthenticateData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData,
PaymentsPostAuthenticateData, PaymentsPreAuthenticateData, PaymentsPreProcessingData,
PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, PaymentsResponseData,
RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
MandateRevokeRouterData, PaymentsAuthenticateRouterData, PaymentsAuthorizeRouterData,
PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData,
PaymentsIncrementalAuthorizationRouterData, PaymentsPostAuthenticateRouterData,
PaymentsPreAuthenticateRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData,
RefundExecuteRouterData, RefundSyncRouterData, SetupMandateRouterData,
},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::payouts::PoFulfill,
router_response_types::PayoutsResponseData,
types::{PayoutsData, PayoutsRouterData},
};
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::types::PayoutFulfillType;
use hyperswitch_interfaces::{
api::{
self,
payments::PaymentSession,
refunds::{Refund, RefundExecute, RefundSync},
ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{
IncrementalAuthorizationType, MandateRevokeType, PaymentsAuthenticateType,
PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType,
PaymentsPostAuthenticateType, PaymentsPreAuthenticateType, PaymentsPreProcessingType,
PaymentsSyncType, PaymentsVoidType, RefundExecuteType, RefundSyncType, Response,
SetupMandateType,
},
webhooks,
};
use masking::{ExposeInterface, Mask, Maskable, PeekInterface};
use ring::{digest, hmac};
use time::OffsetDateTime;
use transformers as cybersource;
use url::Url;
use crate::{
constants::{self, headers},
types::ResponseRouterData,
utils::{
self, convert_amount, PaymentMethodDataType, PaymentsAuthorizeRequestData,
PaymentsPreAuthenticateRequestData, RefundsRequestData, RouterData as OtherRouterData,
},
};
#[derive(Clone)]
pub struct Cybersource {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Cybersource {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl Cybersource {
pub fn generate_digest(&self, payload: &[u8]) -> String {
let payload_digest = digest::digest(&digest::SHA256, payload);
consts::BASE64_ENGINE.encode(payload_digest)
}
pub fn generate_signature(
&self,
auth: cybersource::CybersourceAuthType,
host: String,
resource: &str,
payload: &String,
date: OffsetDateTime,
http_method: Method,
) -> CustomResult<String, errors::ConnectorError> {
let cybersource::CybersourceAuthType {
api_key,
merchant_account,
api_secret,
} = auth;
let is_post_method = matches!(http_method, Method::Post);
let is_patch_method = matches!(http_method, Method::Patch);
let is_delete_method = matches!(http_method, Method::Delete);
let digest_str = if is_post_method || is_patch_method {
"digest "
} else {
""
};
let headers = format!("host date (request-target) {digest_str}v-c-merchant-id");
let request_target = if is_post_method {
format!("(request-target): post {resource}\ndigest: SHA-256={payload}\n")
} else if is_patch_method {
format!("(request-target): patch {resource}\ndigest: SHA-256={payload}\n")
} else if is_delete_method {
format!("(request-target): delete {resource}\n")
} else {
format!("(request-target): get {resource}\n")
};
let signature_string = format!(
"host: {host}\ndate: {date}\n{request_target}v-c-merchant-id: {}",
merchant_account.peek()
);
let key_value = consts::BASE64_ENGINE
.decode(api_secret.expose())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "connector_account_details.api_secret",
})?;
let key = hmac::Key::new(hmac::HMAC_SHA256, &key_value);
let signature_value =
consts::BASE64_ENGINE.encode(hmac::sign(&key, signature_string.as_bytes()).as_ref());
let signature_header = format!(
r#"keyid="{}", algorithm="HmacSHA256", headers="{headers}", signature="{signature_value}""#,
api_key.peek()
);
Ok(signature_header)
}
}
impl ConnectorCommon for Cybersource {
fn id(&self) -> &'static str {
"cybersource"
}
fn common_get_content_type(&self) -> &'static str {
"application/json;charset=utf-8"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.cybersource.base_url.as_ref()
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<
cybersource::CybersourceErrorResponse,
Report<common_utils::errors::ParsingError>,
> = res.response.parse_struct("Cybersource ErrorResponse");
let error_message = if res.status_code == 401 {
constants::CONNECTOR_UNAUTHORIZED_ERROR
} else {
hyperswitch_interfaces::consts::NO_ERROR_MESSAGE
};
match response {
Ok(transformers::CybersourceErrorResponse::StandardError(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let (code, message, reason) = match response.error_information {
Some(ref error_info) => {
let detailed_error_info = error_info.details.as_ref().map(|details| {
details
.iter()
.map(|det| format!("{} : {}", det.field, det.reason))
.collect::<Vec<_>>()
.join(", ")
});
(
error_info.reason.clone(),
error_info.message.clone(),
transformers::get_error_reason(
Some(error_info.message.clone()),
detailed_error_info,
None,
),
)
}
None => {
let detailed_error_info = response.details.map(|details| {
details
.iter()
.map(|det| format!("{} : {}", det.field, det.reason))
.collect::<Vec<_>>()
.join(", ")
});
(
response.reason.clone().map_or(
hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
|reason| reason.to_string(),
),
response
.message
.clone()
.map_or(error_message.to_string(), |msg| msg.to_string()),
transformers::get_error_reason(
response.message,
detailed_error_info,
None,
),
)
}
};
Ok(ErrorResponse {
status_code: res.status_code,
code,
message,
reason,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Ok(transformers::CybersourceErrorResponse::AuthenticationError(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: response.response.rmsg.clone(),
reason: Some(response.response.rmsg),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Ok(transformers::CybersourceErrorResponse::NotAvailableError(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_response = response
.errors
.iter()
.map(|error_info| {
format!(
"{}: {}",
error_info.error_type.clone().unwrap_or("".to_string()),
error_info.message.clone().unwrap_or("".to_string())
)
})
.collect::<Vec<String>>()
.join(" & ");
Ok(ErrorResponse {
status_code: res.status_code,
code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: error_response.clone(),
reason: Some(error_response),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Err(error_msg) => {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
router_env::logger::error!(deserialization_error =? error_msg);
utils::handle_json_response_deserialization_failure(res, "cybersource")
}
}
}
}
impl ConnectorValidation for Cybersource {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::ApplePay,
PaymentMethodDataType::GooglePay,
PaymentMethodDataType::SamsungPay,
]);
utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Cybersource
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let date = OffsetDateTime::now_utc();
let cybersource_req = self.get_request_body(req, connectors)?;
let auth = cybersource::CybersourceAuthType::try_from(&req.connector_auth_type)?;
let merchant_account = auth.merchant_account.clone();
let base_url = connectors.cybersource.base_url.as_str();
let cybersource_host =
Url::parse(base_url).change_context(errors::ConnectorError::RequestEncodingFailed)?;
let host = cybersource_host
.host_str()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
let path: String = self
.get_url(req, connectors)?
.chars()
.skip(base_url.len() - 1)
.collect();
let sha256 = self.generate_digest(cybersource_req.get_inner_value().expose().as_bytes());
let http_method = self.get_http_method();
let signature = self.generate_signature(
auth,
host.to_string(),
path.as_str(),
&sha256,
date,
http_method,
)?;
let mut headers = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
headers::ACCEPT.to_string(),
"application/hal+json;charset=utf-8".to_string().into(),
),
(
"v-c-merchant-id".to_string(),
merchant_account.into_masked(),
),
("Date".to_string(), date.to_string().into()),
("Host".to_string(), host.to_string().into()),
("Signature".to_string(), signature.into_masked()),
];
if matches!(http_method, Method::Post | Method::Put | Method::Patch) {
headers.push((
"Digest".to_string(),
format!("SHA-256={sha256}").into_masked(),
));
}
Ok(headers)
}
}
impl api::Payment for Cybersource {}
impl api::PaymentsPreAuthenticate for Cybersource {}
impl api::PaymentsPostAuthenticate for Cybersource {}
impl api::PaymentsAuthenticate for Cybersource {}
impl api::PaymentAuthorize for Cybersource {}
impl api::PaymentSync for Cybersource {}
impl api::PaymentVoid for Cybersource {}
impl api::PaymentCapture for Cybersource {}
impl api::PaymentIncrementalAuthorization for Cybersource {}
impl api::MandateSetup for Cybersource {}
impl api::ConnectorAccessToken for Cybersource {}
impl api::PaymentToken for Cybersource {}
impl api::PaymentsPreProcessing for Cybersource {}
impl api::PaymentsCompleteAuthorize for Cybersource {}
impl api::ConnectorMandateRevoke for Cybersource {}
impl api::Payouts for Cybersource {}
#[cfg(feature = "payouts")]
impl api::PayoutFulfill for Cybersource {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Cybersource
{
// Not Implemented (R)
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Cybersource
{
fn get_headers(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}pts/v2/payments/", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = cybersource::CybersourceZeroMandateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(SetupMandateType::get_headers(self, req, connectors)?)
.set_body(SetupMandateType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
let response: cybersource::CybersourcePaymentsResponse = res
.response
.parse_struct("CybersourceSetupMandatesResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
let attempt_status = match response.reason {
Some(reason) => match reason {
transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),
transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None,
},
None => None,
};
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>
for Cybersource
{
fn get_headers(
&self,
req: &MandateRevokeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_http_method(&self) -> Method {
Method::Delete
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &MandateRevokeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}tms/v1/paymentinstruments/{}",
self.base_url(connectors),
utils::RevokeMandateRequestData::get_connector_mandate_id(&req.request)?
))
}
fn build_request(
&self,
req: &MandateRevokeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Delete)
.url(&MandateRevokeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(MandateRevokeType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &MandateRevokeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<MandateRevokeRouterData, errors::ConnectorError> {
if matches!(res.status_code, 204) {
event_builder.map(|i| i.set_response_body(&serde_json::json!({"mandate_status": common_enums::MandateStatus::Revoked.to_string()})));
Ok(MandateRevokeRouterData {
response: Ok(MandateRevokeResponseData {
mandate_status: common_enums::MandateStatus::Revoked,
}),
..data.clone()
})
} else {
// If http_code != 204 || http_code != 4xx, we dont know any other response scenario yet.
let response_value: serde_json::Value = serde_json::from_slice(&res.response)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let response_string = response_value.to_string();
event_builder.map(|i| {
i.set_response_body(
&serde_json::json!({"response_string": response_string.clone()}),
)
});
router_env::logger::info!(connector_response=?response_string);
Ok(MandateRevokeRouterData {
response: Err(ErrorResponse {
code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: response_string.clone(),
reason: Some(response_string),
status_code: res.status_code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..data.clone()
})
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cybersource {
// Not Implemented (R)
}
impl PaymentSession for Cybersource {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cybersource {}
impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
for Cybersource
{
fn get_headers(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let redirect_response = req.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
match redirect_response.params {
Some(param) if !param.clone().peek().is_empty() => Ok(format!(
"{}risk/v1/authentications",
self.base_url(connectors)
)),
Some(_) | None => Ok(format!(
"{}risk/v1/authentication-results",
self.base_url(connectors)
)),
}
}
fn get_request_body(
&self,
req: &PaymentsPreProcessingRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let minor_amount = req.request.minor_amount;
let currency =
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?;
let amount = convert_amount(self.amount_converter, minor_amount, currency)?;
let connector_router_data = cybersource::CybersourceRouterData::from((amount, req));
let connector_req =
cybersource::CybersourcePreProcessingRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsPreProcessingType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsPreProcessingType::get_headers(
self, req, connectors,
)?)
.set_body(PaymentsPreProcessingType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsPreProcessingRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: cybersource::CybersourcePreProcessingResponse = res
.response
.parse_struct("Cybersource AuthEnrollmentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>
for Cybersource
{
fn get_headers(
&self,
req: &PaymentsPreAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsPreAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}risk/v1/authentication-setups",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsPreAuthenticateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let minor_amount = req.request.get_minor_amount();
let currency = req.request.get_currency()?;
let amount = convert_amount(self.amount_converter, minor_amount, currency)?;
let connector_router_data = cybersource::CybersourceRouterData::from((amount, req));
let connector_req =
cybersource::CybersourceAuthSetupRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsPreAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsPreAuthenticateType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(PaymentsPreAuthenticateType::get_headers(
self, req, connectors,
)?)
.set_body(self.get_request_body(req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsPreAuthenticateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsPreAuthenticateRouterData, errors::ConnectorError> {
let response: cybersource::CybersourceAuthSetupResponse = res
.response
.parse_struct("Cybersource AuthSetupResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authenticate, PaymentsAuthenticateData, PaymentsResponseData>
for Cybersource
{
fn get_headers(
&self,
req: &PaymentsAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}risk/v1/authentications",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsAuthenticateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let minor_amount =
req.request
.minor_amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "minor_amount",
})?;
let currency =
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?;
let amount = convert_amount(self.amount_converter, minor_amount, currency)?;
let connector_router_data = cybersource::CybersourceRouterData::from((amount, req));
let connector_req =
cybersource::CybersourceAuthEnrollmentRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthenticateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthenticateType::get_headers(
self, req, connectors,
)?)
.set_body(PaymentsAuthenticateType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthenticateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthenticateRouterData, errors::ConnectorError> {
let response: cybersource::CybersourceAuthenticateResponse = res
.response
.parse_struct("Cybersource AuthEnrollmentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData>
for Cybersource
{
fn get_headers(
&self,
req: &PaymentsPostAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsPostAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}risk/v1/authentication-results",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsPostAuthenticateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let minor_amount =
req.request
.minor_amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "minor_amount",
})?;
let currency =
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?;
let amount = convert_amount(self.amount_converter, minor_amount, currency)?;
let connector_router_data = cybersource::CybersourceRouterData::from((amount, req));
let connector_req =
cybersource::CybersourceAuthValidateRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsPostAuthenticateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsPostAuthenticateType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(PaymentsPostAuthenticateType::get_headers(
self, req, connectors,
)?)
.set_body(PaymentsPostAuthenticateType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsPostAuthenticateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsPostAuthenticateRouterData, errors::ConnectorError> {
let response: cybersource::CybersourceAuthenticateResponse = res
.response
.parse_struct("Cybersource AuthEnrollmentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cybersource {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}pts/v2/payments/{}/captures",
self.base_url(connectors),
connector_payment_id
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = cybersource::CybersourceRouterData::from((amount, req));
let connector_req =
cybersource::CybersourcePaymentsCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
.set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
errors::ConnectorError,
> {
let response: cybersource::CybersourcePaymentsResponse = res
.response
.parse_struct("Cybersource PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cybersource {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}tss/v2/transactions/{}",
self.base_url(connectors),
connector_payment_id
))
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: cybersource::CybersourceTransactionResponse = res
.response
.parse_struct("Cybersource PaymentSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[cfg(feature = "v1")]
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cybersource {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
if req.is_three_ds()
&& req.request.is_card()
&& (req.request.connector_mandate_id().is_none()
&& req.request.get_optional_network_transaction_id().is_none())
&& req.request.authentication_data.is_none()
{
Ok(format!(
"{}risk/v1/authentication-setups",
ConnectorCommon::base_url(self, connectors)
))
} else {
Ok(format!(
"{}pts/v2/payments/",
ConnectorCommon::base_url(self, connectors)
))
}
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = cybersource::CybersourceRouterData::from((amount, req));
if req.is_three_ds()
&& req.request.is_card()
&& (req.request.connector_mandate_id().is_none()
&& req.request.get_optional_network_transaction_id().is_none())
&& req.request.authentication_data.is_none()
{
let connector_req =
cybersource::CybersourceAuthSetupRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
} else {
let connector_req =
cybersource::CybersourcePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
if data.is_three_ds()
&& data.request.is_card()
&& (data.request.connector_mandate_id().is_none()
&& data.request.get_optional_network_transaction_id().is_none())
&& data.request.authentication_data.is_none()
{
let response: cybersource::CybersourceAuthSetupResponse = res
.response
.parse_struct("Cybersource AuthSetupResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
} else {
let response: cybersource::CybersourcePaymentsResponse = res
.response
.parse_struct("Cybersource PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
let attempt_status = match response.reason {
Some(reason) => match reason {
transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),
transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None,
},
None => None,
};
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
#[cfg(feature = "v2")]
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cybersource {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}pts/v2/payments/",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = cybersource::CybersourceRouterData::from((amount, req));
let connector_req =
cybersource::CybersourcePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: cybersource::CybersourcePaymentsResponse = res
.response
.parse_struct("Cybersource PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
let attempt_status = match response.reason {
Some(reason) => match reason {
transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),
transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None,
},
None => None,
};
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Cybersource {
fn get_url(
&self,
_req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}pts/v2/payouts", self.base_url(connectors)))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoFulfill>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.destination_currency,
)?;
let connector_router_data = cybersource::CybersourceRouterData::from((amount, req));
let connector_req =
cybersource::CybersourcePayoutFulfillRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutFulfillType::get_headers(self, req, connectors)?)
.set_body(PayoutFulfillType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PayoutsRouterData<PoFulfill>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoFulfill>, errors::ConnectorError> {
let response: cybersource::CybersourceFulfillResponse = res
.response
.parse_struct("CybersourceFulfillResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
let attempt_status = match response.reason {
Some(reason) => match reason {
transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),
transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None,
},
None => None,
};
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Cybersource
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}pts/v2/payments/",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = cybersource::CybersourceRouterData::from((amount, req));
let connector_req =
cybersource::CybersourcePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: cybersource::CybersourcePaymentsResponse = res
.response
.parse_struct("Cybersource PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
let attempt_status = match response.reason {
Some(reason) => match reason {
transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),
transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None,
},
None => None,
};
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cybersource {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}pts/v2/payments/{connector_payment_id}/reversals",
self.base_url(connectors)
))
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let minor_amount =
req.request
.minor_amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "Amount",
})?;
let currency =
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "Currency",
})?;
let amount = convert_amount(self.amount_converter, minor_amount, currency)?;
let connector_router_data = cybersource::CybersourceRouterData::from((amount, req));
let connector_req = cybersource::CybersourceVoidRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: cybersource::CybersourcePaymentsResponse = res
.response
.parse_struct("Cybersource PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl Refund for Cybersource {}
impl RefundExecute for Cybersource {}
impl RefundSync for Cybersource {}
#[allow(dead_code)]
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cybersource {
fn get_headers(
&self,
req: &RefundExecuteRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundExecuteRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}pts/v2/payments/{}/refunds",
self.base_url(connectors),
connector_payment_id
))
}
fn get_request_body(
&self,
req: &RefundExecuteRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = cybersource::CybersourceRouterData::from((refund_amount, req));
let connector_req =
cybersource::CybersourceRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundExecuteRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundExecuteRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundExecuteRouterData, errors::ConnectorError> {
let response: cybersource::CybersourceRefundResponse = res
.response
.parse_struct("Cybersource RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[allow(dead_code)]
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cybersource {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}tss/v2/transactions/{}",
self.base_url(connectors),
refund_id
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: cybersource::CybersourceRsyncResponse = res
.response
.parse_struct("Cybersource RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl
ConnectorIntegration<
IncrementalAuthorization,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
> for Cybersource
{
fn get_headers(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_http_method(&self) -> Method {
Method::Patch
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}pts/v2/payments/{}",
self.base_url(connectors),
connector_payment_id
))
}
fn get_request_body(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let minor_additional_amount = MinorUnit::new(req.request.additional_amount);
let additional_amount = convert_amount(
self.amount_converter,
minor_additional_amount,
req.request.currency,
)?;
let connector_router_data =
cybersource::CybersourceRouterData::from((additional_amount, req));
let connector_request =
cybersource::CybersourcePaymentsIncrementalAuthorizationRequest::try_from(
&connector_router_data,
)?;
Ok(RequestContent::Json(Box::new(connector_request)))
}
fn build_request(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Patch)
.url(&IncrementalAuthorizationType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(IncrementalAuthorizationType::get_headers(
self, req, connectors,
)?)
.set_body(IncrementalAuthorizationType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsIncrementalAuthorizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<
IncrementalAuthorization,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
>,
errors::ConnectorError,
> {
let response: cybersource::CybersourcePaymentsIncrementalAuthorizationResponse = res
.response
.parse_struct("Cybersource PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Cybersource {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static CYBERSOURCE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Maestro,
];
let mut cybersource_supported_payment_methods = SupportedPaymentMethods::new();
cybersource_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
cybersource_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
cybersource_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
cybersource_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
cybersource_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Paze,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
cybersource_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::SamsungPay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
cybersource_supported_payment_methods
});
static CYBERSOURCE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Cybersource",
description: "Cybersource provides payments, fraud protection, integrations, and support to help businesses grow with a digital-first approach.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static CYBERSOURCE_SUPPORTED_WEBHOOK_FLOWS: [common_enums::EventClass; 0] = [];
impl ConnectorSpecifications for Cybersource {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&CYBERSOURCE_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*CYBERSOURCE_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&CYBERSOURCE_SUPPORTED_WEBHOOK_FLOWS)
}
fn get_preprocessing_flow_if_needed(
&self,
current_flow_info: api::CurrentFlowInfo<'_>,
) -> Option<api::PreProcessingFlowName> {
match current_flow_info {
api::CurrentFlowInfo::Authorize { .. } => {
// during authorize flow, there is no pre processing flow. Only alternate PreAuthenticate flow
None
}
api::CurrentFlowInfo::CompleteAuthorize {
request_data,
payment_method: _,
..
} => {
// TODO: add logic before deciding the pre processing flow Authenticate or PostAuthenticate
let redirect_response = request_data.redirect_response.as_ref()?;
match redirect_response.params.as_ref() {
Some(param) if !param.peek().is_empty() => {
Some(api::PreProcessingFlowName::Authenticate)
}
Some(_) | None => Some(api::PreProcessingFlowName::PostAuthenticate),
}
}
api::CurrentFlowInfo::SetupMandate { .. } => None,
}
}
fn get_alternate_flow_if_needed(
&self,
current_flow: api::CurrentFlowInfo<'_>,
) -> Option<api::AlternateFlow> {
match current_flow {
api::CurrentFlowInfo::Authorize {
request_data,
auth_type,
} => {
if self.is_3ds_setup_required(request_data, *auth_type) {
Some(api::AlternateFlow::PreAuthenticate)
} else {
None
}
}
// No alternate flow for complete authorize
api::CurrentFlowInfo::CompleteAuthorize { .. } => None,
api::CurrentFlowInfo::SetupMandate { .. } => None,
}
}
fn is_pre_authentication_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool {
match current_flow {
api::CurrentFlowInfo::Authorize {
request_data,
auth_type,
} => self.is_3ds_setup_required(request_data, *auth_type),
// No alternate flow for complete authorize
api::CurrentFlowInfo::CompleteAuthorize { .. } => false,
api::CurrentFlowInfo::SetupMandate { .. } => false,
}
}
/// Check if authentication flow is required
fn is_authentication_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool {
match current_flow {
api::CurrentFlowInfo::Authorize { .. } => {
// during authorize flow, there is no post_authentication call needed
false
}
api::CurrentFlowInfo::CompleteAuthorize {
request_data,
payment_method: _,
..
} => {
// TODO: add logic before deciding the pre processing flow Authenticate or PostAuthenticate
let redirection_params = request_data
.redirect_response
.as_ref()
.and_then(|redirect_response| redirect_response.params.as_ref());
match redirection_params {
Some(param) if !param.peek().is_empty() => true,
Some(_) | None => false,
}
}
api::CurrentFlowInfo::SetupMandate { .. } => false,
}
}
/// Check if post-authentication flow is required
fn is_post_authentication_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool {
match current_flow {
api::CurrentFlowInfo::Authorize { .. } => {
// during authorize flow, there is no post_authentication call needed
false
}
api::CurrentFlowInfo::CompleteAuthorize {
request_data,
payment_method: _,
..
} => {
// TODO: add logic before deciding the pre processing flow Authenticate or PostAuthenticate
let redirection_params = request_data
.redirect_response
.as_ref()
.and_then(|redirect_response| redirect_response.params.as_ref());
match redirection_params {
Some(param) if !param.peek().is_empty() => false,
Some(_) | None => true,
}
}
api::CurrentFlowInfo::SetupMandate { .. } => false,
}
}
}
impl Cybersource {
pub fn is_3ds_setup_required(
&self,
request: &PaymentsAuthorizeData,
auth_type: common_enums::AuthenticationType,
) -> bool {
router_env::logger::info!(router_data_request=?request, auth_type=?auth_type, "Checking if 3DS setup is required for Cybersource");
auth_type.is_three_ds()
&& request.is_card()
&& (request.connector_mandate_id().is_none()
&& request.get_optional_network_transaction_id().is_none())
&& request.authentication_data.is_none()
}
}
|
crates__hyperswitch_connectors__src__connectors__cybersourcedecisionmanager.rs
|
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods,
},
};
#[cfg(feature = "frm")]
use hyperswitch_domain_models::{
router_flow_types::{Checkout, Transaction},
router_request_types::fraud_check::{FraudCheckCheckoutData, FraudCheckTransactionData},
router_response_types::fraud_check::FraudCheckResponseData,
};
#[cfg(feature = "frm")]
use hyperswitch_interfaces::api::{FraudCheck, FraudCheckCheckout, FraudCheckTransaction};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors::ConnectorError,
events::connector_api_logs::ConnectorEvent,
types::Response,
webhooks,
};
use masking::{ExposeInterface, Mask, Maskable, PeekInterface};
use ring::{digest, hmac};
use time::OffsetDateTime;
use transformers as cybersourcedecisionmanager;
use url::Url;
#[cfg(feature = "frm")]
use crate::types::{
FrmCheckoutRouterData, FrmCheckoutType, FrmTransactionRouterData, FrmTransactionType,
ResponseRouterData,
};
use crate::{
constants::{self, headers},
utils,
utils::convert_amount,
};
#[derive(Clone)]
pub struct Cybersourcedecisionmanager {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Cybersourcedecisionmanager {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
pub fn generate_digest(&self, payload: &[u8]) -> String {
let payload_digest = digest::digest(&digest::SHA256, payload);
consts::BASE64_ENGINE.encode(payload_digest)
}
pub fn generate_signature(
&self,
auth: cybersourcedecisionmanager::CybersourcedecisionmanagerAuthType,
host: String,
resource: &str,
payload: &String,
date: OffsetDateTime,
http_method: Method,
) -> CustomResult<String, ConnectorError> {
let cybersourcedecisionmanager::CybersourcedecisionmanagerAuthType {
api_key,
merchant_account,
api_secret,
} = auth;
let is_post_method = matches!(http_method, Method::Post);
let is_patch_method = matches!(http_method, Method::Patch);
let is_delete_method = matches!(http_method, Method::Delete);
let digest_str = if is_post_method || is_patch_method {
"digest "
} else {
""
};
let headers = format!("host date (request-target) {digest_str}v-c-merchant-id");
let request_target = if is_post_method {
format!("(request-target): post {resource}\ndigest: SHA-256={payload}\n")
} else if is_patch_method {
format!("(request-target): patch {resource}\ndigest: SHA-256={payload}\n")
} else if is_delete_method {
format!("(request-target): delete {resource}\n")
} else {
format!("(request-target): get {resource}\n")
};
let signature_string = format!(
"host: {host}\ndate: {date}\n{request_target}v-c-merchant-id: {}",
merchant_account.peek()
);
let key_value = consts::BASE64_ENGINE
.decode(api_secret.expose())
.change_context(ConnectorError::InvalidConnectorConfig {
config: "connector_account_details.api_secret",
})?;
let key = hmac::Key::new(hmac::HMAC_SHA256, &key_value);
let signature_value =
consts::BASE64_ENGINE.encode(hmac::sign(&key, signature_string.as_bytes()).as_ref());
let signature_header = format!(
r#"keyid="{}", algorithm="HmacSHA256", headers="{headers}", signature="{signature_value}""#,
api_key.peek()
);
Ok(signature_header)
}
}
impl api::Payment for Cybersourcedecisionmanager {}
impl api::PaymentSession for Cybersourcedecisionmanager {}
impl api::ConnectorAccessToken for Cybersourcedecisionmanager {}
impl api::MandateSetup for Cybersourcedecisionmanager {}
impl api::PaymentAuthorize for Cybersourcedecisionmanager {}
impl api::PaymentSync for Cybersourcedecisionmanager {}
impl api::PaymentCapture for Cybersourcedecisionmanager {}
impl api::PaymentVoid for Cybersourcedecisionmanager {}
impl api::Refund for Cybersourcedecisionmanager {}
impl api::RefundExecute for Cybersourcedecisionmanager {}
impl api::RefundSync for Cybersourcedecisionmanager {}
impl api::PaymentToken for Cybersourcedecisionmanager {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Cybersourcedecisionmanager
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response>
for Cybersourcedecisionmanager
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let date = OffsetDateTime::now_utc();
let cybersource_req = self.get_request_body(req, connectors)?;
let auth = cybersourcedecisionmanager::CybersourcedecisionmanagerAuthType::try_from(
&req.connector_auth_type,
)?;
let merchant_account = auth.merchant_account.clone();
let base_url = connectors.cybersource.base_url.as_str();
let cybersource_host =
Url::parse(base_url).change_context(ConnectorError::RequestEncodingFailed)?;
let host = cybersource_host
.host_str()
.ok_or(ConnectorError::RequestEncodingFailed)?;
let path: String = self
.get_url(req, connectors)?
.chars()
.skip(base_url.len() - 1)
.collect();
let sha256 = self.generate_digest(cybersource_req.get_inner_value().expose().as_bytes());
let http_method = self.get_http_method();
let signature = self.generate_signature(
auth,
host.to_string(),
path.as_str(),
&sha256,
date,
http_method,
)?;
let mut headers = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
headers::ACCEPT.to_string(),
"application/hal+json;charset=utf-8".to_string().into(),
),
(
"v-c-merchant-id".to_string(),
merchant_account.into_masked(),
),
("Date".to_string(), date.to_string().into()),
("Host".to_string(), host.to_string().into()),
("Signature".to_string(), signature.into_masked()),
];
if matches!(http_method, Method::Post | Method::Put | Method::Patch) {
headers.push((
"Digest".to_string(),
format!("SHA-256={sha256}").into_masked(),
));
}
Ok(headers)
}
}
impl ConnectorCommon for Cybersourcedecisionmanager {
fn id(&self) -> &'static str {
"cybersourcedecisionmanager"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json;charset=utf-8"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.cybersourcedecisionmanager.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let auth =
cybersourcedecisionmanager::CybersourcedecisionmanagerAuthType::try_from(auth_type)
.change_context(ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.expose().into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
let response: Result<
cybersourcedecisionmanager::CybersourceDecisionManagerErrorResponse,
Report<common_utils::errors::ParsingError>,
> = res
.response
.parse_struct("CybersourceDecisionManagerErrorResponse");
let error_message = if res.status_code == 401 {
constants::CONNECTOR_UNAUTHORIZED_ERROR
} else {
hyperswitch_interfaces::consts::NO_ERROR_MESSAGE
};
match response {
Ok(cybersourcedecisionmanager::CybersourceDecisionManagerErrorResponse::StandardError(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let (code, message, reason) = match response.error_information {
Some(ref error_info) => {
let detailed_error_info = error_info.details.as_ref().map(|details| {
details
.iter()
.map(|det| format!("{} : {}", det.field, det.reason))
.collect::<Vec<_>>()
.join(", ")
});
(
error_info.reason.clone(),
error_info.message.clone(),
cybersourcedecisionmanager::get_error_reason(
Some(error_info.message.clone()),
detailed_error_info,
None,
),
)
}
None => {
let detailed_error_info = response.details.map(|details| {
details
.iter()
.map(|det| format!("{} : {}", det.field, det.reason))
.collect::<Vec<_>>()
.join(", ")
});
(
response.reason.clone().map_or(
hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
|reason| reason.to_string(),
),
response
.message
.clone()
.map_or(error_message.to_string(), |msg| msg.to_string()),
transformers::get_error_reason(
response.message,
detailed_error_info,
None,
),
)
}
};
Ok(ErrorResponse {
status_code: res.status_code,
code,
message,
reason,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Ok(cybersourcedecisionmanager::CybersourceDecisionManagerErrorResponse::AuthenticationError(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: response.response.rmsg.clone(),
reason: Some(response.response.rmsg),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Ok(cybersourcedecisionmanager::CybersourceDecisionManagerErrorResponse::NotAvailableError(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_response = response
.errors
.iter()
.map(|error_info| {
format!(
"{}: {}",
error_info.error_type.clone().unwrap_or("".to_string()),
error_info.message.clone().unwrap_or("".to_string())
)
})
.collect::<Vec<String>>()
.join(" & ");
Ok(ErrorResponse {
status_code: res.status_code,
code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: error_response.clone(),
reason: Some(error_response),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Err(error_msg) => {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
router_env::logger::error!(deserialization_error =? error_msg);
utils::handle_json_response_deserialization_failure(res, "cybersource")
}
}
}
}
impl ConnectorValidation for Cybersourcedecisionmanager {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData>
for Cybersourcedecisionmanager
{
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>
for Cybersourcedecisionmanager
{
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Cybersourcedecisionmanager
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for Cybersourcedecisionmanager
{
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData>
for Cybersourcedecisionmanager
{
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData>
for Cybersourcedecisionmanager
{
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData>
for Cybersourcedecisionmanager
{
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData>
for Cybersourcedecisionmanager
{
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cybersourcedecisionmanager {}
#[cfg(feature = "frm")]
impl FraudCheck for Cybersourcedecisionmanager {}
#[cfg(feature = "frm")]
impl FraudCheckCheckout for Cybersourcedecisionmanager {}
#[cfg(feature = "frm")]
impl FraudCheckTransaction for Cybersourcedecisionmanager {}
#[cfg(feature = "frm")]
impl ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData>
for Cybersourcedecisionmanager
{
fn get_headers(
&self,
req: &FrmCheckoutRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &FrmCheckoutRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"risk/v1/decisions"
))
}
fn get_request_body(
&self,
req: &FrmCheckoutRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let currency = req
.request
.currency
.ok_or(ConnectorError::MissingRequiredField {
field_name: "Currency",
})?;
let amount = convert_amount(
self.amount_converter,
MinorUnit::new(req.request.amount),
currency,
)?;
let connector_router_data =
cybersourcedecisionmanager::CybersourcedecisionmanagerRouterData::from((amount, req));
let req_obj =
cybersourcedecisionmanager::CybersourcedecisionmanagerCheckoutRequest::try_from(
&connector_router_data,
)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &FrmCheckoutRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&FrmCheckoutType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(FrmCheckoutType::get_headers(self, req, connectors)?)
.set_body(FrmCheckoutType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &FrmCheckoutRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<FrmCheckoutRouterData, ConnectorError> {
let response: cybersourcedecisionmanager::CybersourcedecisionmanagerResponse = res
.response
.parse_struct("CybersourcedecisionmanagerPaymentsResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
<FrmCheckoutRouterData>::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[cfg(feature = "frm")]
impl ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData>
for Cybersourcedecisionmanager
{
fn get_headers(
&self,
req: &FrmTransactionRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let mut headers = self.build_headers(req, connectors)?;
// Override Accept header for Transaction endpoint
if let Some(header) = headers.iter_mut().find(|(k, _)| k == headers::ACCEPT) {
header.1 = "application/json".to_string().into();
}
Ok(headers)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &FrmTransactionRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
let id =
req.request
.frm_transaction_id
.clone()
.ok_or(ConnectorError::MissingRequiredField {
field_name: "frm_transaction_id",
})?;
Ok(format!(
"{}risk/v1/decisions/{}/actions",
self.base_url(connectors),
id
))
}
fn get_request_body(
&self,
req: &FrmTransactionRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let req_obj =
cybersourcedecisionmanager::CybersourcedecisionmanagerTransactionRequest::try_from(
req,
)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &FrmTransactionRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&FrmTransactionType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(FrmTransactionType::get_headers(self, req, connectors)?)
.set_body(FrmTransactionType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &FrmTransactionRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<FrmTransactionRouterData, ConnectorError> {
let response: cybersourcedecisionmanager::CybersourcedecisionmanagerResponse = res
.response
.parse_struct("CybersourcedecisionmanagerPaymentsResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
<FrmTransactionRouterData>::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Cybersourcedecisionmanager {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
}
static CYBERSOURCEDECISIONMANAGER_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(SupportedPaymentMethods::new);
static CYBERSOURCEDECISIONMANAGER_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Cybersourcedecisionmanager",
description: "Cybersourcedecisionmanager connector",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static CYBERSOURCEDECISIONMANAGER_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Cybersourcedecisionmanager {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&CYBERSOURCEDECISIONMANAGER_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*CYBERSOURCEDECISIONMANAGER_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&CYBERSOURCEDECISIONMANAGER_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__cybersourcedecisionmanager__transformers.rs
|
use api_models::payments::AdditionalPaymentData;
use common_enums::enums;
use common_utils::{pii, types::StringMajorUnit};
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, RouterData},
router_request_types::ResponseId,
router_response_types::fraud_check::FraudCheckResponseData,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{FrmCheckoutRouterData, FrmTransactionRouterData, ResponseRouterData},
utils::{
AddressDetailsData as _, FrmTransactionRouterDataRequest, RouterData as OtherRouterData,
},
};
//TODO: Fill the struct with respective fields
pub struct CybersourcedecisionmanagerRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for CybersourcedecisionmanagerRouterData<T> {
fn from((amount, router_data): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourcedecisionmanagerTransactionRequest {
decision_information: DecisionInformation,
processing_information: TransactionProcessingInformation,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DecisionInformation {
decision: TransactionDecision,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionProcessingInformation {
action_list: Vec<ActionList>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionDecision {
Accept,
Reject,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ActionList {
Capture,
Reverse,
}
// Auth Struct
pub struct CybersourcedecisionmanagerAuthType {
pub(super) api_key: Secret<String>,
pub(super) merchant_account: Secret<String>,
pub(super) api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for CybersourcedecisionmanagerAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = auth_type
{
Ok(Self {
api_key: api_key.to_owned(),
merchant_account: key1.to_owned(),
api_secret: api_secret.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
// Fraud Response status
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CybersourcedecisionmanagerStatus {
Accepted,
Rejected,
PendingReview,
Declined,
PendingAuthentication,
InvalidRequest,
Challenge,
AuthenticationFailed,
}
impl From<CybersourcedecisionmanagerStatus> for common_enums::FraudCheckStatus {
fn from(item: CybersourcedecisionmanagerStatus) -> Self {
match item {
CybersourcedecisionmanagerStatus::Accepted => Self::Legit,
CybersourcedecisionmanagerStatus::Rejected
| CybersourcedecisionmanagerStatus::Declined => Self::Fraud,
CybersourcedecisionmanagerStatus::PendingReview
| CybersourcedecisionmanagerStatus::Challenge
| CybersourcedecisionmanagerStatus::PendingAuthentication => Self::ManualReview,
CybersourcedecisionmanagerStatus::InvalidRequest
| CybersourcedecisionmanagerStatus::AuthenticationFailed => Self::TransactionFailure,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CybersourcedecisionmanagerResponse {
status: CybersourcedecisionmanagerStatus,
id: String,
error_information: Option<CybersourcedecisionmanagerErrorInformation>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CybersourcedecisionmanagerErrorInformation {
reason: Option<String>,
}
impl<F, T>
TryFrom<ResponseRouterData<F, CybersourcedecisionmanagerResponse, T, FraudCheckResponseData>>
for RouterData<F, T, FraudCheckResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CybersourcedecisionmanagerResponse, T, FraudCheckResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
status: common_enums::FraudCheckStatus::from(item.response.status),
connector_metadata: None,
score: None,
reason: item
.response
.error_information
.and_then(|info| info.reason.map(serde_json::Value::from)),
}),
..item.data
})
}
}
impl TryFrom<&FrmTransactionRouterData> for CybersourcedecisionmanagerTransactionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &FrmTransactionRouterData) -> Result<Self, Self::Error> {
let decision = match item.is_payment_successful() {
Some(false) => TransactionDecision::Reject,
None | Some(true) => TransactionDecision::Accept,
};
let action_list = match decision {
TransactionDecision::Accept => vec![ActionList::Capture],
TransactionDecision::Reject => vec![ActionList::Reverse],
};
Ok(Self {
decision_information: DecisionInformation { decision },
processing_information: TransactionProcessingInformation { action_list },
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourcedecisionmanagerTransactionResponse {
pub id: String,
pub status: CybersourcedecisionmanagerTransactionStatus,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CybersourcedecisionmanagerTransactionStatus {
Accepted,
Rejected,
}
impl<F, T>
TryFrom<
ResponseRouterData<
F,
CybersourcedecisionmanagerTransactionResponse,
T,
FraudCheckResponseData,
>,
> for RouterData<F, T, FraudCheckResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
CybersourcedecisionmanagerTransactionResponse,
T,
FraudCheckResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
status: common_enums::FraudCheckStatus::from(item.response.status),
connector_metadata: None,
score: None,
reason: None,
}),
..item.data
})
}
}
impl From<CybersourcedecisionmanagerTransactionStatus> for common_enums::FraudCheckStatus {
fn from(item: CybersourcedecisionmanagerTransactionStatus) -> Self {
match item {
CybersourcedecisionmanagerTransactionStatus::Accepted => Self::Legit,
CybersourcedecisionmanagerTransactionStatus::Rejected => Self::Fraud,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CybersourceDecisionManagerErrorResponse {
AuthenticationError(Box<CybersourceDecisionManagerAuthenticationErrorResponse>),
//If the request resource is not available/exists in cybersource
NotAvailableError(Box<CybersourceDecisionManagerNotAvailableErrorResponse>),
StandardError(Box<CybersourceDecisionManagerStandardErrorResponse>),
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CybersourceDecisionManagerAuthenticationErrorResponse {
pub response: AuthenticationErrorInformation,
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct AuthenticationErrorInformation {
pub rmsg: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceDecisionManagerNotAvailableErrorResponse {
pub errors: Vec<CybersourceNotAvailableErrorObject>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceNotAvailableErrorObject {
#[serde(rename = "type")]
pub error_type: Option<String>,
pub message: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceDecisionManagerStandardErrorResponse {
pub error_information: Option<ErrorInformation>,
pub status: Option<String>,
pub message: Option<String>,
pub reason: Option<String>,
pub details: Option<Vec<Details>>,
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct ErrorInformation {
pub message: String,
pub reason: String,
pub details: Option<Vec<Details>>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Details {
pub field: String,
pub reason: String,
}
pub fn get_error_reason(
error_info: Option<String>,
detailed_error_info: Option<String>,
avs_error_info: Option<String>,
) -> Option<String> {
match (error_info, detailed_error_info, avs_error_info) {
(Some(message), Some(details), Some(avs_message)) => Some(format!(
"{message}, detailed_error_information: {details}, avs_message: {avs_message}",
)),
(Some(message), Some(details), None) => {
Some(format!("{message}, detailed_error_information: {details}"))
}
(Some(message), None, Some(avs_message)) => {
Some(format!("{message}, avs_message: {avs_message}"))
}
(None, Some(details), Some(avs_message)) => {
Some(format!("{details}, avs_message: {avs_message}"))
}
(Some(message), None, None) => Some(message),
(None, Some(details), None) => Some(details),
(None, None, Some(avs_message)) => Some(avs_message),
(None, None, None) => None,
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourcedecisionmanagerCheckoutRequest {
client_reference_information: ClientReferenceInformation,
payment_information: Option<PaymentInformation>,
order_information: OrderInformationWithBill,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientReferenceInformation {
code: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymentInformation {
Cards(Box<CardPaymentInformation>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardPaymentInformation {
card: Card,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
expiration_month: Option<Secret<String>>,
expiration_year: Option<Secret<String>>,
#[serde(rename = "type")]
card_type: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderInformationWithBill {
amount_details: Amount,
bill_to: Option<BillTo>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
total_amount: StringMajorUnit,
currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BillTo {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address1: Option<Secret<String>>,
locality: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
administrative_area: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
postal_code: Option<Secret<String>>,
country: Option<enums::CountryAlpha2>,
email: Option<pii::Email>,
}
impl TryFrom<&CybersourcedecisionmanagerRouterData<&FrmCheckoutRouterData>>
for CybersourcedecisionmanagerCheckoutRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CybersourcedecisionmanagerRouterData<&FrmCheckoutRouterData>,
) -> Result<Self, Self::Error> {
let client_reference_information = ClientReferenceInformation::from(item);
let email = item.router_data.request.email.clone();
let address = item.router_data.get_optional_billing();
let bill_to = address.and_then(|addr| {
addr.address.as_ref().map(|addr| BillTo {
first_name: addr.first_name.remove_new_line(),
last_name: addr.last_name.remove_new_line(),
address1: addr.line1.remove_new_line(),
locality: addr.city.remove_new_line(),
administrative_area: addr.to_state_code_as_optional().unwrap_or_else(|_| {
addr.state
.remove_new_line()
.as_ref()
.map(|state| truncate_string(state, 20)) //NOTE: Cybersource connector throws error if billing state exceeds 20 characters, so truncation is done to avoid payment failure
}),
postal_code: addr.zip.remove_new_line(),
country: addr.country,
email,
})
});
let order_information = OrderInformationWithBill::try_from((item, bill_to))?;
let payment_information = match item.router_data.request.payment_method_data.as_ref() {
Some(AdditionalPaymentData::Card(card_info)) => Some(PaymentInformation::Cards(
Box::new(CardPaymentInformation {
card: Card {
expiration_month: card_info.card_exp_month.clone(),
expiration_year: card_info.card_exp_year.clone(),
card_type: card_info
.card_network
.clone()
.and_then(|network| get_cybersource_card_type(network))
.map(|s| s.to_string()),
},
}),
)),
Some(_) | None => None,
};
Ok(Self {
payment_information,
order_information,
client_reference_information,
})
}
}
impl From<&CybersourcedecisionmanagerRouterData<&FrmCheckoutRouterData>>
for ClientReferenceInformation
{
fn from(item: &CybersourcedecisionmanagerRouterData<&FrmCheckoutRouterData>) -> Self {
Self {
code: Some(item.router_data.connector_request_reference_id.clone()),
}
}
}
impl
TryFrom<(
&CybersourcedecisionmanagerRouterData<&FrmCheckoutRouterData>,
Option<BillTo>,
)> for OrderInformationWithBill
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, bill_to): (
&CybersourcedecisionmanagerRouterData<&FrmCheckoutRouterData>,
Option<BillTo>,
),
) -> Result<Self, Self::Error> {
let currency = item.router_data.request.currency.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "currency",
},
)?;
Ok(Self {
amount_details: Amount {
total_amount: item.amount.to_owned(),
currency,
},
bill_to,
})
}
}
pub trait RemoveNewLine {
fn remove_new_line(&self) -> Self;
}
impl RemoveNewLine for Option<Secret<String>> {
fn remove_new_line(&self) -> Self {
self.clone().map(|masked_value| {
let new_string = masked_value.expose().replace("\n", " ");
Secret::new(new_string)
})
}
}
impl RemoveNewLine for Option<String> {
fn remove_new_line(&self) -> Self {
self.clone().map(|value| value.replace("\n", " "))
}
}
fn truncate_string(state: &Secret<String>, max_len: usize) -> Secret<String> {
let exposed = state.clone().expose();
let truncated = exposed.get(..max_len).unwrap_or(&exposed);
Secret::new(truncated.to_string())
}
fn get_cybersource_card_type(card_network: common_enums::CardNetwork) -> Option<&'static str> {
match card_network {
common_enums::CardNetwork::Visa => Some("001"),
common_enums::CardNetwork::Mastercard => Some("002"),
common_enums::CardNetwork::AmericanExpress => Some("003"),
common_enums::CardNetwork::JCB => Some("007"),
common_enums::CardNetwork::DinersClub => Some("005"),
common_enums::CardNetwork::Discover => Some("004"),
common_enums::CardNetwork::CartesBancaires => Some("036"),
common_enums::CardNetwork::UnionPay => Some("062"),
//"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024"
common_enums::CardNetwork::Maestro => Some("042"),
common_enums::CardNetwork::Interac
| common_enums::CardNetwork::RuPay
| common_enums::CardNetwork::Star
| common_enums::CardNetwork::Accel
| common_enums::CardNetwork::Pulse
| common_enums::CardNetwork::Nyce => None,
}
}
|
crates__hyperswitch_connectors__src__connectors__datatrans.rs
|
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use base64::Engine;
use common_enums::{CaptureMethod, PaymentMethod, PaymentMethodType};
use common_utils::{
consts::BASE64_ENGINE,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts::NO_ERROR_CODE,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},
};
use masking::{Mask, PeekInterface};
use transformers as datatrans;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{
self, convert_amount, PaymentsAuthorizeRequestData, RefundsRequestData,
RouterData as OtherRouterData,
},
};
impl api::Payment for Datatrans {}
impl api::PaymentSession for Datatrans {}
impl api::ConnectorAccessToken for Datatrans {}
impl api::MandateSetup for Datatrans {}
impl api::PaymentAuthorize for Datatrans {}
impl api::PaymentSync for Datatrans {}
impl api::PaymentCapture for Datatrans {}
impl api::PaymentVoid for Datatrans {}
impl api::Refund for Datatrans {}
impl api::RefundExecute for Datatrans {}
impl api::RefundSync for Datatrans {}
impl api::PaymentToken for Datatrans {}
#[derive(Clone)]
pub struct Datatrans {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Datatrans {
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Datatrans
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Datatrans
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Datatrans {
fn id(&self) -> &'static str {
"datatrans"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.datatrans.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = datatrans::DatatransAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_key = format!("{}:{}", auth.merchant_id.peek(), auth.passcode.peek());
let auth_header = format!("Basic {}", BASE64_ENGINE.encode(auth_key));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth_header.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let (cow, _, _) = encoding_rs::ISO_8859_10.decode(&res.response);
let response = cow.as_ref().to_string();
if utils::is_html_response(&response) {
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: NO_ERROR_CODE.to_owned(),
message: response.clone(),
reason: Some(response),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
let response: datatrans::DatatransErrorResponse = res
.response
.parse_struct("DatatransErrorType")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.code.clone(),
message: response.error.message.clone(),
reason: Some(response.error.message.clone()),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
}
impl ConnectorValidation for Datatrans {
fn validate_mandate_payment(
&self,
_pm_type: Option<PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let connector = self.id();
match pm_data {
PaymentMethodData::Card(_) => Ok(()),
_ => Err(errors::ConnectorError::NotSupported {
message: " mandate payment".to_string(),
connector,
}
.into()),
}
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Datatrans {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Datatrans {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Datatrans
{
fn get_headers(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v1/transactions", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = datatrans::DatatransPaymentsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::SetupMandateType::get_headers(self, req, connectors)?)
.set_body(types::SetupMandateType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
let response: datatrans::DatatransResponse = res
.response
.parse_struct("Datatrans PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Datatrans {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url = self.base_url(connectors);
if req.request.payment_method_data == PaymentMethodData::MandatePayment {
// MIT
Ok(format!("{base_url}v1/transactions/authorize"))
} else if req.request.is_mandate_payment() {
// CIT
Ok(format!("{base_url}v1/transactions"))
} else {
// Direct
if req.is_three_ds() && req.request.authentication_data.is_none() {
Ok(format!("{base_url}v1/transactions"))
} else {
Ok(format!("{base_url}v1/transactions/authorize"))
}
}
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = datatrans::DatatransRouterData::try_from((amount, req))?;
let connector_req = datatrans::DatatransPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: datatrans::DatatransResponse = res
.response
.parse_struct("Datatrans PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Datatrans {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
let base_url = self.base_url(connectors);
Ok(format!("{base_url}v1/transactions/{connector_payment_id}"))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: datatrans::DatatransSyncResponse = res
.response
.parse_struct("datatrans DatatransSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Datatrans {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
let base_url = self.base_url(connectors);
Ok(format!(
"{base_url}v1/transactions/{connector_payment_id}/settle"
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = datatrans::DatatransRouterData::try_from((amount, req))?;
let connector_req = datatrans::DataPaymentCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response = if res.response.is_empty() {
datatrans::DataTransCaptureResponse::Empty
} else {
res.response
.parse_struct("Datatrans DataTransCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?
};
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Datatrans {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let transaction_id = req.request.connector_transaction_id.clone();
let base_url = self.base_url(connectors);
Ok(format!("{base_url}v1/transactions/{transaction_id}/cancel"))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response = if res.response.is_empty() {
datatrans::DataTransCancelResponse::Empty
} else {
res.response
.parse_struct("Datatrans DataTransCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?
};
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Datatrans {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let transaction_id = req.request.connector_transaction_id.clone();
let base_url = self.base_url(connectors);
Ok(format!("{base_url}v1/transactions/{transaction_id}/credit"))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = datatrans::DatatransRouterData::try_from((amount, req))?;
let connector_req = datatrans::DatatransRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: datatrans::DatatransRefundsResponse = res
.response
.parse_struct("datatrans DatatransRefundsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Datatrans {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_refund_id = req.request.get_connector_refund_id()?;
let base_url = self.base_url(connectors);
Ok(format!("{base_url}v1/transactions/{connector_refund_id}"))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: datatrans::DatatransSyncResponse = res
.response
.parse_struct("datatrans DatatransSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Datatrans {
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static DATATRANS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
CaptureMethod::Automatic,
CaptureMethod::Manual,
CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Maestro,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::CartesBancaires,
];
let mut datatrans_supported_payment_methods = SupportedPaymentMethods::new();
datatrans_supported_payment_methods.add(
PaymentMethod::Card,
PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: common_enums::enums::FeatureStatus::Supported,
refunds: common_enums::enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
datatrans_supported_payment_methods.add(
PaymentMethod::Card,
PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: common_enums::enums::FeatureStatus::Supported,
refunds: common_enums::enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
datatrans_supported_payment_methods
});
static DATATRANS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Datatrans",
description:
"Datatrans is a payment gateway that facilitates the processing of payments, including hosting smart payment forms and correctly routing payment information.",
connector_type: common_enums::enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: common_enums::enums::ConnectorIntegrationStatus::Live,
};
static DATATRANS_SUPPORTED_WEBHOOK_FLOWS: [common_enums::enums::EventClass; 0] = [];
impl ConnectorSpecifications for Datatrans {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&DATATRANS_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*DATATRANS_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> {
Some(&DATATRANS_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__datatrans__transformers.rs
|
use std::collections::HashMap;
use api_models::payments::{self, AdditionalPaymentData};
use common_enums::enums;
use common_utils::{pii::Email, request::Method, types::MinorUnit};
use hyperswitch_domain_models::{
payment_method_data::{Card, PaymentMethodData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{PaymentsAuthorizeData, ResponseId, SetupMandateRequestData},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types,
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
},
utils::{
get_unimplemented_payment_method_error_message, AdditionalCardInfo, CardData as _,
PaymentsAuthorizeRequestData, RouterData as _,
},
};
const TRANSACTION_ALREADY_CANCELLED: &str = "transaction already canceled";
const TRANSACTION_ALREADY_SETTLED: &str = "already settled";
const REDIRECTION_SBX_URL: &str = "https://pay.sandbox.datatrans.com";
const REDIRECTION_PROD_URL: &str = "https://pay.datatrans.com";
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct DatatransErrorResponse {
pub error: DatatransError,
}
pub struct DatatransAuthType {
pub(super) merchant_id: Secret<String>,
pub(super) passcode: Secret<String>,
}
pub struct DatatransRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DatatransPaymentsRequest {
pub amount: Option<MinorUnit>,
pub currency: enums::Currency,
pub card: DataTransPaymentDetails,
pub refno: String,
pub auto_settle: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub redirect: Option<RedirectUrls>,
pub option: Option<DataTransCreateAlias>,
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DataTransCreateAlias {
pub create_alias: bool,
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct RedirectUrls {
pub success_url: Option<String>,
pub cancel_url: Option<String>,
pub error_url: Option<String>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TransactionType {
Payment,
Credit,
CardCheck,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TransactionStatus {
Initialized,
Authenticated,
Authorized,
Settled,
Canceled,
Transmitted,
Failed,
ChallengeOngoing,
ChallengeRequired,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(untagged)]
pub enum DatatransSyncResponse {
Error(DatatransError),
Response(SyncResponse),
}
#[derive(Debug, Deserialize, Serialize)]
pub enum DataTransCaptureResponse {
Error(DatatransError),
Empty,
}
#[derive(Debug, Deserialize, Serialize)]
pub enum DataTransCancelResponse {
Error(DatatransError),
Empty,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SyncResponse {
pub transaction_id: String,
#[serde(rename = "type")]
pub res_type: TransactionType,
pub status: TransactionStatus,
pub detail: SyncDetails,
pub card: Option<SyncCardDetails>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SyncCardDetails {
pub alias: Option<String>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SyncDetails {
fail: Option<FailDetails>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct FailDetails {
reason: Option<String>,
message: Option<String>,
}
#[derive(Serialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum DataTransPaymentDetails {
Cards(PlainCardDetails),
Mandate(MandateDetails),
}
#[derive(Serialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PlainCardDetails {
#[serde(rename = "type")]
pub res_type: String,
pub number: cards::CardNumber,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
pub cvv: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "3D")]
pub three_ds: Option<ThreeDSecureData>,
}
#[derive(Serialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct MandateDetails {
#[serde(rename = "type")]
pub res_type: String,
pub alias: String,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
}
#[derive(Serialize, Clone, Debug)]
pub struct ThreedsInfo {
cardholder: CardHolder,
}
#[derive(Serialize, Clone, Debug)]
#[serde(untagged)]
pub enum ThreeDSecureData {
Cardholder(ThreedsInfo),
Authentication(ThreeDSData),
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSData {
#[serde(rename = "threeDSTransactionId")]
pub three_ds_transaction_id: Option<Secret<String>>,
pub cavv: Secret<String>,
pub eci: Option<String>,
pub xid: Option<Secret<String>>,
#[serde(rename = "threeDSVersion")]
pub three_ds_version: Option<String>,
#[serde(rename = "authenticationResponse")]
pub authentication_response: String,
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardHolder {
cardholder_name: Secret<String>,
email: Email,
}
#[derive(Debug, Clone, Serialize, Default, Deserialize)]
pub struct DatatransError {
pub code: String,
pub message: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DatatransResponse {
TransactionResponse(DatatransSuccessResponse),
ErrorResponse(DatatransError),
ThreeDSResponse(Datatrans3DSResponse),
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatatransSuccessResponse {
pub transaction_id: String,
pub acquirer_authorization_code: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DatatransRefundsResponse {
Success(DatatransSuccessResponse),
Error(DatatransError),
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Datatrans3DSResponse {
pub transaction_id: String,
#[serde(rename = "3D")]
pub three_ds_enrolled: ThreeDSEnolled,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSEnolled {
pub enrolled: bool,
}
#[derive(Default, Debug, Serialize)]
pub struct DatatransRefundRequest {
pub amount: MinorUnit,
pub currency: enums::Currency,
pub refno: String,
}
#[derive(Debug, Serialize, Clone)]
pub struct DataPaymentCaptureRequest {
pub amount: MinorUnit,
pub currency: enums::Currency,
pub refno: String,
}
impl<T> TryFrom<(MinorUnit, T)> for DatatransRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
impl TryFrom<&types::SetupMandateRouterData> for DatatransPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => Ok(Self {
amount: None,
currency: item.request.currency,
card: DataTransPaymentDetails::Cards(PlainCardDetails {
res_type: "PLAIN".to_string(),
number: req_card.card_number.clone(),
expiry_month: req_card.card_exp_month.clone(),
expiry_year: req_card.get_card_expiry_year_2_digit()?,
cvv: req_card.card_cvc.clone(),
three_ds: Some(ThreeDSecureData::Cardholder(ThreedsInfo {
cardholder: CardHolder {
cardholder_name: item.get_billing_full_name()?,
email: item.get_billing_email()?,
},
})),
}),
refno: item.connector_request_reference_id.clone(),
auto_settle: true, // zero auth doesn't support manual capture
option: Some(DataTransCreateAlias { create_alias: true }),
redirect: Some(RedirectUrls {
success_url: item.request.router_return_url.clone(),
cancel_url: item.request.router_return_url.clone(),
error_url: item.request.router_return_url.clone(),
}),
}),
PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Datatrans"),
))?
}
}
}
}
impl TryFrom<&DatatransRouterData<&types::PaymentsAuthorizeRouterData>>
for DatatransPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let is_mandate_payment = item.router_data.request.is_mandate_payment();
let option =
is_mandate_payment.then_some(DataTransCreateAlias { create_alias: true });
// provides return url for only mandate payment(CIT) or 3ds through datatrans
let redirect = if is_mandate_payment
|| (item.router_data.is_three_ds()
&& item.router_data.request.authentication_data.is_none())
{
Some(RedirectUrls {
success_url: item.router_data.request.router_return_url.clone(),
cancel_url: item.router_data.request.router_return_url.clone(),
error_url: item.router_data.request.router_return_url.clone(),
})
} else {
None
};
Ok(Self {
amount: Some(item.amount),
currency: item.router_data.request.currency,
card: create_card_details(item, &req_card)?,
refno: item.router_data.connector_request_reference_id.clone(),
auto_settle: item.router_data.request.is_auto_capture()?,
option,
redirect,
})
}
PaymentMethodData::MandatePayment => {
let additional_payment_data = match item
.router_data
.request
.additional_payment_method_data
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "additional_payment_method_data",
})? {
AdditionalPaymentData::Card(card) => *card,
_ => Err(errors::ConnectorError::NotSupported {
message: "Payment Method Not Supported".to_string(),
connector: "DataTrans",
})?,
};
Ok(Self {
amount: Some(item.amount),
currency: item.router_data.request.currency,
card: create_mandate_details(item, &additional_payment_data)?,
refno: item.router_data.connector_request_reference_id.clone(),
auto_settle: item.router_data.request.is_auto_capture()?,
option: None,
redirect: None,
})
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Datatrans"),
))?
}
}
}
}
impl TryFrom<&ConnectorAuthType> for DatatransAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
merchant_id: key1.clone(),
passcode: api_key.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
fn get_status(item: &DatatransResponse, is_auto_capture: bool) -> enums::AttemptStatus {
match item {
DatatransResponse::ErrorResponse(_) => enums::AttemptStatus::Failure,
DatatransResponse::TransactionResponse(_) => {
if is_auto_capture {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
DatatransResponse::ThreeDSResponse(_) => enums::AttemptStatus::AuthenticationPending,
}
}
fn create_card_details(
item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>,
card: &Card,
) -> Result<DataTransPaymentDetails, error_stack::Report<errors::ConnectorError>> {
let mut details = PlainCardDetails {
res_type: "PLAIN".to_string(),
number: card.card_number.clone(),
expiry_month: card.card_exp_month.clone(),
expiry_year: card.get_card_expiry_year_2_digit()?,
cvv: card.card_cvc.clone(),
three_ds: None,
};
if let Some(auth_data) = &item.router_data.request.authentication_data {
details.three_ds = Some(ThreeDSecureData::Authentication(ThreeDSData {
three_ds_transaction_id: auth_data
.threeds_server_transaction_id
.clone()
.map(Secret::new),
cavv: auth_data.cavv.clone(),
eci: auth_data.eci.clone(),
xid: auth_data.ds_trans_id.clone().map(Secret::new),
three_ds_version: auth_data
.message_version
.clone()
.map(|version| version.to_string()),
authentication_response: "Y".to_string(),
}));
} else if item.router_data.is_three_ds() {
details.three_ds = Some(ThreeDSecureData::Cardholder(ThreedsInfo {
cardholder: CardHolder {
cardholder_name: item.router_data.get_billing_full_name()?,
email: item.router_data.get_billing_email()?,
},
}));
}
Ok(DataTransPaymentDetails::Cards(details))
}
fn create_mandate_details(
item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>,
additional_card_details: &payments::AdditionalCardInfo,
) -> Result<DataTransPaymentDetails, error_stack::Report<errors::ConnectorError>> {
let alias = item.router_data.request.get_connector_mandate_id()?;
Ok(DataTransPaymentDetails::Mandate(MandateDetails {
res_type: "ALIAS".to_string(),
alias,
expiry_month: additional_card_details.card_exp_month.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "card_exp_month",
},
)?,
expiry_year: additional_card_details.get_card_expiry_year_2_digit()?,
}))
}
impl From<SyncResponse> for enums::AttemptStatus {
fn from(item: SyncResponse) -> Self {
match item.res_type {
TransactionType::Payment => match item.status {
TransactionStatus::Authorized => Self::Authorized,
TransactionStatus::Settled | TransactionStatus::Transmitted => Self::Charged,
TransactionStatus::ChallengeOngoing | TransactionStatus::ChallengeRequired => {
Self::AuthenticationPending
}
TransactionStatus::Canceled => Self::Voided,
TransactionStatus::Failed => Self::Failure,
TransactionStatus::Initialized | TransactionStatus::Authenticated => Self::Pending,
},
TransactionType::CardCheck => match item.status {
TransactionStatus::Settled
| TransactionStatus::Transmitted
| TransactionStatus::Authorized => Self::Charged,
TransactionStatus::ChallengeOngoing | TransactionStatus::ChallengeRequired => {
Self::AuthenticationPending
}
TransactionStatus::Canceled => Self::Voided,
TransactionStatus::Failed => Self::Failure,
TransactionStatus::Initialized | TransactionStatus::Authenticated => Self::Pending,
},
TransactionType::Credit => Self::Failure,
}
}
}
impl From<SyncResponse> for enums::RefundStatus {
fn from(item: SyncResponse) -> Self {
match item.res_type {
TransactionType::Credit => match item.status {
TransactionStatus::Settled | TransactionStatus::Transmitted => Self::Success,
TransactionStatus::ChallengeOngoing | TransactionStatus::ChallengeRequired => {
Self::Pending
}
TransactionStatus::Initialized
| TransactionStatus::Authenticated
| TransactionStatus::Authorized
| TransactionStatus::Canceled
| TransactionStatus::Failed => Self::Failure,
},
TransactionType::Payment | TransactionType::CardCheck => Self::Failure,
}
}
}
impl<F>
TryFrom<ResponseRouterData<F, DatatransResponse, PaymentsAuthorizeData, PaymentsResponseData>>
for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DatatransResponse, PaymentsAuthorizeData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = get_status(&item.response, item.data.request.is_auto_capture()?);
let response = match &item.response {
DatatransResponse::ErrorResponse(error) => Err(ErrorResponse {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message.clone()),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
DatatransResponse::TransactionResponse(response) => {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
}
DatatransResponse::ThreeDSResponse(response) => {
let redirection_link = match item.data.test_mode {
Some(true) => format!("{REDIRECTION_SBX_URL}/v1/start"),
Some(false) | None => format!("{REDIRECTION_PROD_URL}/v1/start"),
};
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.transaction_id.clone(),
),
redirection_data: Box::new(Some(RedirectForm::Form {
endpoint: format!("{}/{}", redirection_link, response.transaction_id),
method: Method::Get,
form_fields: HashMap::new(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl<F>
TryFrom<ResponseRouterData<F, DatatransResponse, SetupMandateRequestData, PaymentsResponseData>>
for RouterData<F, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
DatatransResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
// zero auth doesn't support manual capture
let status = get_status(&item.response, true);
let response = match &item.response {
DatatransResponse::ErrorResponse(error) => Err(ErrorResponse {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message.clone()),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
DatatransResponse::TransactionResponse(response) => {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
}
DatatransResponse::ThreeDSResponse(response) => {
let redirection_link = match item.data.test_mode {
Some(true) => format!("{REDIRECTION_SBX_URL}/v1/start"),
Some(false) | None => format!("{REDIRECTION_PROD_URL}/v1/start"),
};
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.transaction_id.clone(),
),
redirection_data: Box::new(Some(RedirectForm::Form {
endpoint: format!("{}/{}", redirection_link, response.transaction_id),
method: Method::Get,
form_fields: HashMap::new(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl<F> TryFrom<&DatatransRouterData<&types::RefundsRouterData<F>>> for DatatransRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DatatransRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
currency: item.router_data.request.currency,
refno: item.router_data.request.refund_id.clone(),
})
}
}
impl TryFrom<RefundsResponseRouterData<Execute, DatatransRefundsResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, DatatransRefundsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
DatatransRefundsResponse::Error(error) => Ok(Self {
response: Err(ErrorResponse {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
DatatransRefundsResponse::Success(response) => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: response.transaction_id,
refund_status: enums::RefundStatus::Success,
}),
..item.data
}),
}
}
}
impl TryFrom<RefundsResponseRouterData<RSync, DatatransSyncResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, DatatransSyncResponse>,
) -> Result<Self, Self::Error> {
let response = match item.response {
DatatransSyncResponse::Error(error) => Err(ErrorResponse {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
DatatransSyncResponse::Response(response) => Ok(RefundsResponseData {
connector_refund_id: response.transaction_id.to_string(),
refund_status: enums::RefundStatus::from(response),
}),
};
Ok(Self {
response,
..item.data
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<DatatransSyncResponse>>
for types::PaymentsSyncRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<DatatransSyncResponse>,
) -> Result<Self, Self::Error> {
match item.response {
DatatransSyncResponse::Error(error) => {
let response = Err(ErrorResponse {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
response,
..item.data
})
}
DatatransSyncResponse::Response(sync_response) => {
let status = enums::AttemptStatus::from(sync_response.clone());
let response = if status == enums::AttemptStatus::Failure {
let (code, message) = match sync_response.detail.fail {
Some(fail_details) => (
fail_details.reason.unwrap_or(NO_ERROR_CODE.to_string()),
fail_details.message.unwrap_or(NO_ERROR_MESSAGE.to_string()),
),
None => (NO_ERROR_CODE.to_string(), NO_ERROR_MESSAGE.to_string()),
};
Err(ErrorResponse {
code,
message: message.clone(),
reason: Some(message),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
let mandate_reference = sync_response
.card
.as_ref()
.and_then(|card| card.alias.as_ref())
.map(|alias| MandateReference {
connector_mandate_id: Some(alias.clone()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
sync_response.transaction_id.to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
}
}
impl TryFrom<&DatatransRouterData<&types::PaymentsCaptureRouterData>>
for DataPaymentCaptureRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DatatransRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
currency: item.router_data.request.currency,
refno: item.router_data.connector_request_reference_id.clone(),
})
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<DataTransCaptureResponse>>
for types::PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<DataTransCaptureResponse>,
) -> Result<Self, Self::Error> {
let status = match item.response {
DataTransCaptureResponse::Error(error) => {
if error.message == *TRANSACTION_ALREADY_SETTLED {
common_enums::AttemptStatus::Charged
} else {
common_enums::AttemptStatus::Failure
}
}
// Datatrans http code 204 implies Successful Capture
//https://api-reference.datatrans.ch/#tag/v1transactions/operation/settle
DataTransCaptureResponse::Empty => {
if item.http_code == 204 {
common_enums::AttemptStatus::Charged
} else {
common_enums::AttemptStatus::Failure
}
}
};
Ok(Self {
status,
..item.data
})
}
}
impl TryFrom<PaymentsCancelResponseRouterData<DataTransCancelResponse>>
for types::PaymentsCancelRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<DataTransCancelResponse>,
) -> Result<Self, Self::Error> {
let status = match item.response {
// Datatrans http code 204 implies Successful Cancellation
//https://api-reference.datatrans.ch/#tag/v1transactions/operation/cancel
DataTransCancelResponse::Empty => {
if item.http_code == 204 {
common_enums::AttemptStatus::Voided
} else {
common_enums::AttemptStatus::Failure
}
}
DataTransCancelResponse::Error(error) => {
if error.message == *TRANSACTION_ALREADY_CANCELLED {
common_enums::AttemptStatus::Voided
} else {
common_enums::AttemptStatus::Failure
}
}
};
Ok(Self {
status,
..item.data
})
}
}
|
crates__hyperswitch_connectors__src__connectors__deutschebank.rs
|
pub mod transformers;
use std::{sync::LazyLock, time::SystemTime};
use actix_web::http::header::Date;
use base64::Engine;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{
Authorize, Capture, CompleteAuthorize, PSync, PaymentMethodToken, Session,
SetupMandate, Void,
},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefreshTokenRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask, Secret};
use rand::distributions::{Alphanumeric, DistString};
use ring::hmac;
use transformers as deutschebank;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{
self, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
RefundsRequestData, RouterData as ConnectorRouterData,
},
};
#[derive(Clone)]
pub struct Deutschebank {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Deutschebank {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Deutschebank {}
impl api::PaymentSession for Deutschebank {}
impl api::ConnectorAccessToken for Deutschebank {}
impl api::MandateSetup for Deutschebank {}
impl api::PaymentAuthorize for Deutschebank {}
impl api::PaymentsCompleteAuthorize for Deutschebank {}
impl api::PaymentSync for Deutschebank {}
impl api::PaymentCapture for Deutschebank {}
impl api::PaymentVoid for Deutschebank {}
impl api::Refund for Deutschebank {}
impl api::RefundExecute for Deutschebank {}
impl api::RefundSync for Deutschebank {}
impl api::PaymentToken for Deutschebank {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Deutschebank
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Deutschebank
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let access_token = req
.access_token
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let mut header = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", access_token.token.expose()).into_masked(),
),
];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Deutschebank {
fn id(&self) -> &'static str {
"deutschebank"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.deutschebank.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = deutschebank::DeutschebankAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::MERCHANT_ID.to_string(),
auth.merchant_id.expose().into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: deutschebank::PaymentsErrorResponse = res
.response
.parse_struct("PaymentsErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.rc,
message: response.message.clone(),
reason: Some(response.message),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Deutschebank {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: hyperswitch_domain_models::payment_method_data::PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd =
std::collections::HashSet::from([utils::PaymentMethodDataType::SepaBankDebit]);
utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Deutschebank {
//TODO: implement sessions flow
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Deutschebank
{
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Deutschebank {
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/security/v1/token", self.base_url(connectors)))
}
fn get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn build_request(
&self,
req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let auth = deutschebank::DeutschebankAuthType::try_from(&req.connector_auth_type)?;
let client_id = auth.client_id.expose();
let date = Date(SystemTime::now().into()).to_string();
let random_string = Alphanumeric.sample_string(&mut rand::thread_rng(), 50);
let string_to_sign = client_id.clone() + &date + &random_string;
let key = hmac::Key::new(hmac::HMAC_SHA256, auth.client_key.expose().as_bytes());
let client_secret = format!(
"V1:{}",
common_utils::consts::BASE64_ENGINE
.encode(hmac::sign(&key, string_to_sign.as_bytes()).as_ref())
);
let headers = vec![
(
headers::X_RANDOM_VALUE.to_string(),
random_string.into_masked(),
),
(headers::X_REQUEST_DATE.to_string(), date.into_masked()),
(
headers::CONTENT_TYPE.to_string(),
types::RefreshTokenType::get_content_type(self)
.to_string()
.into(),
),
];
let connector_req = deutschebank::DeutschebankAccessTokenRequest {
client_id: Secret::from(client_id),
client_secret: Secret::from(client_secret),
grant_type: "client_credentials".to_string(),
scope: "ftx".to_string(),
};
let body = RequestContent::FormUrlEncoded(Box::new(connector_req));
let req = Some(
RequestBuilder::new()
.method(Method::Post)
.headers(headers)
.url(&types::RefreshTokenType::get_url(self, req, connectors)?)
.set_body(body)
.build(),
);
Ok(req)
}
fn handle_response(
&self,
data: &RefreshTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
let response: deutschebank::DeutschebankAccessTokenResponse = res
.response
.parse_struct("Paypal PaypalAuthUpdateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: deutschebank::DeutschebankError = res
.response
.parse_struct("DeutschebankError")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
match response {
deutschebank::DeutschebankError::PaymentsErrorResponse(response) => Ok(ErrorResponse {
status_code: res.status_code,
code: response.rc,
message: response.message.clone(),
reason: Some(response.message),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
deutschebank::DeutschebankError::AccessTokenErrorResponse(response) => {
Ok(ErrorResponse {
status_code: res.status_code,
code: response.cause.clone(),
message: response.cause.clone(),
reason: Some(response.description),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Deutschebank {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let event_id = req.connector_request_reference_id.clone();
let tx_action = if req.request.is_auto_capture()? {
"authorization"
} else {
"preauthorization"
};
if req.is_three_ds() && req.request.is_card() {
Ok(format!(
"{}/services/v2.1/headless3DSecure/event/{event_id}/{tx_action}/initialize",
self.base_url(connectors)
))
} else if !req.is_three_ds() && req.request.is_card() {
Err(errors::ConnectorError::NotSupported {
message: "Non-ThreeDs".to_owned(),
connector: "deutschebank",
}
.into())
} else if req.request.connector_mandate_id().is_none() {
Ok(format!(
"{}/services/v2.1/managedmandate",
self.base_url(connectors)
))
} else {
Ok(format!(
"{}/services/v2.1/payment/event/{event_id}/directdebit/{tx_action}",
self.base_url(connectors)
))
}
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = deutschebank::DeutschebankRouterData::from((amount, req));
let connector_req =
deutschebank::DeutschebankPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
if data.is_three_ds() && data.request.is_card() {
let response: deutschebank::DeutschebankThreeDSInitializeResponse = res
.response
.parse_struct("DeutschebankPaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
} else if data.request.connector_mandate_id().is_none() {
let response: deutschebank::DeutschebankMandatePostResponse = res
.response
.parse_struct("DeutschebankMandatePostResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
} else {
let response: deutschebank::DeutschebankPaymentsResponse = res
.response
.parse_struct("DeutschebankPaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Deutschebank
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let event_id = req.connector_request_reference_id.clone();
let tx_action = if req.request.is_auto_capture()? {
"authorization"
} else {
"preauthorization"
};
if req.is_three_ds() && matches!(req.payment_method, enums::PaymentMethod::Card) {
Ok(format!(
"{}/services/v2.1//headless3DSecure/event/{event_id}/final",
self.base_url(connectors)
))
} else {
Ok(format!(
"{}/services/v2.1/payment/event/{event_id}/directdebit/{tx_action}",
self.base_url(connectors)
))
}
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = deutschebank::DeutschebankRouterData::from((amount, req));
let connector_req =
deutschebank::DeutschebankCompleteAuthorizeRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: deutschebank::DeutschebankPaymentsResponse = res
.response
.parse_struct("Deutschebank PaymentsCompleteAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Deutschebank {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let tx_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/services/v2.1/payment/tx/{tx_id}",
self.base_url(connectors)
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: deutschebank::DeutschebankPaymentsResponse = res
.response
.parse_struct("DeutschebankPaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Deutschebank {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let event_id = req.connector_request_reference_id.clone();
let tx_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/services/v2.1/payment/event/{event_id}/tx/{tx_id}/capture",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = deutschebank::DeutschebankRouterData::from((amount, req));
let connector_req =
deutschebank::DeutschebankCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: deutschebank::DeutschebankPaymentsResponse = res
.response
.parse_struct("Deutschebank PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Deutschebank {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let event_id = req.connector_request_reference_id.clone();
let tx_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/services/v2.1/payment/event/{event_id}/tx/{tx_id}/reversal",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = deutschebank::DeutschebankReversalRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: deutschebank::DeutschebankPaymentsResponse = res
.response
.parse_struct("Deutschebank PaymentsCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Deutschebank {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let event_id = req.attempt_id.clone();
let tx_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/services/v2.1/payment/event/{event_id}/tx/{tx_id}/refund",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data =
deutschebank::DeutschebankRouterData::from((refund_amount, req));
let connector_req =
deutschebank::DeutschebankRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: deutschebank::DeutschebankPaymentsResponse = res
.response
.parse_struct("DeutschebankPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Deutschebank {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let tx_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}/services/v2.1/payment/tx/{tx_id}",
self.base_url(connectors)
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: deutschebank::DeutschebankPaymentsResponse = res
.response
.parse_struct("DeutschebankPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Deutschebank {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static DEUTSCHEBANK_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
];
let mut deutschebank_supported_payment_methods = SupportedPaymentMethods::new();
deutschebank_supported_payment_methods.add(
enums::PaymentMethod::BankDebit,
enums::PaymentMethodType::Sepa,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
deutschebank_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::NotSupported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
deutschebank_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::NotSupported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
deutschebank_supported_payment_methods
});
static DEUTSCHEBANK_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Deutsche Bank",
description:
"Deutsche Bank is a German multinational investment bank and financial services company ",
connector_type: enums::HyperswitchConnectorCategory::BankAcquirer,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static DEUTSCHEBANK_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Deutschebank {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&DEUTSCHEBANK_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*DEUTSCHEBANK_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&DEUTSCHEBANK_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__deutschebank__transformers.rs
|
use std::collections::HashMap;
use cards::CardNumber;
use common_enums::{enums, PaymentMethod};
use common_utils::{ext_traits::ValueExt, pii::Email, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankDebitData, PaymentMethodData},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
payments::{Authorize, Capture, CompleteAuthorize, PSync},
refunds::{Execute, RSync},
},
router_request_types::{
CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCaptureData, PaymentsSyncData,
ResponseId,
},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{PaymentsCancelResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, RefundsRequestData, RouterData as OtherRouterData,
},
};
pub struct DeutschebankRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for DeutschebankRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub struct DeutschebankAuthType {
pub(super) client_id: Secret<String>,
pub(super) merchant_id: Secret<String>,
pub(super) client_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for DeutschebankAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
client_id: api_key.to_owned(),
merchant_id: key1.to_owned(),
client_key: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct DeutschebankAccessTokenRequest {
pub grant_type: String,
pub client_id: Secret<String>,
pub client_secret: Secret<String>,
pub scope: String,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct DeutschebankAccessTokenResponse {
pub access_token: Secret<String>,
pub expires_in: i64,
pub expires_on: i64,
pub scope: String,
pub token_type: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, DeutschebankAccessTokenResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DeutschebankAccessTokenResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum DeutschebankSEPAApproval {
Click,
Email,
Sms,
Dynamic,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankMandatePostRequest {
approval_by: DeutschebankSEPAApproval,
email_address: Email,
iban: Secret<String>,
first_name: Secret<String>,
last_name: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum DeutschebankPaymentsRequest {
MandatePost(DeutschebankMandatePostRequest),
DirectDebit(DeutschebankDirectDebitRequest),
CreditCard(Box<DeutschebankThreeDSInitializeRequest>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequest {
means_of_payment: DeutschebankThreeDSInitializeRequestMeansOfPayment,
tds_20_data: DeutschebankThreeDSInitializeRequestTds20Data,
amount_total: DeutschebankThreeDSInitializeRequestAmountTotal,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestMeansOfPayment {
credit_card: DeutschebankThreeDSInitializeRequestCreditCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCreditCard {
number: CardNumber,
expiry_date: DeutschebankThreeDSInitializeRequestCreditCardExpiry,
code: Secret<String>,
cardholder: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCreditCardExpiry {
year: Secret<String>,
month: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestAmountTotal {
amount: MinorUnit,
currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestTds20Data {
communication_data: DeutschebankThreeDSInitializeRequestCommunicationData,
customer_data: DeutschebankThreeDSInitializeRequestCustomerData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCommunicationData {
method_notification_url: String,
cres_notification_url: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCustomerData {
billing_address: DeutschebankThreeDSInitializeRequestCustomerBillingData,
cardholder_email: Email,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCustomerBillingData {
street: Secret<String>,
postal_code: Secret<String>,
city: String,
state: Secret<String>,
country: String,
}
impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>>
for DeutschebankPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DeutschebankRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item
.router_data
.request
.mandate_id
.clone()
.and_then(|mandate_id| mandate_id.mandate_reference_id)
{
None => {
// To facilitate one-off payments via SEPA with Deutsche Bank, we are considering not storing the connector mandate ID in our system if future usage is on-session.
// We will only check for customer acceptance to make a one-off payment. we will be storing the connector mandate details only when setup future usage is off-session.
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => {
if item.router_data.request.customer_acceptance.is_some() {
let billing_address = item.router_data.get_billing_address()?;
Ok(Self::MandatePost(DeutschebankMandatePostRequest {
approval_by: DeutschebankSEPAApproval::Click,
email_address: item.router_data.request.get_email()?,
iban: Secret::from(iban.peek().replace(" ", "")),
first_name: billing_address.get_first_name()?.clone(),
last_name: billing_address.get_last_name()?.clone(),
}))
} else {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "customer_acceptance",
}
.into())
}
}
PaymentMethodData::Card(ccard) => {
if !item.router_data.clone().is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Non-ThreeDs".to_owned(),
connector: "deutschebank",
}
.into())
} else {
let billing_address = item.router_data.get_billing_address()?;
Ok(Self::CreditCard(Box::new(DeutschebankThreeDSInitializeRequest {
means_of_payment: DeutschebankThreeDSInitializeRequestMeansOfPayment {
credit_card: DeutschebankThreeDSInitializeRequestCreditCard {
number: ccard.clone().card_number,
expiry_date: DeutschebankThreeDSInitializeRequestCreditCardExpiry {
year: ccard.get_expiry_year_4_digit(),
month: ccard.card_exp_month,
},
code: ccard.card_cvc,
cardholder: item.router_data.get_billing_full_name()?,
}},
amount_total: DeutschebankThreeDSInitializeRequestAmountTotal {
amount: item.amount,
currency: item.router_data.request.currency,
},
tds_20_data: DeutschebankThreeDSInitializeRequestTds20Data {
communication_data: DeutschebankThreeDSInitializeRequestCommunicationData {
method_notification_url: item.router_data.request.get_complete_authorize_url()?,
cres_notification_url: item.router_data.request.get_complete_authorize_url()?,
},
customer_data: DeutschebankThreeDSInitializeRequestCustomerData {
billing_address: DeutschebankThreeDSInitializeRequestCustomerBillingData {
street: billing_address.get_line1()?.clone(),
postal_code: billing_address.get_zip()?.clone(),
city: billing_address.get_city()?.to_string(),
state: billing_address.get_state()?.clone(),
country: item.router_data.get_billing_country()?.to_string(),
},
cardholder_email: item.router_data.request.get_email()?,
}
}
})))
}
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("deutschebank"),
)
.into()),
}
}
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(mandate_data)) => {
let mandate_metadata: DeutschebankMandateMetadata = mandate_data
.get_mandate_metadata()
.ok_or(errors::ConnectorError::MissingConnectorMandateMetadata)?
.clone()
.parse_value("DeutschebankMandateMetadata")
.change_context(errors::ConnectorError::ParsingFailed)?;
Ok(Self::DirectDebit(DeutschebankDirectDebitRequest {
amount_total: DeutschebankAmount {
amount: item.amount,
currency: item.router_data.request.currency,
},
means_of_payment: DeutschebankMeansOfPayment {
bank_account: DeutschebankBankAccount {
account_holder: mandate_metadata.account_holder,
iban: mandate_metadata.iban,
},
},
mandate: DeutschebankMandate {
reference: mandate_metadata.reference,
signed_on: mandate_metadata.signed_on,
},
}))
}
Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_))
| Some(api_models::payments::MandateReferenceId::NetworkMandateId(_))
| Some(api_models::payments::MandateReferenceId::CardWithLimitedData) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("deutschebank"),
)
.into())
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankThreeDSInitializeResponse {
outcome: DeutschebankThreeDSInitializeResponseOutcome,
challenge_required: Option<DeutschebankThreeDSInitializeResponseChallengeRequired>,
processed: Option<DeutschebankThreeDSInitializeResponseProcessed>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankThreeDSInitializeResponseProcessed {
rc: String,
message: String,
tx_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DeutschebankThreeDSInitializeResponseOutcome {
Processed,
ChallengeRequired,
MethodRequired,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankThreeDSInitializeResponseChallengeRequired {
acs_url: String,
creq: String,
}
impl
TryFrom<
ResponseRouterData<
Authorize,
DeutschebankThreeDSInitializeResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
Authorize,
DeutschebankThreeDSInitializeResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.outcome {
DeutschebankThreeDSInitializeResponseOutcome::Processed => {
match item.response.processed {
Some(processed) => Ok(Self {
status: if is_response_success(&processed.rc) {
match item.data.request.is_auto_capture()? {
true => common_enums::AttemptStatus::Charged,
false => common_enums::AttemptStatus::Authorized,
}
} else {
common_enums::AttemptStatus::AuthenticationFailed
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
processed.tx_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(processed.tx_id.clone()),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
}),
None => {
let response_string = format!("{:?}", item.response);
Err(
errors::ConnectorError::UnexpectedResponseError(bytes::Bytes::from(
response_string,
))
.into(),
)
}
}
}
DeutschebankThreeDSInitializeResponseOutcome::ChallengeRequired => {
match item.response.challenge_required {
Some(challenge) => Ok(Self {
status: common_enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(
RedirectForm::DeutschebankThreeDSChallengeFlow {
acs_url: challenge.acs_url,
creq: challenge.creq,
},
)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
}),
None => {
let response_string = format!("{:?}", item.response);
Err(
errors::ConnectorError::UnexpectedResponseError(bytes::Bytes::from(
response_string,
))
.into(),
)
}
}
}
DeutschebankThreeDSInitializeResponseOutcome::MethodRequired => Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "METHOD_REQUIRED Flow not supported for deutschebank 3ds payments".to_owned(),
reason: Some("METHOD_REQUIRED Flow is not currently supported for deutschebank 3ds payments".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DeutschebankSEPAMandateStatus {
Created,
PendingApproval,
PendingSecondaryApproval,
PendingReview,
PendingSubmission,
Submitted,
Active,
Failed,
Discarded,
Expired,
Replaced,
}
impl From<DeutschebankSEPAMandateStatus> for common_enums::AttemptStatus {
fn from(item: DeutschebankSEPAMandateStatus) -> Self {
match item {
DeutschebankSEPAMandateStatus::Active
| DeutschebankSEPAMandateStatus::Created
| DeutschebankSEPAMandateStatus::PendingApproval
| DeutschebankSEPAMandateStatus::PendingSecondaryApproval
| DeutschebankSEPAMandateStatus::PendingReview
| DeutschebankSEPAMandateStatus::PendingSubmission
| DeutschebankSEPAMandateStatus::Submitted => Self::AuthenticationPending,
DeutschebankSEPAMandateStatus::Failed
| DeutschebankSEPAMandateStatus::Discarded
| DeutschebankSEPAMandateStatus::Expired
| DeutschebankSEPAMandateStatus::Replaced => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankMandateMetadata {
account_holder: Secret<String>,
iban: Secret<String>,
reference: Secret<String>,
signed_on: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankMandatePostResponse {
rc: String,
message: String,
mandate_id: Option<String>,
reference: Option<String>,
approval_date: Option<String>,
language: Option<String>,
approval_by: Option<DeutschebankSEPAApproval>,
state: Option<DeutschebankSEPAMandateStatus>,
}
fn get_error_response(error_code: String, error_reason: String, status_code: u16) -> ErrorResponse {
ErrorResponse {
code: error_code.to_string(),
message: error_reason.clone(),
reason: Some(error_reason),
status_code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
fn is_response_success(rc: &String) -> bool {
rc == "0"
}
impl
TryFrom<
ResponseRouterData<
Authorize,
DeutschebankMandatePostResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
Authorize,
DeutschebankMandatePostResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let signed_on = match item.response.approval_date.clone() {
Some(date) => date.chars().take(10).collect(),
None => time::OffsetDateTime::now_utc().date().to_string(),
};
let response_code = item.response.rc.clone();
let is_response_success = is_response_success(&response_code);
match (
item.response.reference.clone(),
item.response.state.clone(),
is_response_success,
) {
(Some(reference), Some(state), true) => Ok(Self {
status: common_enums::AttemptStatus::from(state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::Form {
endpoint: item.data.request.get_complete_authorize_url()?,
method: common_utils::request::Method::Get,
form_fields: HashMap::from([
("reference".to_string(), reference.clone()),
("signed_on".to_string(), signed_on.clone()),
]),
})),
mandate_reference: if item.data.request.is_mandate_payment() {
Box::new(Some(MandateReference {
connector_mandate_id: item.response.mandate_id,
payment_method_id: None,
mandate_metadata: Some(Secret::new(
serde_json::json!(DeutschebankMandateMetadata {
account_holder: item.data.get_billing_address()?.get_full_name()?,
iban: match item.data.request.payment_method_data.clone() {
PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit {
iban,
..
}) => Ok(Secret::from(iban.peek().replace(" ", ""))),
_ => Err(errors::ConnectorError::MissingRequiredField {
field_name:
"payment_method_data.bank_debit.sepa_bank_debit.iban"
}),
}?,
reference: Secret::from(reference.clone()),
signed_on,
}),
)),
connector_mandate_request_reference_id: None,
}))
} else {
Box::new(None)
},
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
}),
_ => Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
}),
}
}
}
impl
TryFrom<
ResponseRouterData<
Authorize,
DeutschebankPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
Authorize,
DeutschebankPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_code = item.response.rc.clone();
if is_response_success(&response_code) {
Ok(Self {
status: match item.data.request.is_auto_capture()? {
true => common_enums::AttemptStatus::Charged,
false => common_enums::AttemptStatus::Authorized,
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
})
}
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankAmount {
amount: MinorUnit,
currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankMeansOfPayment {
bank_account: DeutschebankBankAccount,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankBankAccount {
account_holder: Secret<String>,
iban: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankMandate {
reference: Secret<String>,
signed_on: String,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankDirectDebitRequest {
amount_total: DeutschebankAmount,
means_of_payment: DeutschebankMeansOfPayment,
mandate: DeutschebankMandate,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum DeutschebankCompleteAuthorizeRequest {
DeutschebankDirectDebitRequest(DeutschebankDirectDebitRequest),
DeutschebankThreeDSCompleteAuthorizeRequest(DeutschebankThreeDSCompleteAuthorizeRequest),
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankThreeDSCompleteAuthorizeRequest {
cres: String,
}
impl TryFrom<&DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>>
for DeutschebankCompleteAuthorizeRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if matches!(item.router_data.payment_method, PaymentMethod::Card) {
let redirect_response_payload = item
.router_data
.request
.get_redirect_response_payload()?
.expose();
let cres = redirect_response_payload
.get("cres")
.and_then(|v| v.as_str())
.map(String::from)
.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "cres" })?;
Ok(Self::DeutschebankThreeDSCompleteAuthorizeRequest(
DeutschebankThreeDSCompleteAuthorizeRequest { cres },
))
} else {
match item.router_data.request.payment_method_data.clone() {
Some(PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit {
iban, ..
})) => {
let account_holder = item.router_data.get_billing_address()?.get_full_name()?;
let redirect_response =
item.router_data.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let queries_params = redirect_response
.params
.map(|param| {
let mut queries = HashMap::<String, String>::new();
let values = param.peek().split('&').collect::<Vec<&str>>();
for value in values {
let pair = value.split('=').collect::<Vec<&str>>();
queries.insert(
pair.first()
.ok_or(
errors::ConnectorError::ResponseDeserializationFailed,
)?
.to_string(),
pair.get(1)
.ok_or(
errors::ConnectorError::ResponseDeserializationFailed,
)?
.to_string(),
);
}
Ok::<_, errors::ConnectorError>(queries)
})
.transpose()?
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let reference = Secret::from(
queries_params
.get("reference")
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "reference",
})?
.to_owned(),
);
let signed_on = queries_params
.get("signed_on")
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "signed_on",
})?
.to_owned();
Ok(Self::DeutschebankDirectDebitRequest(
DeutschebankDirectDebitRequest {
amount_total: DeutschebankAmount {
amount: item.amount,
currency: item.router_data.request.currency,
},
means_of_payment: DeutschebankMeansOfPayment {
bank_account: DeutschebankBankAccount {
account_holder,
iban: Secret::from(iban.peek().replace(" ", "")),
},
},
mandate: {
DeutschebankMandate {
reference,
signed_on,
}
},
},
))
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("deutschebank"),
)
.into()),
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum DeutschebankTXAction {
Authorization,
Capture,
Credit,
Preauthorization,
Refund,
Reversal,
RiskCheck,
#[serde(rename = "verify-mop")]
VerifyMop,
Payment,
AccountInformation,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub struct BankAccount {
account_holder: Option<Secret<String>>,
bank_name: Option<Secret<String>>,
bic: Option<Secret<String>>,
iban: Option<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub struct TransactionBankAccountInfo {
bank_account: Option<BankAccount>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub struct DeutschebankTransactionInfo {
back_state: Option<String>,
ip_address: Option<Secret<String>>,
#[serde(rename = "type")]
pm_type: Option<String>,
transaction_bankaccount_info: Option<TransactionBankAccountInfo>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub struct DeutschebankPaymentsResponse {
rc: String,
message: String,
timestamp: String,
back_ext_id: Option<String>,
back_rc: Option<String>,
event_id: Option<String>,
kind: Option<String>,
tx_action: Option<DeutschebankTXAction>,
tx_id: String,
amount_total: Option<DeutschebankAmount>,
transaction_info: Option<DeutschebankTransactionInfo>,
}
impl
TryFrom<
ResponseRouterData<
CompleteAuthorize,
DeutschebankPaymentsResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
CompleteAuthorize,
DeutschebankPaymentsResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_code = item.response.rc.clone();
if is_response_success(&response_code) {
Ok(Self {
status: match item.data.request.is_auto_capture()? {
true => common_enums::AttemptStatus::Charged,
false => common_enums::AttemptStatus::Authorized,
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
})
}
}
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum DeutschebankTransactionKind {
Directdebit,
#[serde(rename = "CREDITCARD_3DS20")]
Creditcard3ds20,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankCaptureRequest {
changed_amount: MinorUnit,
kind: DeutschebankTransactionKind,
}
impl TryFrom<&DeutschebankRouterData<&PaymentsCaptureRouterData>> for DeutschebankCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DeutschebankRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
if matches!(item.router_data.payment_method, PaymentMethod::BankDebit) {
Ok(Self {
changed_amount: item.amount,
kind: DeutschebankTransactionKind::Directdebit,
})
} else if item.router_data.is_three_ds()
&& matches!(item.router_data.payment_method, PaymentMethod::Card)
{
Ok(Self {
changed_amount: item.amount,
kind: DeutschebankTransactionKind::Creditcard3ds20,
})
} else {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("deutschebank"),
)
.into())
}
}
}
impl
TryFrom<
ResponseRouterData<
Capture,
DeutschebankPaymentsResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
> for RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
Capture,
DeutschebankPaymentsResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_code = item.response.rc.clone();
if is_response_success(&response_code) {
Ok(Self {
status: common_enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
})
}
}
}
impl
TryFrom<
ResponseRouterData<
PSync,
DeutschebankPaymentsResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
> for RouterData<PSync, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
PSync,
DeutschebankPaymentsResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_code = item.response.rc.clone();
let status = if is_response_success(&response_code) {
item.response
.tx_action
.and_then(|tx_action| match tx_action {
DeutschebankTXAction::Preauthorization => {
Some(common_enums::AttemptStatus::Authorized)
}
DeutschebankTXAction::Authorization | DeutschebankTXAction::Capture => {
Some(common_enums::AttemptStatus::Charged)
}
DeutschebankTXAction::Credit
| DeutschebankTXAction::Refund
| DeutschebankTXAction::Reversal
| DeutschebankTXAction::RiskCheck
| DeutschebankTXAction::VerifyMop
| DeutschebankTXAction::Payment
| DeutschebankTXAction::AccountInformation => None,
})
} else {
Some(common_enums::AttemptStatus::Failure)
};
match status {
Some(common_enums::AttemptStatus::Failure) => Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
}),
Some(status) => Ok(Self {
status,
..item.data
}),
None => Ok(Self { ..item.data }),
}
}
}
#[derive(Debug, Serialize)]
pub struct DeutschebankReversalRequest {
kind: DeutschebankTransactionKind,
}
impl TryFrom<&PaymentsCancelRouterData> for DeutschebankReversalRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
if matches!(item.payment_method, PaymentMethod::BankDebit) {
Ok(Self {
kind: DeutschebankTransactionKind::Directdebit,
})
} else if item.is_three_ds() && matches!(item.payment_method, PaymentMethod::Card) {
Ok(Self {
kind: DeutschebankTransactionKind::Creditcard3ds20,
})
} else {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("deutschebank"),
)
.into())
}
}
}
impl TryFrom<PaymentsCancelResponseRouterData<DeutschebankPaymentsResponse>>
for PaymentsCancelRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<DeutschebankPaymentsResponse>,
) -> Result<Self, Self::Error> {
let response_code = item.response.rc.clone();
if is_response_success(&response_code) {
Ok(Self {
status: common_enums::AttemptStatus::Voided,
..item.data
})
} else {
Ok(Self {
status: common_enums::AttemptStatus::VoidFailed,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
})
}
}
}
#[derive(Debug, Serialize)]
pub struct DeutschebankRefundRequest {
changed_amount: MinorUnit,
kind: DeutschebankTransactionKind,
}
impl<F> TryFrom<&DeutschebankRouterData<&RefundsRouterData<F>>> for DeutschebankRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &DeutschebankRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
if matches!(item.router_data.payment_method, PaymentMethod::BankDebit) {
Ok(Self {
changed_amount: item.amount,
kind: DeutschebankTransactionKind::Directdebit,
})
} else if item.router_data.is_three_ds()
&& matches!(item.router_data.payment_method, PaymentMethod::Card)
{
Ok(Self {
changed_amount: item.amount,
kind: DeutschebankTransactionKind::Creditcard3ds20,
})
} else {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("deutschebank"),
)
.into())
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, DeutschebankPaymentsResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, DeutschebankPaymentsResponse>,
) -> Result<Self, Self::Error> {
let response_code = item.response.rc.clone();
if is_response_success(&response_code) {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.tx_id,
refund_status: enums::RefundStatus::Success,
}),
..item.data
})
} else {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
})
}
}
}
impl TryFrom<RefundsResponseRouterData<RSync, DeutschebankPaymentsResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, DeutschebankPaymentsResponse>,
) -> Result<Self, Self::Error> {
let response_code = item.response.rc.clone();
let status = if is_response_success(&response_code) {
item.response
.tx_action
.and_then(|tx_action| match tx_action {
DeutschebankTXAction::Credit | DeutschebankTXAction::Refund => {
Some(enums::RefundStatus::Success)
}
DeutschebankTXAction::Preauthorization
| DeutschebankTXAction::Authorization
| DeutschebankTXAction::Capture
| DeutschebankTXAction::Reversal
| DeutschebankTXAction::RiskCheck
| DeutschebankTXAction::VerifyMop
| DeutschebankTXAction::Payment
| DeutschebankTXAction::AccountInformation => None,
})
} else {
Some(enums::RefundStatus::Failure)
};
match status {
Some(enums::RefundStatus::Failure) => Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
}),
Some(refund_status) => Ok(Self {
response: Ok(RefundsResponseData {
refund_status,
connector_refund_id: item.data.request.get_connector_refund_id()?,
}),
..item.data
}),
None => Ok(Self { ..item.data }),
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct PaymentsErrorResponse {
pub rc: String,
pub message: String,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct AccessTokenErrorResponse {
pub cause: String,
pub description: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum DeutschebankError {
PaymentsErrorResponse(PaymentsErrorResponse),
AccessTokenErrorResponse(AccessTokenErrorResponse),
}
|
crates__hyperswitch_connectors__src__connectors__digitalvirgo.rs
|
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{
Authorize, Capture, CompleteAuthorize, PSync, PaymentMethodToken, Session,
SetupMandate, Void,
},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{Mask, PeekInterface};
use transformers as digitalvirgo;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Digitalvirgo {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Digitalvirgo {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Digitalvirgo {}
impl api::PaymentSession for Digitalvirgo {}
impl api::ConnectorAccessToken for Digitalvirgo {}
impl api::MandateSetup for Digitalvirgo {}
impl api::PaymentAuthorize for Digitalvirgo {}
impl api::PaymentSync for Digitalvirgo {}
impl api::PaymentCapture for Digitalvirgo {}
impl api::PaymentVoid for Digitalvirgo {}
impl api::Refund for Digitalvirgo {}
impl api::RefundExecute for Digitalvirgo {}
impl api::RefundSync for Digitalvirgo {}
impl api::PaymentToken for Digitalvirgo {}
impl api::PaymentsCompleteAuthorize for Digitalvirgo {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Digitalvirgo
{
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Digitalvirgo
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Digitalvirgo {
fn id(&self) -> &'static str {
"digitalvirgo"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.digitalvirgo.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = digitalvirgo::DigitalvirgoAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let encoded_api_key = consts::BASE64_ENGINE.encode(format!(
"{}:{}",
auth.username.peek(),
auth.password.peek()
));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Basic {encoded_api_key}").into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: digitalvirgo::DigitalvirgoErrorResponse = res
.response
.parse_struct("DigitalvirgoErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_code = response.cause.or(response.operation_error);
Ok(ErrorResponse {
status_code: res.status_code,
code: error_code
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_code
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason: response.description,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Digitalvirgo {
fn validate_psync_reference_id(
&self,
_data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
// in case we dont have transaction id, we can make psync using attempt id
Ok(())
}
}
impl ConnectorRedirectResponse for Digitalvirgo {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
action: enums::PaymentAction,
) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> {
match action {
enums::PaymentAction::PSync
| enums::PaymentAction::CompleteAuthorize
| enums::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
Ok(enums::CallConnectorAction::Trigger)
}
}
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Digitalvirgo {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Digitalvirgo {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Digitalvirgo
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Digitalvirgo {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/payment", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let surcharge_amount = req.request.surcharge_details.clone().and_then(|surcharge| {
utils::convert_amount(
self.amount_converter,
surcharge.surcharge_amount,
req.request.currency,
)
.ok()
});
let connector_router_data =
digitalvirgo::DigitalvirgoRouterData::from((amount, surcharge_amount, req));
let connector_req =
digitalvirgo::DigitalvirgoPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: digitalvirgo::DigitalvirgoPaymentsResponse = res
.response
.parse_struct("Digitalvirgo PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Digitalvirgo {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"/payment/state?partnerTransactionId=",
req.connector_request_reference_id
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response_details: Vec<digitalvirgo::DigitalvirgoPaymentSyncResponse> = res
.response
.parse_struct("digitalvirgo PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let response = response_details
.first()
.cloned()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Digitalvirgo
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"/payment/confirmation"
))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = digitalvirgo::DigitalvirgoConfirmRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: digitalvirgo::DigitalvirgoPaymentsResponse = res
.response
.parse_struct("DigitalvirgoPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Digitalvirgo {
fn build_request(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "capture".to_string(),
connector: "digitalvirgo".to_string(),
}
.into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Digitalvirgo {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Digitalvirgo {
fn build_request(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "refund".to_string(),
connector: "digitalvirgo".to_string(),
}
.into())
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Digitalvirgo {
fn build_request(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "refund_sync".to_string(),
connector: "digitalvirgo".to_string(),
}
.into())
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Digitalvirgo {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static DIGITALVIRGO_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::SequentialAutomatic,
];
let mut digitalvirgo_supported_payment_methods = SupportedPaymentMethods::new();
digitalvirgo_supported_payment_methods.add(
enums::PaymentMethod::MobilePayment,
enums::PaymentMethodType::DirectCarrierBilling,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
digitalvirgo_supported_payment_methods
});
static DIGITALVIRGO_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Digital Virgo",
description:
"Digital Virgo is an alternative payment provider specializing in carrier billing and mobile payments ",
connector_type: enums::HyperswitchConnectorCategory::AlternativePaymentMethod,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static DIGITALVIRGO_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Digitalvirgo {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&DIGITALVIRGO_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*DIGITALVIRGO_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&DIGITALVIRGO_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__dlocal.rs
|
pub mod transformers;
use api_models::webhooks::IncomingWebhookEvent;
use common_enums::enums;
use common_utils::{
crypto::{self, SignMessage},
date_time,
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hex::encode;
use hyperswitch_domain_models::{
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use lazy_static::lazy_static;
use masking::{Mask, Maskable, PeekInterface};
use transformers as dlocal;
use crate::{
connectors::dlocal::transformers::DlocalRouterData, constants::headers,
types::ResponseRouterData, utils::convert_amount,
};
#[derive(Clone)]
pub struct Dlocal {
amount_convertor: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Dlocal {
pub fn new() -> &'static Self {
&Self {
amount_convertor: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Dlocal {}
impl api::PaymentToken for Dlocal {}
impl api::PaymentSession for Dlocal {}
impl api::ConnectorAccessToken for Dlocal {}
impl api::MandateSetup for Dlocal {}
impl api::PaymentAuthorize for Dlocal {}
impl api::PaymentSync for Dlocal {}
impl api::PaymentCapture for Dlocal {}
impl api::PaymentVoid for Dlocal {}
impl api::Refund for Dlocal {}
impl api::RefundExecute for Dlocal {}
impl api::RefundSync for Dlocal {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Dlocal
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let dlocal_req = self.get_request_body(req, connectors)?;
let date = date_time::date_as_yyyymmddthhmmssmmmz()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let auth = dlocal::DlocalAuthType::try_from(&req.connector_auth_type)?;
let sign_req: String = if dlocal_req.get_inner_value().peek() == r#""{}""# {
format!("{}{}", auth.x_login.peek(), date)
} else {
format!(
"{}{}{}",
auth.x_login.peek(),
date,
dlocal_req.get_inner_value().peek()
)
};
let authz = crypto::HmacSha256::sign_message(
&crypto::HmacSha256,
auth.secret.peek().as_bytes(),
sign_req.as_bytes(),
)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to sign the message")?;
let auth_string: String = format!("V2-HMAC-SHA256, Signature: {}", encode(authz));
let headers = vec![
(
headers::AUTHORIZATION.to_string(),
auth_string.into_masked(),
),
(headers::X_LOGIN.to_string(), auth.x_login.into_masked()),
(
headers::X_TRANS_KEY.to_string(),
auth.x_trans_key.into_masked(),
),
(headers::X_VERSION.to_string(), "2.1".to_string().into()),
(headers::X_DATE.to_string(), date.into()),
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
];
Ok(headers)
}
}
impl ConnectorCommon for Dlocal {
fn id(&self) -> &'static str {
"dlocal"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.dlocal.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: dlocal::DlocalErrorResponse = res
.response
.parse_struct("Dlocal ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i: &mut ConnectorEvent| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code.to_string(),
message: response.message.clone(),
reason: Some(response.message),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Dlocal {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Dlocal
{
// Not Implemented (R)
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Dlocal {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Dlocal {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Dlocal {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Dlocal".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Dlocal {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}secure_payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = DlocalRouterData::try_from((amount, req))?;
let connector_req = dlocal::DlocalPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
router_env::logger::debug!(dlocal_payments_authorize_response=?res);
let response: dlocal::DlocalPaymentsResponse = res
.response
.parse_struct("Dlocal PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Dlocal {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}payments/{}/status",
self.base_url(connectors),
req.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
router_env::logger::debug!(dlocal_payment_sync_response=?res);
let response: dlocal::DlocalPaymentsResponse = res
.response
.parse_struct("Dlocal PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Dlocal {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = DlocalRouterData::try_from((amount, req))?;
let connector_req = dlocal::DlocalPaymentsCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
router_env::logger::debug!(dlocal_payments_capture_response=?res);
let response: dlocal::DlocalPaymentsResponse = res
.response
.parse_struct("Dlocal PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Dlocal {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}payments/{}/cancel",
self.base_url(connectors),
req.request.connector_transaction_id.clone(),
))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
router_env::logger::debug!(dlocal_payments_cancel_response=?res);
let response: dlocal::DlocalPaymentsResponse = res
.response
.parse_struct("Dlocal PaymentsCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Dlocal {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}refunds", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = DlocalRouterData::try_from((amount, req))?;
let connector_req = dlocal::DlocalRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
router_env::logger::debug!(dlocal_refund_response=?res);
let response: dlocal::RefundResponse =
res.response
.parse_struct("Dlocal RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Dlocal {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let refund_id = req.request.connector_refund_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_refund_id",
},
)?;
Ok(format!(
"{}refunds/{refund_id}/status",
self.base_url(connectors),
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
router_env::logger::debug!(dlocal_refund_sync_response=?res);
let response: dlocal::RefundResponse = res
.response
.parse_struct("Dlocal RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Dlocal {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
Ok(IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
lazy_static! {
static ref DLOCAL_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_capture_methods2 = vec![
enums::CaptureMethod::Automatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::CartesBancaires,
];
let mut dlocal_supported_payment_methods = SupportedPaymentMethods::new();
dlocal_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
dlocal_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
dlocal_supported_payment_methods.add(
enums::PaymentMethod::Voucher,
enums::PaymentMethodType::Oxxo,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods2.clone(),
specific_features: None,
},
);
dlocal_supported_payment_methods
};
static ref DLOCAL_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "DLOCAL",
description:
"Dlocal is a cross-border payment processor enabling businesses to accept and send payments in emerging markets worldwide.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static ref DLOCAL_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
}
impl ConnectorSpecifications for Dlocal {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*DLOCAL_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*DLOCAL_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*DLOCAL_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__dwolla.rs
|
pub mod transformers;
use std::sync::LazyLock;
use base64::engine::Engine;
use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE,
crypto,
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ErrorResponse, PaymentMethodToken as PMT, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
CreateConnectorCustomer,
},
router_request_types::{
AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, ResponseId, SetupMandateRequestData,
},
router_response_types::{
ConnectorCustomerResponseData, ConnectorInfo, PaymentMethodDetails, PaymentsResponseData,
RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsSyncRouterData,
RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, RefreshTokenType, Response, TokenizationType},
webhooks,
};
use masking::{ExposeInterface, Mask, Secret};
use ring::hmac;
use transformers as dwolla;
use transformers::extract_token_from_body;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{convert_amount, get_http_header, RefundsRequestData, RouterData as RD},
};
#[derive(Clone)]
pub struct Dwolla {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Dwolla {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl api::ConnectorCustomer for Dwolla {}
impl api::Payment for Dwolla {}
impl api::PaymentSession for Dwolla {}
impl api::ConnectorAccessToken for Dwolla {}
impl api::MandateSetup for Dwolla {}
impl api::PaymentAuthorize for Dwolla {}
impl api::PaymentSync for Dwolla {}
impl api::PaymentCapture for Dwolla {}
impl api::PaymentVoid for Dwolla {}
impl api::Refund for Dwolla {}
impl api::RefundExecute for Dwolla {}
impl api::RefundSync for Dwolla {}
impl api::PaymentToken for Dwolla {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Dwolla
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let access_token = req
.access_token
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let header = vec![
(
headers::CONTENT_TYPE.to_string(),
self.common_get_content_type().to_string().into(),
),
(
headers::ACCEPT.to_string(),
self.common_get_content_type().to_string().into(),
),
(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", access_token.token.expose()).into_masked(),
),
(
headers::IDEMPOTENCY_KEY.to_string(),
uuid::Uuid::new_v4().to_string().into(),
),
];
Ok(header)
}
}
impl ConnectorCommon for Dwolla {
fn id(&self) -> &'static str {
"dwolla"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/vnd.dwolla.v1.hal+json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.dwolla.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: dwolla::DwollaErrorResponse = res
.response
.parse_struct("DwollaErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code,
message: response.message,
reason: response
.embedded
.as_ref()
.and_then(|errors_vec| errors_vec.errors.first())
.and_then(|details| details.message.clone()),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Dwolla {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Dwolla {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Dwolla {
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/token", self.base_url(connectors)))
}
fn get_headers(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = dwolla::DwollaAuthType::try_from(&req.connector_auth_type)?;
let mut headers = vec![(
headers::CONTENT_TYPE.to_string(),
"application/x-www-form-urlencoded".to_string().into(),
)];
let auth_str = format!(
"{}:{}",
auth.client_id.expose(),
auth.client_secret.expose()
);
let encoded = BASE64_ENGINE.encode(auth_str);
let auth_header_value = format!("Basic {encoded}");
headers.push((
headers::AUTHORIZATION.to_string(),
auth_header_value.into_masked(),
));
Ok(headers)
}
fn build_request(
&self,
req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let headers = self.get_headers(req, connectors)?;
let connector_req = dwolla::DwollaAccessTokenRequest {
grant_type: "client_credentials".to_string(),
};
let body = RequestContent::FormUrlEncoded(Box::new(connector_req));
let req = Some(
RequestBuilder::new()
.method(Method::Post)
.headers(headers)
.url(&RefreshTokenType::get_url(self, req, connectors)?)
.set_body(body)
.build(),
);
Ok(req)
}
fn handle_response(
&self,
data: &RefreshTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
let response: dwolla::DwollaAccessTokenResponse = res
.response
.parse_struct("Dwolla DwollaAccessTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>
for Dwolla
{
fn get_url(
&self,
_req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/customers", self.base_url(connectors)))
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_headers(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_request_body(
&self,
req: &ConnectorCustomerRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = dwolla::DwollaCustomerRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::ConnectorCustomerType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::ConnectorCustomerType::get_headers(
self, req, connectors,
)?)
.set_body(types::ConnectorCustomerType::get_request_body(
self, req, connectors,
)?)
.build(),
);
Ok(request)
}
fn handle_response(
&self,
data: &ConnectorCustomerRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<ConnectorCustomerRouterData, errors::ConnectorError> {
let headers = res
.headers
.as_ref()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let location = get_http_header("Location", headers)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let connector_customer_id = location
.split('/')
.next_back()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?
.to_string();
let response = serde_json::json!({"connector_customer_id": connector_customer_id.clone()});
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(RouterData {
connector_customer: Some(connector_customer_id.clone()),
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(connector_customer_id),
)),
..data.clone()
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Dwolla
{
fn get_headers(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let customer_id = req.get_connector_customer_id()?;
Ok(format!(
"{}/customers/{}/funding-sources",
self.base_url(connectors),
customer_id
))
}
fn get_request_body(
&self,
req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = dwolla::DwollaFundingSourceRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(TokenizationType::get_headers(self, req, connectors)?)
.set_body(TokenizationType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &TokenizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<TokenizationRouterData, errors::ConnectorError> {
let token = res
.headers
.as_ref()
.and_then(|headers| get_http_header("Location", headers).ok())
.and_then(|location| location.rsplit('/').next().map(|s| s.to_string()))
.ok_or_else(|| report!(errors::ConnectorError::ResponseHandlingFailed))?;
let response = serde_json::json!({ "payment_token": token });
if let Some(builder) = event_builder {
builder.set_response_body(&response);
}
router_env::logger::info!(connector_response=?response);
Ok(RouterData {
payment_method_token: Some(PMT::Token(token.clone().into())),
response: Ok(PaymentsResponseData::TokenizationResponse { token }),
..data.clone()
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
if let Ok(body) = std::str::from_utf8(&res.response) {
if res.status_code == 400 && body.contains("Duplicate") {
let token = extract_token_from_body(&res.response);
let metadata = Some(Secret::new(
serde_json::json!({ "payment_method_token": token? }),
));
let response: dwolla::DwollaErrorResponse = res
.response
.parse_struct("DwollaErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
return Ok(ErrorResponse {
status_code: res.status_code,
code: response.code,
message: response.message,
reason: response
.embedded
.as_ref()
.and_then(|errors_vec| errors_vec.errors.first())
.and_then(|details| details.message.clone()),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: metadata,
});
}
}
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Dwolla {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Dwolla {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/transfers", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data =
dwolla::DwollaRouterData::try_from((amount, req, self.base_url(connectors)))?;
let connector_req = dwolla::DwollaPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let headers = res
.headers
.as_ref()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let location = get_http_header("Location", headers)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let payment_id = location
.split('/')
.next_back()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?
.to_string();
let response = serde_json::json!({"payment_id : ": payment_id.clone()});
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let connector_metadata = data
.payment_method_token
.as_ref()
.and_then(|token| match token {
PMT::Token(t) => Some(serde_json::json!({ "payment_token": t.clone().expose() })),
_ => None,
});
Ok(RouterData {
payment_method_token: data.payment_method_token.clone(),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(payment_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(payment_id.clone()),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
amount_captured: Some(data.request.amount),
..data.clone()
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Dwolla {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/transfers/{}",
self.base_url(connectors),
connector_payment_id.clone()
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: dwolla::DwollaPSyncResponse = res
.response
.parse_struct("dwolla DwollaPSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Dwolla {
//Not implemented for Dwolla
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Dwolla {
//Not implemented for Dwolla
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Dwolla {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/transfers", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_in_minor_unit = MinorUnit::new(req.request.refund_amount);
let amount = convert_amount(
self.amount_converter,
amount_in_minor_unit,
req.request.currency,
)?;
let connector_router_data =
dwolla::DwollaRouterData::try_from((amount, req, self.base_url(connectors)))?;
let connector_req = dwolla::DwollaRefundsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let headers = res
.headers
.as_ref()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let location = get_http_header("Location", headers)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let refund_id = location
.split('/')
.next_back()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?
.to_string();
let response = serde_json::json!({"refund_id : ": refund_id.clone()});
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(RouterData {
response: Ok(RefundsResponseData {
connector_refund_id: refund_id.clone(),
refund_status: enums::RefundStatus::Pending,
}),
..data.clone()
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Dwolla {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}/transfers/{}",
self.base_url(connectors),
connector_refund_id.clone()
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: dwolla::DwollaRSyncResponse = res
.response
.parse_struct("dwolla DwollaRSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Dwolla {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let sig = request
.headers
.get("X-Request-Signature-SHA-256")
.and_then(|hv| hv.to_str().ok())
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)?;
hex::decode(sig).map_err(|_| errors::ConnectorError::WebhookSignatureNotFound.into())
}
async fn verify_webhook_source(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_name: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_name,
connector_webhook_details,
)
.await?;
let signature = self
.get_webhook_source_verification_signature(request, &connector_webhook_secrets)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
let secret_bytes = connector_webhook_secrets.secret.as_ref();
let key = hmac::Key::new(hmac::HMAC_SHA256, secret_bytes);
let verify = hmac::verify(&key, request.body, &signature)
.map(|_| true)
.map_err(|_| errors::ConnectorError::WebhookSourceVerificationFailed)?;
Ok(verify)
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let details: dwolla::DwollaWebhookDetails = request
.body
.parse_struct("DwollaWebhookDetails")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
if let Some(correlation_id) = &details.correlation_id {
if correlation_id.starts_with("refund_") {
Ok(api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(
details.resource_id.clone(),
),
))
} else if correlation_id.starts_with("payment_") {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
details.resource_id.clone(),
),
))
} else {
Err(report!(errors::ConnectorError::WebhookReferenceIdNotFound))
}
} else {
Err(report!(errors::ConnectorError::WebhookReferenceIdNotFound))
}
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let details: dwolla::DwollaWebhookDetails = request
.body
.parse_struct("DwollaWebhookDetails")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
let incoming = api_models::webhooks::IncomingWebhookEvent::try_from(details)?;
Ok(incoming)
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let details: dwolla::DwollaWebhookDetails = request
.body
.parse_struct("DwollaWebhookDetails")
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(details))
}
}
static DWOLLA_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::SequentialAutomatic,
];
let mut dwolla_supported_payment_methods = SupportedPaymentMethods::new();
dwolla_supported_payment_methods.add(
enums::PaymentMethod::BankDebit,
enums::PaymentMethodType::Ach,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
dwolla_supported_payment_methods
});
static DWOLLA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Dwolla",
description: "Dwolla is a multinational financial technology company offering financial services and software as a service (SaaS)",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static DWOLLA_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] =
[enums::EventClass::Payments, enums::EventClass::Refunds];
impl ConnectorSpecifications for Dwolla {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&DWOLLA_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*DWOLLA_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&DWOLLA_SUPPORTED_WEBHOOK_FLOWS)
}
fn should_call_connector_customer(
&self,
_payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> bool {
true
}
}
|
crates__hyperswitch_connectors__src__connectors__dwolla__transformers.rs
|
use common_enums::{enums, AttemptStatus};
use common_utils::{errors::CustomResult, types::StringMajorUnit};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::{BankDebitData, PaymentMethodData},
router_data::{AccessToken, ConnectorAuthType, PaymentMethodToken, RouterData},
router_flow_types::refunds::RSync,
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, CustomerData, RouterData as _},
};
pub struct DwollaAuthType {
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for DwollaAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
client_id: api_key.to_owned(),
client_secret: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct DwollaAccessTokenRequest {
pub grant_type: String,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct DwollaAccessTokenResponse {
access_token: Secret<String>,
expires_in: i64,
token_type: String,
}
pub fn extract_token_from_body(body: &[u8]) -> CustomResult<String, errors::ConnectorError> {
let parsed: serde_json::Value = serde_json::from_slice(body)
.map_err(|_| report!(errors::ConnectorError::ResponseDeserializationFailed))?;
parsed
.get("_links")
.and_then(|links| links.get("about"))
.and_then(|about| about.get("href"))
.and_then(|href| href.as_str())
.and_then(|url| url.rsplit('/').next())
.map(|id| id.to_string())
.ok_or_else(|| report!(errors::ConnectorError::ResponseHandlingFailed))
}
fn map_topic_to_status(topic: &str) -> DwollaPaymentStatus {
match topic {
"customer_transfer_created" | "customer_bank_transfer_created" => {
DwollaPaymentStatus::Pending
}
"customer_transfer_completed" | "customer_bank_transfer_completed" => {
DwollaPaymentStatus::Succeeded
}
"customer_transfer_failed" | "customer_bank_transfer_failed" => DwollaPaymentStatus::Failed,
_ => DwollaPaymentStatus::Pending,
}
}
impl<F, T> TryFrom<ResponseRouterData<F, DwollaAccessTokenResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DwollaAccessTokenResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Debug)]
pub struct DwollaRouterData<'a, T> {
pub amount: StringMajorUnit,
pub router_data: T,
pub base_url: &'a str,
}
impl<'a, T> TryFrom<(StringMajorUnit, T, &'a str)> for DwollaRouterData<'a, T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(amount, router_data, base_url): (StringMajorUnit, T, &'a str),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data,
base_url,
})
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DwollaCustomerRequest {
first_name: Secret<String>,
last_name: Secret<String>,
email: common_utils::pii::Email,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DwollaCustomerResponse {}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DwollaFundingSourceResponse {}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DwollaFundingSourceRequest {
routing_number: Secret<String>,
account_number: Secret<String>,
#[serde(rename = "type")]
account_type: common_enums::BankType,
name: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DwollaPaymentsRequest {
#[serde(rename = "_links")]
links: DwollaPaymentLinks,
amount: DwollaAmount,
correlation_id: String,
}
#[derive(Default, Debug, Serialize, PartialEq, Deserialize, Clone)]
pub struct DwollaPaymentLinks {
source: DwollaRequestLink,
destination: DwollaRequestLink,
}
#[derive(Default, Debug, Serialize, PartialEq, Deserialize, Clone)]
pub struct DwollaRequestLink {
href: String,
}
#[derive(Debug, Serialize, PartialEq, Deserialize, Clone)]
pub struct DwollaAmount {
pub currency: common_enums::Currency,
pub value: StringMajorUnit,
}
#[derive(Debug, Serialize, PartialEq, Deserialize, Clone)]
#[serde(untagged)]
pub enum DwollaPSyncResponse {
Payment(DwollaPaymentSyncResponse),
Webhook(DwollaWebhookDetails),
}
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct DwollaPaymentSyncResponse {
pub id: String,
pub status: DwollaPaymentStatus,
pub amount: DwollaAmount,
}
#[derive(Debug, Serialize, PartialEq, Deserialize, Clone)]
#[serde(untagged)]
pub enum DwollaRSyncResponse {
Payment(DwollaRefundSyncResponse),
Webhook(DwollaWebhookDetails),
}
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct DwollaRefundSyncResponse {
id: String,
status: DwollaPaymentStatus,
amount: DwollaAmount,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct DwollaMetaData {
pub merchant_funding_source: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DwollaRefundsRequest {
#[serde(rename = "_links")]
links: DwollaPaymentLinks,
amount: DwollaAmount,
correlation_id: String,
}
impl TryFrom<&types::ConnectorCustomerRouterData> for DwollaCustomerRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> {
Ok(Self {
first_name: item.get_billing_first_name()?,
last_name: item.get_billing_last_name()?,
email: item
.request
.get_email()
.or_else(|_| item.get_billing_email())?,
})
}
}
impl TryFrom<&types::TokenizationRouterData> for DwollaFundingSourceRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::BankDebit(BankDebitData::AchBankDebit {
ref routing_number,
ref account_number,
ref bank_type,
ref bank_account_holder_name,
..
}) => {
let account_type =
(*bank_type).ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "bank_type",
})?;
let name = bank_account_holder_name.clone().ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "bank_account_holder_name",
}
})?;
let request = Self {
routing_number: routing_number.clone(),
account_number: account_number.clone(),
account_type,
name,
};
Ok(request)
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("dwolla"),
))?,
}
}
}
impl<'a> TryFrom<&DwollaRouterData<'a, &PaymentsAuthorizeRouterData>> for DwollaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DwollaRouterData<'a, &PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let source_funding = match item.router_data.get_payment_method_token().ok() {
Some(PaymentMethodToken::Token(pm_token)) => pm_token,
_ => {
return Err(report!(errors::ConnectorError::MissingRequiredField {
field_name: "payment_method_token",
}))
}
};
let metadata = utils::to_connector_meta_from_secret::<DwollaMetaData>(
item.router_data.connector_meta_data.clone(),
)
.change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata" })?;
let source_url = format!(
"{}/funding-sources/{}",
item.base_url,
source_funding.expose()
);
let destination_url = format!(
"{}/funding-sources/{}",
item.base_url,
metadata.merchant_funding_source.expose()
);
let request = Self {
links: DwollaPaymentLinks {
source: DwollaRequestLink { href: source_url },
destination: DwollaRequestLink {
href: destination_url,
},
},
amount: DwollaAmount {
currency: item.router_data.request.currency,
value: item.amount.to_owned(),
},
correlation_id: format!(
"payment_{}",
item.router_data.connector_request_reference_id
),
};
Ok(request)
}
}
impl<F, T> TryFrom<ResponseRouterData<F, DwollaPSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DwollaPSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let connector_metadata =
item.data
.payment_method_token
.as_ref()
.and_then(|token| match token {
PaymentMethodToken::Token(t) => {
Some(serde_json::json!({ "payment_token": t.clone().expose() }))
}
_ => None,
});
match item.response {
DwollaPSyncResponse::Payment(payment_response) => {
let payment_id = payment_response.id.clone();
let status = payment_response.status;
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(payment_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(payment_id.clone()),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
status: AttemptStatus::from(status),
..item.data
})
}
DwollaPSyncResponse::Webhook(webhook_response) => {
let payment_id = webhook_response.resource_id.clone();
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(payment_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(payment_id.clone()),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
status: AttemptStatus::from(map_topic_to_status(
webhook_response.topic.as_str(),
)),
..item.data
})
}
}
}
}
impl<'a, F> TryFrom<&DwollaRouterData<'a, &RefundsRouterData<F>>> for DwollaRefundsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &DwollaRouterData<'a, &RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let destination_funding = item
.router_data
.request
.connector_metadata
.as_ref()
.and_then(|meta| {
meta.get("payment_token")
.and_then(|token| token.as_str().map(|s| s.to_string()))
})
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "payment_token",
})?;
let metadata = utils::to_connector_meta_from_secret::<DwollaMetaData>(
item.router_data.connector_meta_data.clone(),
)
.change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata" })?;
let source_url = format!(
"{}/funding-sources/{}",
item.base_url,
metadata.merchant_funding_source.expose()
);
let destination_url = format!("{}/funding-sources/{}", item.base_url, destination_funding);
let request = Self {
links: DwollaPaymentLinks {
source: DwollaRequestLink { href: source_url },
destination: DwollaRequestLink {
href: destination_url,
},
},
amount: DwollaAmount {
currency: item.router_data.request.currency,
value: item.amount.to_owned(),
},
correlation_id: format!("refund_{}", item.router_data.connector_request_reference_id),
};
Ok(request)
}
}
impl TryFrom<RefundsResponseRouterData<RSync, DwollaRSyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, DwollaRSyncResponse>,
) -> Result<Self, Self::Error> {
match item.response {
DwollaRSyncResponse::Payment(refund_response) => {
let refund_id = refund_response.id.clone();
let status = refund_response.status;
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: refund_id,
refund_status: enums::RefundStatus::from(status),
}),
..item.data
})
}
DwollaRSyncResponse::Webhook(webhook_response) => {
let refund_id = webhook_response.resource_id.clone();
let status = map_topic_to_status(webhook_response.topic.as_str());
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: refund_id,
refund_status: enums::RefundStatus::from(status),
}),
..item.data
})
}
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum DwollaPaymentStatus {
Succeeded,
Failed,
Pending,
#[default]
Processing,
Processed,
}
impl From<DwollaPaymentStatus> for AttemptStatus {
fn from(item: DwollaPaymentStatus) -> Self {
match item {
DwollaPaymentStatus::Succeeded => Self::Charged,
DwollaPaymentStatus::Processed => Self::Charged,
DwollaPaymentStatus::Failed => Self::Failure,
DwollaPaymentStatus::Processing => Self::Pending,
DwollaPaymentStatus::Pending => Self::Pending,
}
}
}
impl From<DwollaPaymentStatus> for enums::RefundStatus {
fn from(item: DwollaPaymentStatus) -> Self {
match item {
DwollaPaymentStatus::Succeeded => Self::Success,
DwollaPaymentStatus::Processed => Self::Success,
DwollaPaymentStatus::Failed => Self::Failure,
DwollaPaymentStatus::Processing => Self::Pending,
DwollaPaymentStatus::Pending => Self::Pending,
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DwollaErrorResponse {
pub code: String,
pub message: String,
#[serde(rename = "_embedded")]
pub embedded: Option<DwollaErrorDetails>,
pub reason: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DwollaErrorDetails {
pub errors: Vec<DwollaErrorDetail>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DwollaErrorDetail {
pub code: Option<String>,
pub message: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DwollaWebhookDetails {
pub id: String,
pub resource_id: String,
pub topic: String,
pub correlation_id: Option<String>,
}
impl From<&str> for DwollaWebhookEventType {
fn from(topic: &str) -> Self {
match topic {
"customer_created" => Self::CustomerCreated,
"customer_verified" => Self::CustomerVerified,
"customer_funding_source_added" => Self::CustomerFundingSourceAdded,
"customer_funding_source_removed" => Self::CustomerFundingSourceRemoved,
"customer_funding_source_verified" => Self::CustomerFundingSourceVerified,
"customer_funding_source_unverified" => Self::CustomerFundingSourceUnverified,
"customer_microdeposits_added" => Self::CustomerMicrodepositsAdded,
"customer_microdeposits_failed" => Self::CustomerMicrodepositsFailed,
"customer_microdeposits_completed" => Self::CustomerMicrodepositsCompleted,
"customer_microdeposits_maxattempts" => Self::CustomerMicrodepositsMaxAttempts,
"customer_bank_transfer_creation_failed" => Self::CustomerBankTransferCreationFailed,
"customer_bank_transfer_created" => Self::CustomerBankTransferCreated,
"customer_transfer_created" => Self::CustomerTransferCreated,
"customer_bank_transfer_failed" => Self::CustomerBankTransferFailed,
"customer_bank_transfer_completed" => Self::CustomerBankTransferCompleted,
"customer_transfer_completed" => Self::CustomerTransferCompleted,
"customer_transfer_failed" => Self::CustomerTransferFailed,
"transfer_created" => Self::TransferCreated,
"transfer_pending" => Self::TransferPending,
"transfer_completed" => Self::TransferCompleted,
"transfer_failed" => Self::TransferFailed,
_ => Self::Unknown,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum DwollaWebhookEventType {
CustomerCreated,
CustomerVerified,
CustomerFundingSourceAdded,
CustomerFundingSourceRemoved,
CustomerFundingSourceUnverified,
CustomerFundingSourceVerified,
CustomerMicrodepositsAdded,
CustomerMicrodepositsFailed,
CustomerMicrodepositsCompleted,
CustomerMicrodepositsMaxAttempts,
CustomerTransferCreated,
CustomerBankTransferCreationFailed,
CustomerBankTransferCreated,
CustomerBankTransferCompleted,
CustomerBankTransferFailed,
CustomerTransferCompleted,
CustomerTransferFailed,
TransferCreated,
TransferPending,
TransferCompleted,
TransferFailed,
#[serde(other)]
Unknown,
}
impl TryFrom<DwollaWebhookDetails> for api_models::webhooks::IncomingWebhookEvent {
type Error = errors::ConnectorError;
fn try_from(details: DwollaWebhookDetails) -> Result<Self, Self::Error> {
let correlation_id = match details.correlation_id.as_deref() {
Some(cid) => cid,
None => {
return Ok(Self::EventNotSupported);
}
};
let event_type = DwollaWebhookEventType::from(details.topic.as_str());
let is_refund = correlation_id.starts_with("refund_");
Ok(match (event_type, is_refund) {
(DwollaWebhookEventType::CustomerTransferCompleted, true)
| (DwollaWebhookEventType::CustomerBankTransferCompleted, true) => Self::RefundSuccess,
(DwollaWebhookEventType::CustomerTransferFailed, true)
| (DwollaWebhookEventType::CustomerBankTransferFailed, true) => Self::RefundFailure,
(DwollaWebhookEventType::CustomerTransferCreated, false)
| (DwollaWebhookEventType::CustomerBankTransferCreated, false) => {
Self::PaymentIntentProcessing
}
(DwollaWebhookEventType::CustomerTransferCompleted, false)
| (DwollaWebhookEventType::CustomerBankTransferCompleted, false) => {
Self::PaymentIntentSuccess
}
(DwollaWebhookEventType::CustomerTransferFailed, false)
| (DwollaWebhookEventType::CustomerBankTransferFailed, false) => {
Self::PaymentIntentFailure
}
_ => Self::EventNotSupported,
})
}
}
|
crates__hyperswitch_connectors__src__connectors__ebanx.rs
|
pub mod transformers;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
#[cfg(feature = "payouts")]
use common_utils::request::RequestContent;
#[cfg(feature = "payouts")]
use common_utils::request::{Method, Request, RequestBuilder};
#[cfg(feature = "payouts")]
use common_utils::types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector};
use common_utils::{errors::CustomResult, ext_traits::BytesExt};
use error_stack::{report, ResultExt};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_data::RouterData,
router_flow_types::{PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient},
types::{PayoutsData, PayoutsResponseData, PayoutsRouterData},
};
use hyperswitch_domain_models::{
router_data::{AccessToken, ErrorResponse},
router_flow_types::{
AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session,
SetupMandate, Void,
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods,
},
};
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::types::{PayoutCancelType, PayoutCreateType, PayoutFulfillType};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors::ConnectorError,
events::connector_api_logs::ConnectorEvent,
types::Response,
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},
};
#[cfg(feature = "payouts")]
use masking::Maskable;
#[cfg(feature = "payouts")]
use router_env::{instrument, tracing};
use transformers as ebanx;
#[cfg(feature = "payouts")]
use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount};
#[derive(Clone)]
pub struct Ebanx {
#[cfg(feature = "payouts")]
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Ebanx {
pub fn new() -> &'static Self {
&Self {
#[cfg(feature = "payouts")]
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Ebanx {}
impl api::PaymentSession for Ebanx {}
impl api::ConnectorAccessToken for Ebanx {}
impl api::MandateSetup for Ebanx {}
impl api::PaymentAuthorize for Ebanx {}
impl api::PaymentSync for Ebanx {}
impl api::PaymentCapture for Ebanx {}
impl api::PaymentVoid for Ebanx {}
impl api::Refund for Ebanx {}
impl api::RefundExecute for Ebanx {}
impl api::RefundSync for Ebanx {}
impl api::PaymentToken for Ebanx {}
impl api::Payouts for Ebanx {}
#[cfg(feature = "payouts")]
impl api::PayoutCancel for Ebanx {}
#[cfg(feature = "payouts")]
impl api::PayoutCreate for Ebanx {}
#[cfg(feature = "payouts")]
impl api::PayoutEligibility for Ebanx {}
#[cfg(feature = "payouts")]
impl api::PayoutQuote for Ebanx {}
#[cfg(feature = "payouts")]
impl api::PayoutRecipient for Ebanx {}
#[cfg(feature = "payouts")]
impl api::PayoutFulfill for Ebanx {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Ebanx
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
#[cfg(feature = "payouts")]
fn build_headers(
&self,
_req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let header = vec![(
headers::CONTENT_TYPE.to_string(),
self.common_get_content_type().to_string().into(),
)];
Ok(header)
}
}
impl ConnectorCommon for Ebanx {
fn id(&self) -> &'static str {
"ebanx"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.ebanx.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
let response: ebanx::EbanxErrorResponse =
res.response
.parse_struct("EbanxErrorResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.status_code,
message: response.code,
reason: response.message,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> for Ebanx {
fn get_url(
&self,
_req: &PayoutsRouterData<PoCreate>,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!("{}ws/payout/create", connectors.ebanx.base_url))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoCreate>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoCreate>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.source_currency,
)?;
let connector_router_data = ebanx::EbanxRouterData::from((amount, req));
let connector_req = ebanx::EbanxPayoutCreateRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoCreate>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutCreateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutCreateType::get_headers(self, req, connectors)?)
.set_body(PayoutCreateType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PayoutsRouterData<PoCreate>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoCreate>, ConnectorError> {
let response: ebanx::EbanxPayoutResponse = res
.response
.parse_struct("EbanxPayoutResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Ebanx {
fn get_url(
&self,
_req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!("{}ws/payout/commit", connectors.ebanx.base_url,))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoFulfill>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.source_currency,
)?;
let connector_router_data = ebanx::EbanxRouterData::from((amount, req));
let connector_req = ebanx::EbanxPayoutFulfillRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutFulfillType::get_headers(self, req, connectors)?)
.set_body(PayoutFulfillType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoFulfill>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoFulfill>, ConnectorError> {
let response: ebanx::EbanxFulfillResponse = res
.response
.parse_struct("EbanxFulfillResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData> for Ebanx {
fn get_url(
&self,
_req: &PayoutsRouterData<PoCancel>,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!("{}ws/payout/cancel", connectors.ebanx.base_url,))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoCancel>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, _connectors)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoCancel>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let connector_req = ebanx::EbanxPayoutCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoCancel>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Put)
.url(&PayoutCancelType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutCancelType::get_headers(self, req, connectors)?)
.set_body(PayoutCancelType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoCancel>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoCancel>, ConnectorError> {
let response: ebanx::EbanxCancelResponse = res
.response
.parse_struct("EbanxCancelResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData> for Ebanx {}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData> for Ebanx {}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData> for Ebanx {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Ebanx
{
// Not Implemented (R)
}
impl ConnectorValidation for Ebanx {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Ebanx {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Ebanx {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Ebanx {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Ebanx {}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Ebanx {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Ebanx {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Ebanx {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Ebanx {}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Ebanx {}
impl IncomingWebhook for Ebanx {
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<IncomingWebhookEvent, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
}
static EBANX_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Ebanx",
description: "EBANX payout connector for cross-border disbursements and local currency payouts across Latin America, Africa, and emerging markets",
connector_type: common_enums::HyperswitchConnectorCategory::PayoutProcessor,
integration_status: common_enums::ConnectorIntegrationStatus::Sandbox,
};
impl ConnectorSpecifications for Ebanx {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&EBANX_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
None
}
fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> {
None
}
}
|
crates__hyperswitch_connectors__src__connectors__elavon.rs
|
pub mod transformers;
use std::{collections::HashMap, str, sync::LazyLock};
use common_enums::{enums, CaptureMethod, PaymentMethod, PaymentMethodType};
use common_utils::{
errors::CustomResult,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::report;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{Secret, WithoutType};
use serde::Serialize;
use transformers as elavon;
use crate::{
constants::headers,
types::ResponseRouterData,
utils,
utils::{is_mandate_supported, PaymentMethodDataType},
};
pub fn struct_to_xml<T: Serialize>(
item: &T,
) -> Result<HashMap<String, Secret<String, WithoutType>>, errors::ConnectorError> {
let xml_content = quick_xml::se::to_string_with_root("txn", &item).map_err(|e| {
router_env::logger::error!("Error serializing Struct: {:?}", e);
errors::ConnectorError::ResponseDeserializationFailed
})?;
let mut result = HashMap::new();
result.insert(
"xmldata".to_string(),
Secret::<_, WithoutType>::new(xml_content),
);
Ok(result)
}
#[derive(Clone)]
pub struct Elavon {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Elavon {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl api::Payment for Elavon {}
impl api::PaymentSession for Elavon {}
impl api::ConnectorAccessToken for Elavon {}
impl api::MandateSetup for Elavon {}
impl api::PaymentAuthorize for Elavon {}
impl api::PaymentSync for Elavon {}
impl api::PaymentCapture for Elavon {}
impl api::PaymentVoid for Elavon {}
impl api::Refund for Elavon {}
impl api::RefundExecute for Elavon {}
impl api::RefundSync for Elavon {}
impl api::PaymentToken for Elavon {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Elavon
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Elavon
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Elavon {
fn id(&self) -> &'static str {
"elavon"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.elavon.base_url.as_ref()
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Elavon {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Elavon {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Elavon {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Elavon {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}processxml.do", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = elavon::ElavonRouterData::from((amount, req));
let connector_req = elavon::ElavonPaymentsRequest::try_from(&connector_router_data)?;
router_env::logger::info!(raw_connector_request=?connector_req);
Ok(RequestContent::FormUrlEncoded(Box::new(struct_to_xml(
&connector_req,
)?)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: elavon::ElavonPaymentsResponse =
utils::deserialize_xml_to_struct(&res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Elavon {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}processxml.do", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = elavon::SyncRequest::try_from(req)?;
router_env::logger::info!(raw_connector_request=?connector_req);
Ok(RequestContent::FormUrlEncoded(Box::new(struct_to_xml(
&connector_req,
)?)))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.set_body(types::PaymentsSyncType::get_request_body(
self, req, connectors,
)?)
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: elavon::ElavonSyncResponse = utils::deserialize_xml_to_struct(&res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Elavon {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}processxml.do", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = elavon::ElavonRouterData::from((amount, req));
let connector_req = elavon::PaymentsCaptureRequest::try_from(&connector_router_data)?;
router_env::logger::info!(raw_connector_request=?connector_req);
Ok(RequestContent::FormUrlEncoded(Box::new(struct_to_xml(
&connector_req,
)?)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: elavon::ElavonPaymentsResponse =
utils::deserialize_xml_to_struct(&res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Elavon {
fn build_request(
&self,
_req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("Cancel/Void flow".to_string()).into())
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Elavon {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}processxml.do", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = elavon::ElavonRouterData::from((refund_amount, req));
let connector_req = elavon::ElavonRefundRequest::try_from(&connector_router_data)?;
router_env::logger::info!(raw_connector_request=?connector_req);
Ok(RequestContent::FormUrlEncoded(Box::new(struct_to_xml(
&connector_req,
)?)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: elavon::ElavonPaymentsResponse =
utils::deserialize_xml_to_struct(&res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Elavon {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}processxml.do", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = elavon::SyncRequest::try_from(req)?;
router_env::logger::info!(raw_connector_request=?connector_req);
Ok(RequestContent::FormUrlEncoded(Box::new(struct_to_xml(
&connector_req,
)?)))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: elavon::ElavonSyncResponse = utils::deserialize_xml_to_struct(&res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Elavon {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
impl ConnectorValidation for Elavon {
fn validate_mandate_payment(
&self,
pm_type: Option<PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]);
is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
static ELAVON_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
CaptureMethod::Automatic,
CaptureMethod::Manual,
CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::Interac,
];
let mut elavon_supported_payment_methods = SupportedPaymentMethods::new();
elavon_supported_payment_methods.add(
PaymentMethod::Card,
PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
elavon_supported_payment_methods.add(
PaymentMethod::Card,
PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
elavon_supported_payment_methods
});
static ELAVON_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Elavon",
description: "Elavon, a wholly owned subsidiary of U.S. Bank, has been a global leader in payment processing for more than 30 years.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static ELAVON_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Elavon {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&ELAVON_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*ELAVON_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&ELAVON_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__envoy.rs
|
pub mod transformers;
use std::sync::LazyLock;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask};
use transformers as envoy;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Envoy {
amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Envoy {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Envoy {}
impl api::PaymentSession for Envoy {}
impl api::ConnectorAccessToken for Envoy {}
impl api::MandateSetup for Envoy {}
impl api::PaymentAuthorize for Envoy {}
impl api::PaymentSync for Envoy {}
impl api::PaymentCapture for Envoy {}
impl api::PaymentVoid for Envoy {}
impl api::Refund for Envoy {}
impl api::RefundExecute for Envoy {}
impl api::RefundSync for Envoy {}
impl api::PaymentToken for Envoy {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Envoy
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Envoy
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Envoy {
fn id(&self) -> &'static str {
"envoy"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.envoy.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = envoy::EnvoyAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.expose().into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: envoy::EnvoyErrorResponse =
res.response
.parse_struct("EnvoyErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code,
message: response.message,
reason: response.reason,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Envoy {
fn validate_mandate_payment(
&self,
_pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
match pm_data {
PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
"validate_mandate_payment does not support cards".to_string(),
)
.into()),
_ => Ok(()),
}
}
fn validate_psync_reference_id(
&self,
_data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
Ok(())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Envoy {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Envoy {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Envoy {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Envoy {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = envoy::EnvoyRouterData::from((amount, req));
let connector_req = envoy::EnvoyPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: envoy::EnvoyPaymentsResponse = res
.response
.parse_struct("Envoy PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Envoy {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: envoy::EnvoyPaymentsResponse = res
.response
.parse_struct("envoy PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Envoy {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: envoy::EnvoyPaymentsResponse = res
.response
.parse_struct("Envoy PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Envoy {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Envoy {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = envoy::EnvoyRouterData::from((refund_amount, req));
let connector_req = envoy::EnvoyRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: envoy::RefundResponse = res
.response
.parse_struct("envoy RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Envoy {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: envoy::RefundResponse = res
.response
.parse_struct("envoy RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Envoy {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static ENVOY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(SupportedPaymentMethods::new);
static ENVOY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Envoy",
description: "Envoy connector",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static ENVOY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Envoy {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&ENVOY_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*ENVOY_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&ENVOY_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__facilitapay.rs
|
mod requests;
mod responses;
pub mod transformers;
use common_enums::enums;
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt, ValueExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{
Authorize, Capture, CreateConnectorCustomer, PSync, PaymentMethodToken, Session,
SetupMandate, Void,
},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, RefreshTokenType, Response},
webhooks,
};
use lazy_static::lazy_static;
use masking::{ExposeInterface, Mask, PeekInterface};
use requests::{
FacilitapayAuthRequest, FacilitapayCustomerRequest, FacilitapayPaymentsRequest,
FacilitapayRouterData,
};
use responses::{
FacilitapayAuthResponse, FacilitapayCustomerResponse, FacilitapayPaymentsResponse,
FacilitapayRefundResponse, FacilitapayWebhookEventType,
};
use transformers::parse_facilitapay_error_response;
use crate::{
connectors::facilitapay::responses::FacilitapayVoidResponse,
constants::headers,
types::{RefreshTokenRouterData, ResponseRouterData},
utils::{self, RefundsRequestData},
};
#[derive(Clone)]
pub struct Facilitapay {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Facilitapay {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl api::ConnectorCustomer for Facilitapay {}
impl api::Payment for Facilitapay {}
impl api::PaymentSession for Facilitapay {}
impl api::ConnectorAccessToken for Facilitapay {}
impl api::MandateSetup for Facilitapay {}
impl api::PaymentAuthorize for Facilitapay {}
impl api::PaymentSync for Facilitapay {}
impl api::PaymentCapture for Facilitapay {}
impl api::PaymentVoid for Facilitapay {}
impl api::Refund for Facilitapay {}
impl api::RefundExecute for Facilitapay {}
impl api::RefundSync for Facilitapay {}
impl api::PaymentToken for Facilitapay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Facilitapay
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Facilitapay
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let access_token = req
.access_token
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let headers = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", access_token.token.clone().peek()).into_masked(),
),
];
Ok(headers)
}
}
impl ConnectorCommon for Facilitapay {
fn id(&self) -> &'static str {
"facilitapay"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.facilitapay.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
parse_facilitapay_error_response(res, event_builder)
}
}
impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>
for Facilitapay
{
fn get_headers(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/subject/people", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &ConnectorCustomerRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = FacilitapayCustomerRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::ConnectorCustomerType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::ConnectorCustomerType::get_headers(
self, req, connectors,
)?)
.set_body(types::ConnectorCustomerType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &ConnectorCustomerRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<ConnectorCustomerRouterData, errors::ConnectorError>
where
ConnectorCustomerRouterData: Clone,
{
let response: FacilitapayCustomerResponse = res
.response
.parse_struct("FacilitapayCustomerResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorValidation for Facilitapay {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Facilitapay {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Facilitapay {
fn get_headers(
&self,
_req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![(
headers::CONTENT_TYPE.to_string(),
self.common_get_content_type().to_string().into(),
)])
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/sign_in", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = FacilitapayAuthRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.attach_default_headers()
.headers(RefreshTokenType::get_headers(self, req, connectors)?)
.url(&RefreshTokenType::get_url(self, req, connectors)?)
.set_body(RefreshTokenType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefreshTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
let response: FacilitapayAuthResponse = res
.response
.parse_struct("FacilitapayAuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Facilitapay
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented(
"Setup Mandate flow for Facilitapay".to_string(),
)
.into())
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Facilitapay {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/transactions", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = FacilitapayRouterData::from((amount, req));
let connector_req = FacilitapayPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: FacilitapayPaymentsResponse = res
.response
.parse_struct("FacilitapayPaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Facilitapay {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_transaction_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/transactions/{}",
self.base_url(connectors),
connector_transaction_id
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: FacilitapayPaymentsResponse = res
.response
.parse_struct("FacilitapayPaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Facilitapay {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: FacilitapayPaymentsResponse = res
.response
.parse_struct("FacilitapayPaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Facilitapay {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/transactions/{}/refund",
self.base_url(connectors),
req.request.connector_transaction_id
))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: FacilitapayVoidResponse = res
.response
.parse_struct("FacilitapayCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Facilitapay {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/transactions/{}/refund_received_transaction",
self.base_url(connectors),
req.request.connector_transaction_id
))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
// Validate that this is a full refund
if req.request.payment_amount != req.request.refund_amount {
return Err(errors::ConnectorError::NotSupported {
message: "Partial refund not supported by Facilitapay".to_string(),
connector: "Facilitapay",
}
.into());
}
let request = RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: FacilitapayRefundResponse = res
.response
.parse_struct("FacilitapayRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Facilitapay {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}/transactions/{}/refund_received_transaction/{}",
self.base_url(connectors),
req.request.connector_transaction_id,
refund_id
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: FacilitapayRefundResponse = res
.response
.parse_struct("FacilitapayRefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Facilitapay {
async fn verify_webhook_source(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<masking::Secret<serde_json::Value>>,
_connector_name: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let webhook_body: responses::FacilitapayWebhookNotification = request
.body
.parse_struct("FacilitapayWebhookNotification")
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let connector_webhook_secrets = match connector_webhook_details {
Some(secret_value) => {
let secret = secret_value
.parse_value::<api_models::admin::MerchantConnectorWebhookDetails>(
"MerchantConnectorWebhookDetails",
)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
secret.merchant_secret.expose()
}
None => "default_secret".to_string(),
};
// FacilitaPay uses a simple 4-digit secret for verification
Ok(webhook_body.notification.secret.peek() == &connector_webhook_secrets)
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook_body: responses::FacilitapayWebhookNotification = request
.body
.parse_struct("FacilitapayWebhookNotification")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
// Extract transaction ID from the webhook data
let transaction_id = match &webhook_body.notification.data {
responses::FacilitapayWebhookData::Transaction { transaction_id }
| responses::FacilitapayWebhookData::CardPayment { transaction_id, .. } => {
transaction_id.clone()
}
responses::FacilitapayWebhookData::Exchange {
transaction_ids, ..
}
| responses::FacilitapayWebhookData::Wire {
transaction_ids, ..
}
| responses::FacilitapayWebhookData::WireError {
transaction_ids, ..
} => transaction_ids
.first()
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?
.clone(),
};
// For refund webhooks, Facilitapay sends the original payment transaction ID
// not the refund transaction ID
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(transaction_id),
))
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let webhook_body: responses::FacilitapayWebhookNotification = request
.body
.parse_struct("FacilitapayWebhookNotification")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
// Note: For "identified" events, we need additional logic to determine if it's cross-currency
// Since we don't have access to the payment data here, we'll default to Success for now
// The actual status determination happens in the webhook processing flow
let event = match webhook_body.notification.event_type {
FacilitapayWebhookEventType::ExchangeCreated => {
api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing
}
FacilitapayWebhookEventType::Identified
| FacilitapayWebhookEventType::PaymentApproved
| FacilitapayWebhookEventType::WireCreated => {
api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess
}
FacilitapayWebhookEventType::PaymentExpired
| FacilitapayWebhookEventType::PaymentFailed => {
api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure
}
FacilitapayWebhookEventType::PaymentRefunded => {
api_models::webhooks::IncomingWebhookEvent::RefundSuccess
}
FacilitapayWebhookEventType::WireWaitingCorrection => {
api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired
}
};
Ok(event)
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook_body: responses::FacilitapayWebhookNotification = request
.body
.parse_struct("FacilitapayWebhookNotification")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Box::new(webhook_body))
}
}
lazy_static! {
static ref FACILITAPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name:
"Facilitapay",
description:
"FacilitaPay, the best and most reliable payment provider for your international business.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static ref FACILITAPAY_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
let facilitapay_supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::SequentialAutomatic,
];
let mut facilitapay_supported_payment_methods = SupportedPaymentMethods::new();
facilitapay_supported_payment_methods.add(
enums::PaymentMethod::BankTransfer,
enums::PaymentMethodType::Pix,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: facilitapay_supported_capture_methods.clone(),
specific_features: None,
},
);
facilitapay_supported_payment_methods
};
static ref FACILITAPAY_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = vec![
enums::EventClass::Payments,
];
}
impl ConnectorSpecifications for Facilitapay {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*FACILITAPAY_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*FACILITAPAY_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*FACILITAPAY_SUPPORTED_WEBHOOK_FLOWS)
}
fn should_call_connector_customer(
&self,
_payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> bool {
true
}
}
|
crates__hyperswitch_connectors__src__connectors__fiserv.rs
|
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts, errors,
events::connector_api_logs::ConnectorEvent,
types, webhooks,
};
use masking::{ExposeInterface, Mask, PeekInterface};
use ring::hmac;
use time::OffsetDateTime;
use transformers as fiserv;
use uuid::Uuid;
use crate::{
constants::headers, types::ResponseRouterData, utils as connector_utils, utils::convert_amount,
};
#[derive(Clone)]
pub struct Fiserv {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Fiserv {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
pub fn generate_authorization_signature(
&self,
auth: fiserv::FiservAuthType,
request_id: &str,
payload: &str,
timestamp: i128,
) -> CustomResult<String, errors::ConnectorError> {
let fiserv::FiservAuthType {
api_key,
api_secret,
..
} = auth;
let raw_signature = format!("{}{request_id}{timestamp}{payload}", api_key.peek());
let key = hmac::Key::new(hmac::HMAC_SHA256, api_secret.expose().as_bytes());
let signature_value = common_utils::consts::BASE64_ENGINE
.encode(hmac::sign(&key, raw_signature.as_bytes()).as_ref());
Ok(signature_value)
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Fiserv
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let timestamp = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
let auth: fiserv::FiservAuthType =
fiserv::FiservAuthType::try_from(&req.connector_auth_type)?;
let mut auth_header = self.get_auth_header(&req.connector_auth_type)?;
let fiserv_req = self.get_request_body(req, connectors)?;
let client_request_id = Uuid::new_v4().to_string();
let hmac = self
.generate_authorization_signature(
auth,
&client_request_id,
fiserv_req.get_inner_value().peek(),
timestamp,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let mut headers = vec![
(
headers::CONTENT_TYPE.to_string(),
types::PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
),
("Client-Request-Id".to_string(), client_request_id.into()),
("Auth-Token-Type".to_string(), "HMAC".to_string().into()),
(headers::TIMESTAMP.to_string(), timestamp.to_string().into()),
(headers::AUTHORIZATION.to_string(), hmac.into_masked()),
];
headers.append(&mut auth_header);
Ok(headers)
}
}
impl ConnectorCommon for Fiserv {
fn id(&self) -> &'static str {
"fiserv"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.fiserv.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = fiserv::FiservAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::API_KEY.to_string(),
auth.api_key.into_masked(),
)])
}
fn build_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: fiserv::ErrorResponse = res
.response
.parse_struct("Fiserv ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_details_opt = response.error.as_ref().and_then(|v| v.first());
let (code, message, reason) = if let Some(first_error) = error_details_opt {
let code = first_error
.code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string());
let message = first_error
.message
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string());
let reason = first_error.additional_info.clone();
(code, message, reason)
} else {
(
consts::NO_ERROR_CODE.to_string(),
consts::NO_ERROR_MESSAGE.to_string(),
None,
)
};
Ok(ErrorResponse {
code,
message,
reason,
status_code: res.status_code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl api::ConnectorAccessToken for Fiserv {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Fiserv {
// Not Implemented (R)
}
impl ConnectorValidation for Fiserv {}
impl api::Payment for Fiserv {}
impl api::PaymentToken for Fiserv {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Fiserv
{
// Not Implemented (R)
}
impl api::MandateSetup for Fiserv {}
#[allow(dead_code)]
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Fiserv {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Fiserv".to_string())
.into(),
)
}
}
impl api::PaymentVoid for Fiserv {}
#[allow(dead_code)]
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Fiserv {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
"application/json"
}
fn get_url(
&self,
_req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
//The docs has this url wrong, cancels is the working endpoint
"{}ch/payments/v1/cancels",
connectors.fiserv.base_url
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = fiserv::FiservCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build(),
);
Ok(request)
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: fiserv::FiservPaymentsResponse = res
.response
.parse_struct("Fiserv PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::PaymentSync for Fiserv {}
#[allow(dead_code)]
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Fiserv {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
"application/json"
}
fn get_url(
&self,
_req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ch/payments/v1/transaction-inquiry",
connectors.fiserv.base_url
))
}
fn get_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = fiserv::FiservSyncRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
);
Ok(request)
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: fiserv::FiservSyncResponse = res
.response
.parse_struct("Fiserv PaymentSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let p_sync_response = response.sync_responses.first().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "P_Sync_Responses[0]",
},
)?;
let (approved_amount, currency) = match &p_sync_response {
fiserv::FiservPaymentsResponse::Charges(resp) => (
&resp.payment_receipt.approved_amount.total,
&resp.payment_receipt.approved_amount.currency,
),
fiserv::FiservPaymentsResponse::Checkout(resp) => (
&resp.payment_receipt.approved_amount.total,
&resp.payment_receipt.approved_amount.currency,
),
};
let response_integrity_object = connector_utils::get_sync_integrity_object(
self.amount_converter,
*approved_amount,
currency.to_string().clone(),
)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let new_router_data = RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed);
new_router_data.map(|mut router_data| {
router_data.request.integrity_object = Some(response_integrity_object);
router_data
})
}
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::PaymentCapture for Fiserv {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Fiserv {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
"application/json"
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_to_capture = convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let router_obj = fiserv::FiservRouterData::try_from((amount_to_capture, req))?;
let connector_req = fiserv::FiservCaptureRequest::try_from(&router_obj)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
);
Ok(request)
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: fiserv::FiservPaymentsResponse = res
.response
.parse_struct("Fiserv Payment Response")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let (approved_amount, currency) = match &response {
fiserv::FiservPaymentsResponse::Charges(resp) => (
&resp.payment_receipt.approved_amount.total,
&resp.payment_receipt.approved_amount.currency,
),
fiserv::FiservPaymentsResponse::Checkout(resp) => (
&resp.payment_receipt.approved_amount.total,
&resp.payment_receipt.approved_amount.currency,
),
};
let response_integrity_object = connector_utils::get_capture_integrity_object(
self.amount_converter,
Some(*approved_amount),
currency.to_string().clone(),
)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let new_router_data = RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed);
new_router_data.map(|mut router_data| {
router_data.request.integrity_object = Some(response_integrity_object);
router_data
})
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ch/payments/v1/charges",
connectors.fiserv.base_url
))
}
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::PaymentSession for Fiserv {}
#[allow(dead_code)]
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Fiserv {}
impl api::PaymentAuthorize for Fiserv {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Fiserv {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
"application/json"
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let url = match &req.request.payment_method_data {
PaymentMethodData::Wallet(WalletData::PaypalRedirect(_)) => {
format!("{}ch/checkouts/v1/orders", connectors.fiserv.base_url)
}
_ => format!("{}ch/payments/v1/charges", connectors.fiserv.base_url),
};
Ok(url)
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let router_obj = fiserv::FiservRouterData::try_from((amount, req))?;
let connector_req = fiserv::FiservPaymentsRequest::try_from(&router_obj)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
);
Ok(request)
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: fiserv::FiservPaymentsResponse = res
.response
.parse_struct("Fiserv PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let (approved_amount, currency) = match &response {
fiserv::FiservPaymentsResponse::Charges(resp) => (
&resp.payment_receipt.approved_amount.total,
&resp.payment_receipt.approved_amount.currency,
),
fiserv::FiservPaymentsResponse::Checkout(resp) => (
&resp.payment_receipt.approved_amount.total,
&resp.payment_receipt.approved_amount.currency,
),
};
let response_integrity_object = connector_utils::get_authorise_integrity_object(
self.amount_converter,
*approved_amount,
currency.to_string().clone(),
)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let new_router_data = RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed);
new_router_data.map(|mut router_data| {
router_data.request.integrity_object = Some(response_integrity_object);
router_data
})
}
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::Refund for Fiserv {}
impl api::RefundExecute for Fiserv {}
impl api::RefundSync for Fiserv {}
#[allow(dead_code)]
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Fiserv {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
"application/json"
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ch/payments/v1/refunds",
connectors.fiserv.base_url
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let router_obj = fiserv::FiservRouterData::try_from((refund_amount, req))?;
let connector_req = fiserv::FiservRefundRequest::try_from(&router_obj)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
router_env::logger::debug!(target: "router::connector::fiserv", response=?res);
let response: fiserv::RefundResponse =
res.response
.parse_struct("fiserv RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let response_integrity_object = connector_utils::get_refund_integrity_object(
self.amount_converter,
response.payment_receipt.approved_amount.total,
response
.payment_receipt
.approved_amount
.currency
.to_string()
.clone(),
)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let new_router_data = RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed);
new_router_data.map(|mut router_data| {
router_data.request.integrity_object = Some(response_integrity_object);
router_data
})
}
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[allow(dead_code)]
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Fiserv {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
"application/json"
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ch/payments/v1/transaction-inquiry",
connectors.fiserv.base_url
))
}
fn get_request_body(
&self,
req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = fiserv::FiservSyncRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
);
Ok(request)
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
router_env::logger::debug!(target: "router::connector::fiserv", response=?res);
let response: fiserv::FiservSyncResponse = res
.response
.parse_struct("Fiserv Refund Response")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let r_sync_response = response.sync_responses.first().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "R_Sync_Responses[0]",
},
)?;
let (approved_amount, currency) = match &r_sync_response {
fiserv::FiservPaymentsResponse::Charges(resp) => (
&resp.payment_receipt.approved_amount.total,
&resp.payment_receipt.approved_amount.currency,
),
fiserv::FiservPaymentsResponse::Checkout(resp) => (
&resp.payment_receipt.approved_amount.total,
&resp.payment_receipt.approved_amount.currency,
),
};
let response_integrity_object = connector_utils::get_refund_integrity_object(
self.amount_converter,
*approved_amount,
currency.to_string().clone(),
)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let new_router_data = RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed);
new_router_data.map(|mut router_data| {
router_data.request.integrity_object = Some(response_integrity_object);
router_data
})
}
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Fiserv {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static FISERV_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::SequentialAutomatic,
enums::CaptureMethod::Manual,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Interac,
];
let mut fiserv_supported_payment_methods = SupportedPaymentMethods::new();
fiserv_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
fiserv_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
fiserv_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
fiserv_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Paypal,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
fiserv_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
fiserv_supported_payment_methods
});
static FISERV_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Fiserv",
description:
"Fiserv is a global fintech and payments company with solutions for banking, global commerce, merchant acquiring, billing and payments, and point-of-sale ",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static FISERV_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Fiserv {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&FISERV_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*FISERV_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&FISERV_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__fiserv__transformers.rs
|
use api_models::payments::{
ApplePayCombinedMetadata, ApplepayCombinedSessionTokenData, ApplepaySessionTokenData,
ApplepaySessionTokenMetadata,
};
use base64::Engine;
use common_enums::{enums, Currency};
use common_utils::{
consts::BASE64_ENGINE, ext_traits::ValueExt, pii, request::Method, types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{ser::Serializer, Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, CardData as _, PaymentsCancelRequestData, PaymentsSyncRequestData, RouterData as _,
},
};
#[derive(Debug, Serialize)]
pub struct FiservRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(FloatMajorUnit, T)> for FiservRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, router_data): (FloatMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data,
})
}
}
impl Serialize for FiservCheckoutChargesRequest {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Checkout(inner) => inner.serialize(serializer),
Self::Charges(inner) => inner.serialize(serializer),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservPaymentsRequest {
amount: Amount,
merchant_details: MerchantDetails,
#[serde(flatten)]
checkout_charges_request: FiservCheckoutChargesRequest,
}
#[derive(Debug)]
pub enum FiservCheckoutChargesRequest {
Checkout(CheckoutPaymentsRequest),
Charges(ChargesPaymentRequest),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckoutPaymentsRequest {
order: FiservOrder,
payment_method: FiservPaymentMethod,
interactions: FiservInteractions,
transaction_details: TransactionDetails,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FiservChannel {
Web,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FiservPaymentInitiator {
Merchant,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FiservCustomerConfirmation {
ReviewAndPay,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservInteractions {
channel: FiservChannel,
customer_confirmation: FiservCustomerConfirmation,
payment_initiator: FiservPaymentInitiator,
return_urls: FiservReturnUrls,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservReturnUrls {
success_url: String,
cancel_url: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservPaymentMethod {
provider: FiservWallet,
#[serde(rename = "type")]
wallet_type: FiservWalletType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservOrder {
intent: FiservIntent,
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FiservIntent {
Authorize,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ChargesPaymentRequest {
source: Source,
transaction_interaction: Option<TransactionInteraction>,
transaction_details: TransactionDetails,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FiservWallet {
ApplePay,
GooglePay,
PayPal,
}
#[derive(Debug, Serialize)]
#[serde(tag = "sourceType")]
pub enum Source {
#[serde(rename = "GooglePay")]
GooglePay(GooglePayData),
#[serde(rename = "PaymentCard")]
PaymentCard { card: CardData },
#[serde(rename = "ApplePay")]
ApplePay(ApplePayWalletDetails),
#[serde(rename = "DecryptedWallet")]
DecryptedWallet(DecryptedWalletDetails),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayWalletDetails {
pub data: Secret<String>,
pub header: ApplePayHeader,
pub signature: Secret<String>,
pub version: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub application_data: Option<Secret<String>>,
pub apple_pay_merchant_id: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayHeader {
#[serde(skip_serializing_if = "Option::is_none")]
pub application_data_hash: Option<Secret<String>>,
pub ephemeral_public_key: Secret<String>,
pub public_key_hash: Secret<String>,
pub transaction_id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DecryptedWalletDetails {
pub card: WalletCardData,
#[serde(rename = "cavv")]
pub cryptogram: Secret<String>,
#[serde(rename = "xid")]
pub transaction_id: Secret<String>,
pub wallet_type: FiservWalletType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FiservWalletType {
ApplePay,
GooglePay,
PaypalWallet,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayData {
data: Secret<String>,
signature: Secret<String>,
version: String,
intermediate_signing_key: IntermediateSigningKey,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardData {
card_data: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
security_code: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletCardData {
card_data: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
}
#[derive(Default, Debug, Serialize)]
pub struct Amount {
total: FloatMajorUnit,
currency: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionDetails {
#[serde(skip_serializing_if = "Option::is_none")]
capture_flag: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
reversal_reason_code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_transaction_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
operation_type: Option<OperationType>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum OperationType {
Create,
Capture,
Authorize,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantDetails {
merchant_id: Secret<String>,
terminal_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionInteraction {
origin: TransactionInteractionOrigin,
eci_indicator: TransactionInteractionEciIndicator,
pos_condition_code: TransactionInteractionPosConditionCode,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum TransactionInteractionOrigin {
#[default]
Ecom,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionInteractionEciIndicator {
#[default]
ChannelEncrypted,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionInteractionPosConditionCode {
#[default]
CardNotPresentEcom,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IntermediateSigningKey {
signed_key: Secret<String>,
signatures: Vec<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SignedKey {
key_value: String,
key_expiration: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SignedMessage {
encrypted_message: String,
ephemeral_public_key: String,
tag: String,
}
#[derive(Debug, Default)]
pub struct FullyParsedGooglePayToken {
pub signature: Secret<String>,
pub protocol_version: String,
pub encrypted_message: String,
pub ephemeral_public_key: String,
pub tag: String,
pub key_value: String,
pub key_expiration: String,
pub signatures: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RawGooglePayToken {
pub signature: Secret<String>,
pub protocol_version: String,
pub signed_message: Secret<String>,
pub intermediate_signing_key: IntermediateSigningKey,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ApplePayDecryptedData {
pub data: Secret<String>,
pub signature: Secret<String>,
pub version: Secret<String>,
pub header: ApplePayHeader,
}
pub fn parse_googlepay_token_safely(token_json_str: &str) -> FullyParsedGooglePayToken {
let mut result = FullyParsedGooglePayToken::default();
if let Ok(raw_token) = serde_json::from_str::<RawGooglePayToken>(token_json_str) {
result.signature = raw_token.signature;
result.protocol_version = raw_token.protocol_version;
result.signatures = raw_token
.intermediate_signing_key
.signatures
.into_iter()
.map(|s| s.expose().to_owned())
.collect();
if let Ok(key) = serde_json::from_str::<SignedKey>(
&raw_token.intermediate_signing_key.signed_key.expose(),
) {
result.key_value = key.key_value;
result.key_expiration = key.key_expiration;
}
if let Ok(message) =
serde_json::from_str::<SignedMessage>(&raw_token.signed_message.expose())
{
result.encrypted_message = message.encrypted_message;
result.ephemeral_public_key = message.ephemeral_public_key;
result.tag = message.tag;
}
}
result
}
impl TryFrom<&FiservRouterData<&types::PaymentsAuthorizeRouterData>> for FiservPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &FiservRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if item.router_data.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Cards 3DS".to_string(),
connector: "Fiserv",
})?
}
let auth: FiservAuthType = FiservAuthType::try_from(&item.router_data.connector_auth_type)?;
let amount = Amount {
total: item.amount,
currency: item.router_data.request.currency.to_string(),
};
let metadata = item.router_data.get_connector_meta()?.clone();
let session: FiservSessionObject = metadata
.expose()
.parse_value("FiservSessionObject")
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "Merchant connector account metadata",
})?;
let merchant_details = MerchantDetails {
merchant_id: auth.merchant_account,
terminal_id: Some(session.terminal_id),
};
let checkout_charges_request = match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ref ccard) => {
Ok(FiservCheckoutChargesRequest::Charges(
ChargesPaymentRequest {
source: Source::PaymentCard {
card: CardData {
card_data: ccard.card_number.clone(),
expiration_month: ccard.card_exp_month.clone(),
expiration_year: ccard.get_expiry_year_4_digit(),
security_code: Some(ccard.card_cvc.clone()),
},
},
transaction_details: TransactionDetails {
capture_flag: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None
)),
reversal_reason_code: None,
merchant_transaction_id: Some(
item.router_data.connector_request_reference_id.clone(),
),
operation_type: None,
},
transaction_interaction: Some(TransactionInteraction {
//Payment is being made in online mode, card not present
origin: TransactionInteractionOrigin::Ecom,
// transaction encryption such as SSL/TLS, but authentication was not performed
eci_indicator: TransactionInteractionEciIndicator::ChannelEncrypted,
//card not present in online transaction
pos_condition_code:
TransactionInteractionPosConditionCode::CardNotPresentEcom,
}),
},
))
}
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::GooglePay(data) => {
let token_string = data
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?
.to_owned();
let parsed = parse_googlepay_token_safely(&token_string);
Ok(FiservCheckoutChargesRequest::Charges(
ChargesPaymentRequest {
source: Source::GooglePay(GooglePayData {
data: Secret::new(parsed.encrypted_message),
signature: Secret::new(parsed.signature.expose().to_owned()),
version: parsed.protocol_version,
intermediate_signing_key: IntermediateSigningKey {
signed_key: Secret::new(
serde_json::json!({
"keyValue": parsed.key_value,
"keyExpiration": parsed.key_expiration
})
.to_string(),
),
signatures: parsed
.signatures
.into_iter()
.map(|s| Secret::new(s.to_owned()))
.collect(),
},
}),
transaction_details: TransactionDetails {
capture_flag: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None
)),
reversal_reason_code: None,
merchant_transaction_id: Some(
item.router_data.connector_request_reference_id.clone(),
),
operation_type: None,
},
transaction_interaction: None,
},
))
}
WalletData::PaypalRedirect(_) => {
let return_url = item
.router_data
.request
.complete_authorize_url
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "return_url",
})?;
Ok(FiservCheckoutChargesRequest::Checkout(
CheckoutPaymentsRequest {
payment_method: FiservPaymentMethod {
provider: FiservWallet::PayPal,
wallet_type: FiservWalletType::PaypalWallet,
},
order: FiservOrder {
intent: FiservIntent::Authorize,
},
interactions: FiservInteractions {
channel: FiservChannel::Web,
customer_confirmation: FiservCustomerConfirmation::ReviewAndPay,
payment_initiator: FiservPaymentInitiator::Merchant,
return_urls: FiservReturnUrls {
success_url: return_url.clone(),
cancel_url: return_url,
},
},
transaction_details: TransactionDetails {
operation_type: Some(OperationType::Create),
capture_flag: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None
)),
reversal_reason_code: None,
merchant_transaction_id: Some(
item.router_data.connector_request_reference_id.clone(),
),
},
},
))
}
WalletData::ApplePay(apple_pay_data) => match item
.router_data
.payment_method_token
.clone()
{
Some(PaymentMethodToken::ApplePayDecrypt(pre_decrypt_data)) => Ok(
FiservCheckoutChargesRequest::Charges(ChargesPaymentRequest {
source: Source::DecryptedWallet(DecryptedWalletDetails {
wallet_type: FiservWalletType::ApplePay,
cryptogram: pre_decrypt_data
.payment_data
.online_payment_cryptogram
.clone(),
transaction_id: Secret::new(apple_pay_data.transaction_identifier),
card: WalletCardData {
card_data: pre_decrypt_data
.application_primary_account_number
.clone(),
expiration_month: pre_decrypt_data
.get_expiry_month()
.change_context(
errors::ConnectorError::MissingRequiredField {
field_name: "apple_pay_expiry_month",
},
)?,
expiration_year: pre_decrypt_data.get_four_digit_expiry_year(),
},
}),
transaction_details: TransactionDetails {
capture_flag: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None
)),
reversal_reason_code: None,
merchant_transaction_id: Some(
item.router_data.connector_request_reference_id.clone(),
),
operation_type: None,
},
transaction_interaction: None,
}),
),
_ => {
let decoded_bytes = match apple_pay_data.payment_data {
common_types::payments::ApplePayPaymentData::Encrypted(
ref encrypted_str,
) => BASE64_ENGINE
.decode(encrypted_str)
.change_context(errors::ConnectorError::ParsingFailed)?,
_ => {
return Err(errors::ConnectorError::ParsingFailed.into());
}
};
let payment_data_decoded: ApplePayDecryptedData =
serde_json::from_slice(&decoded_bytes)
.change_context(errors::ConnectorError::ParsingFailed)?;
let data = payment_data_decoded.data;
let signature = payment_data_decoded.signature;
let version = payment_data_decoded.version;
let header = ApplePayHeader {
ephemeral_public_key: payment_data_decoded.header.ephemeral_public_key,
public_key_hash: payment_data_decoded.header.public_key_hash,
transaction_id: payment_data_decoded.header.transaction_id,
application_data_hash: None,
};
let apple_pay_metadata = item.router_data.get_connector_meta()?;
let applepay_metadata = apple_pay_metadata
.clone()
.parse_value::<ApplepayCombinedSessionTokenData>(
"ApplepayCombinedSessionTokenData",
)
.change_context(errors::ConnectorError::ParsingFailed)
.map(|combined_metadata| {
ApplepaySessionTokenMetadata::ApplePayCombined(
combined_metadata.apple_pay_combined,
)
})
.or_else(|_| {
apple_pay_metadata
.parse_value::<ApplepaySessionTokenData>(
"ApplepaySessionTokenData",
)
.change_context(errors::ConnectorError::ParsingFailed)
.map(|old_metadata| {
ApplepaySessionTokenMetadata::ApplePay(
old_metadata.apple_pay,
)
})
})?;
let merchant_identifier = match applepay_metadata {
ApplepaySessionTokenMetadata::ApplePayCombined(ref combined) => {
match combined.get_combined_metadata_required().change_context(
errors::ConnectorError::MissingApplePayTokenData,
)? {
ApplePayCombinedMetadata::Simplified { .. } => {
return Err(
errors::ConnectorError::MissingApplePayTokenData.into(),
)
}
ApplePayCombinedMetadata::Manual {
session_token_data, ..
} => &session_token_data.merchant_identifier.clone(),
}
}
ApplepaySessionTokenMetadata::ApplePay(ref data) => {
&data.session_token_data.merchant_identifier
}
};
Ok(FiservCheckoutChargesRequest::Charges(
ChargesPaymentRequest {
source: Source::ApplePay(ApplePayWalletDetails {
data,
header,
signature,
version,
application_data: None,
apple_pay_merchant_id: Secret::new(
merchant_identifier.to_owned(),
),
}),
transaction_details: TransactionDetails {
capture_flag: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None
)),
reversal_reason_code: None,
merchant_transaction_id: Some(
item.router_data.connector_request_reference_id.clone(),
),
operation_type: None,
},
transaction_interaction: None,
},
))
}
},
_ => Err(error_stack::report!(
errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiserv"),
)
)),
},
PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => Err(
error_stack::report!(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiserv"),
)),
),
}?;
Ok(Self {
amount,
checkout_charges_request,
merchant_details,
})
}
}
pub struct FiservAuthType {
pub(super) api_key: Secret<String>,
pub(super) merchant_account: Secret<String>,
pub(super) api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for FiservAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = auth_type
{
Ok(Self {
api_key: api_key.to_owned(),
merchant_account: key1.to_owned(),
api_secret: api_secret.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservCancelRequest {
transaction_details: TransactionDetails,
merchant_details: MerchantDetails,
reference_transaction_details: ReferenceTransactionDetails,
}
impl TryFrom<&types::PaymentsCancelRouterData> for FiservCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let auth: FiservAuthType = FiservAuthType::try_from(&item.connector_auth_type)?;
let metadata = item.get_connector_meta()?.clone();
let session: FiservSessionObject = metadata
.expose()
.parse_value("FiservSessionObject")
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "Merchant connector account metadata",
})?;
Ok(Self {
merchant_details: MerchantDetails {
merchant_id: auth.merchant_account,
terminal_id: Some(session.terminal_id),
},
reference_transaction_details: ReferenceTransactionDetails {
reference_transaction_id: item.request.connector_transaction_id.to_string(),
},
transaction_details: TransactionDetails {
capture_flag: None,
reversal_reason_code: Some(item.request.get_cancellation_reason()?),
merchant_transaction_id: Some(item.connector_request_reference_id.clone()),
operation_type: None,
},
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorResponse {
pub error: Option<Vec<ErrorDetails>>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorDetails {
#[serde(rename = "type")]
pub error_type: Option<String>,
pub code: Option<String>,
pub field: Option<String>,
pub message: Option<String>,
pub additional_info: Option<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FiservPaymentStatus {
Succeeded,
Failed,
Captured,
Declined,
Voided,
Authorized,
#[default]
Processing,
Created,
}
impl From<FiservPaymentStatus> for enums::AttemptStatus {
fn from(item: FiservPaymentStatus) -> Self {
match item {
FiservPaymentStatus::Captured | FiservPaymentStatus::Succeeded => Self::Charged,
FiservPaymentStatus::Declined | FiservPaymentStatus::Failed => Self::Failure,
FiservPaymentStatus::Processing => Self::Authorizing,
FiservPaymentStatus::Voided => Self::Voided,
FiservPaymentStatus::Authorized => Self::Authorized,
FiservPaymentStatus::Created => Self::AuthenticationPending,
}
}
}
impl From<FiservPaymentStatus> for enums::RefundStatus {
fn from(item: FiservPaymentStatus) -> Self {
match item {
FiservPaymentStatus::Succeeded
| FiservPaymentStatus::Authorized
| FiservPaymentStatus::Captured => Self::Success,
FiservPaymentStatus::Declined | FiservPaymentStatus::Failed => Self::Failure,
FiservPaymentStatus::Voided
| FiservPaymentStatus::Processing
| FiservPaymentStatus::Created => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessorResponseDetails {
pub approval_status: Option<String>,
pub approval_code: Option<String>,
pub reference_number: Option<String>,
pub processor: Option<String>,
pub host: Option<String>,
pub network_routed: Option<String>,
pub network_international_id: Option<String>,
pub response_code: Option<String>,
pub response_message: Option<String>,
pub host_response_code: Option<String>,
pub host_response_message: Option<String>,
pub additional_info: Option<Vec<AdditionalInfo>>,
pub bank_association_details: Option<BankAssociationDetails>,
pub response_indicators: Option<ResponseIndicators>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdditionalInfo {
pub name: Option<String>,
pub value: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BankAssociationDetails {
pub association_response_code: Option<String>,
pub avs_security_code_response: Option<AvsSecurityCodeResponse>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AvsSecurityCodeResponse {
pub street_match: Option<String>,
pub postal_code_match: Option<String>,
pub security_code_match: Option<String>,
pub association: Option<Association>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Association {
pub avs_code: Option<String>,
pub security_code_response: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResponseIndicators {
pub alternate_route_debit_indicator: Option<bool>,
pub signature_line_indicator: Option<bool>,
pub signature_debit_route_indicator: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservChargesResponse {
pub gateway_response: GatewayResponse,
pub payment_receipt: PaymentReceipt,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservCheckoutResponse {
pub gateway_response: GatewayResponse,
pub payment_receipt: PaymentReceipt,
pub interactions: FiservResponseInteractions,
pub order: Option<FiservResponseOrders>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservResponseInteractions {
actions: FiservResponseActions,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservResponseActions {
#[serde(rename = "type")]
action_type: String,
url: url::Url,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservResponseOrders {
intent: FiservIntent,
order_id: String,
order_status: FiservOrderStatus,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FiservOrderStatus {
PayerActionRequired,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FiservPaymentsResponse {
Charges(FiservChargesResponse),
Checkout(FiservCheckoutResponse),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentReceipt {
pub approved_amount: ApprovedAmount,
pub processor_response_details: Option<ProcessorResponseDetails>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApprovedAmount {
pub total: FloatMajorUnit,
pub currency: Currency,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(transparent)]
pub struct FiservSyncResponse {
pub sync_responses: Vec<FiservPaymentsResponse>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GatewayResponse {
gateway_transaction_id: Option<String>,
transaction_state: FiservPaymentStatus,
transaction_processing_details: TransactionProcessingDetails,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionProcessingDetails {
order_id: String,
transaction_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, FiservPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FiservPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (gateway_resp, redirect_url, order_id) = match &item.response {
FiservPaymentsResponse::Charges(res) => (res.gateway_response.clone(), None, None),
FiservPaymentsResponse::Checkout(res) => (
res.gateway_response.clone(),
Some(res.interactions.actions.url.clone()),
res.order.as_ref().map(|o| o.order_id.clone()),
),
};
let redirection_data = redirect_url.map(|url| RedirectForm::from((url, Method::Get)));
let connector_metadata: Option<serde_json::Value> = Some(serde_json::json!({
"order_id": order_id,
}));
Ok(Self {
status: enums::AttemptStatus::from(gateway_resp.transaction_state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
gateway_resp.transaction_processing_details.transaction_id,
),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(
gateway_resp.transaction_processing_details.order_id,
),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FiservSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FiservSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let gateway_resp = match item.response.sync_responses.first() {
Some(gateway_response) => gateway_response,
None => Err(errors::ConnectorError::ResponseHandlingFailed)?,
};
let connector_response_reference_id = match gateway_resp {
FiservPaymentsResponse::Charges(res) => {
&res.gateway_response.transaction_processing_details.order_id
}
FiservPaymentsResponse::Checkout(res) => {
&res.gateway_response.transaction_processing_details.order_id
}
};
let transaction_id = match gateway_resp {
FiservPaymentsResponse::Charges(res) => {
&res.gateway_response
.transaction_processing_details
.transaction_id
}
FiservPaymentsResponse::Checkout(res) => {
&res.gateway_response
.transaction_processing_details
.transaction_id
}
};
let transaction_state = match gateway_resp {
FiservPaymentsResponse::Charges(res) => &res.gateway_response.transaction_state,
FiservPaymentsResponse::Checkout(res) => &res.gateway_response.transaction_state,
};
Ok(Self {
status: enums::AttemptStatus::from(transaction_state.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(connector_response_reference_id.to_string()),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservCaptureRequest {
amount: Amount,
transaction_details: TransactionDetails,
merchant_details: MerchantDetails,
reference_transaction_details: ReferenceTransactionDetails,
#[serde(skip_serializing_if = "Option::is_none")]
order: Option<FiservOrderRequest>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservOrderRequest {
order_id: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReferenceTransactionDetails {
reference_transaction_id: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FiservSessionObject {
pub terminal_id: Secret<String>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for FiservSessionObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
impl TryFrom<&FiservRouterData<&types::PaymentsCaptureRouterData>> for FiservCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &FiservRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let auth: FiservAuthType = FiservAuthType::try_from(&item.router_data.connector_auth_type)?;
let metadata = item
.router_data
.connector_meta_data
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
let session: FiservSessionObject = metadata
.expose()
.parse_value("FiservSessionObject")
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "Merchant connector account metadata",
})?;
let order_id = item
.router_data
.request
.connector_meta
.as_ref()
.and_then(|v| v.get("order_id"))
.and_then(|v| v.as_str())
.map(|s| s.to_string());
Ok(Self {
amount: Amount {
total: item.amount,
currency: item.router_data.request.currency.to_string(),
},
order: Some(FiservOrderRequest { order_id }),
transaction_details: TransactionDetails {
capture_flag: Some(true),
reversal_reason_code: None,
merchant_transaction_id: Some(
item.router_data.connector_request_reference_id.clone(),
),
operation_type: Some(OperationType::Capture),
},
merchant_details: MerchantDetails {
merchant_id: auth.merchant_account,
terminal_id: Some(session.terminal_id),
},
reference_transaction_details: ReferenceTransactionDetails {
reference_transaction_id: item
.router_data
.request
.connector_transaction_id
.to_string(),
},
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservSyncRequest {
merchant_details: MerchantDetails,
reference_transaction_details: ReferenceTransactionDetails,
}
impl TryFrom<&types::PaymentsSyncRouterData> for FiservSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let auth: FiservAuthType = FiservAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
merchant_details: MerchantDetails {
merchant_id: auth.merchant_account,
terminal_id: None,
},
reference_transaction_details: ReferenceTransactionDetails {
reference_transaction_id: item
.request
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
},
})
}
}
impl TryFrom<&types::RefundSyncRouterData> for FiservSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
let auth: FiservAuthType = FiservAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
merchant_details: MerchantDetails {
merchant_id: auth.merchant_account,
terminal_id: None,
},
reference_transaction_details: ReferenceTransactionDetails {
reference_transaction_id: item
.request
.connector_refund_id
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?,
},
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservRefundRequest {
amount: Amount,
merchant_details: MerchantDetails,
reference_transaction_details: ReferenceTransactionDetails,
}
impl<F> TryFrom<&FiservRouterData<&types::RefundsRouterData<F>>> for FiservRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &FiservRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let auth: FiservAuthType = FiservAuthType::try_from(&item.router_data.connector_auth_type)?;
let metadata = item
.router_data
.connector_meta_data
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
let session: FiservSessionObject = metadata
.expose()
.parse_value("FiservSessionObject")
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "Merchant connector account metadata",
})?;
Ok(Self {
amount: Amount {
total: item.amount,
currency: item.router_data.request.currency.to_string(),
},
merchant_details: MerchantDetails {
merchant_id: auth.merchant_account,
terminal_id: Some(session.terminal_id),
},
reference_transaction_details: ReferenceTransactionDetails {
reference_transaction_id: item
.router_data
.request
.connector_transaction_id
.to_string(),
},
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
pub gateway_response: GatewayResponse,
pub payment_receipt: PaymentReceipt,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item
.response
.gateway_response
.transaction_processing_details
.transaction_id,
refund_status: enums::RefundStatus::from(
item.response.gateway_response.transaction_state,
),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, FiservSyncResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, FiservSyncResponse>,
) -> Result<Self, Self::Error> {
let gateway_resp = item
.response
.sync_responses
.first()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let transaction_id = match gateway_resp {
FiservPaymentsResponse::Charges(res) => {
&res.gateway_response
.transaction_processing_details
.transaction_id
}
FiservPaymentsResponse::Checkout(res) => {
&res.gateway_response
.transaction_processing_details
.transaction_id
}
};
let transaction_state = match gateway_resp {
FiservPaymentsResponse::Charges(res) => &res.gateway_response.transaction_state,
FiservPaymentsResponse::Checkout(res) => &res.gateway_response.transaction_state,
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: transaction_id.clone(),
refund_status: enums::RefundStatus::from(transaction_state.clone()),
}),
..item.data
})
}
}
|
crates__hyperswitch_connectors__src__connectors__fiservemea.rs
|
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts, errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask, PeekInterface};
use ring::hmac;
use time::OffsetDateTime;
use transformers as fiservemea;
use uuid::Uuid;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, RefundsRequestData as _},
};
#[derive(Clone)]
pub struct Fiservemea {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Fiservemea {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
pub fn generate_authorization_signature(
&self,
auth: fiservemea::FiservemeaAuthType,
request_id: &str,
payload: &str,
timestamp: i128,
) -> CustomResult<String, errors::ConnectorError> {
let fiservemea::FiservemeaAuthType {
api_key,
secret_key,
} = auth;
let raw_signature = format!("{}{request_id}{timestamp}{payload}", api_key.peek());
let key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.expose().as_bytes());
let signature_value = common_utils::consts::BASE64_ENGINE
.encode(hmac::sign(&key, raw_signature.as_bytes()).as_ref());
Ok(signature_value)
}
}
impl api::Payment for Fiservemea {}
impl api::PaymentSession for Fiservemea {}
impl api::ConnectorAccessToken for Fiservemea {}
impl api::MandateSetup for Fiservemea {}
impl api::PaymentAuthorize for Fiservemea {}
impl api::PaymentSync for Fiservemea {}
impl api::PaymentCapture for Fiservemea {}
impl api::PaymentVoid for Fiservemea {}
impl api::Refund for Fiservemea {}
impl api::RefundExecute for Fiservemea {}
impl api::RefundSync for Fiservemea {}
impl api::PaymentToken for Fiservemea {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Fiservemea {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Fiservemea {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Fiservemea
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Fiservemea".to_string())
.into(),
)
}
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Fiservemea
{
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Fiservemea
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let timestamp = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
let auth: fiservemea::FiservemeaAuthType =
fiservemea::FiservemeaAuthType::try_from(&req.connector_auth_type)?;
let client_request_id = Uuid::new_v4().to_string();
let http_method = self.get_http_method();
let hmac = match http_method {
Method::Get => self
.generate_authorization_signature(auth.clone(), &client_request_id, "", timestamp)
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
Method::Post | Method::Put | Method::Delete | Method::Patch => {
let fiserv_req = self.get_request_body(req, connectors)?;
self.generate_authorization_signature(
auth.clone(),
&client_request_id,
fiserv_req.get_inner_value().peek(),
timestamp,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?
}
};
let headers = vec![
(
headers::CONTENT_TYPE.to_string(),
types::PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
),
("Client-Request-Id".to_string(), client_request_id.into()),
(headers::API_KEY.to_string(), auth.api_key.expose().into()),
(headers::TIMESTAMP.to_string(), timestamp.to_string().into()),
(headers::MESSAGE_SIGNATURE.to_string(), hmac.into_masked()),
];
Ok(headers)
}
}
impl ConnectorCommon for Fiservemea {
fn id(&self) -> &'static str {
"fiservemea"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.fiservemea.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: fiservemea::FiservemeaErrorResponse = res
.response
.parse_struct("FiservemeaErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
match response.error {
Some(error) => {
let details = error.details.map(|details| {
details
.iter()
.map(|detail| {
format!(
"{}: {}",
detail
.field
.clone()
.unwrap_or("No Field Provided".to_string()),
detail
.message
.clone()
.unwrap_or("No Message Provided".to_string())
)
})
.collect::<Vec<String>>()
.join(", ")
});
Ok(ErrorResponse {
status_code: res.status_code,
code: error.code.unwrap_or(consts::NO_ERROR_CODE.to_string()),
message: response
.response_type
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: match details {
Some(details) => Some(format!(
"{} {}",
error.message.unwrap_or("".to_string()),
details
)),
None => error.message,
},
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
None => Ok(ErrorResponse {
status_code: res.status_code,
code: consts::NO_ERROR_CODE.to_string(),
message: response
.response_type
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: response.response_type,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
}
}
}
impl ConnectorValidation for Fiservemea {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Fiservemea {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/ipp/payments-gateway/v2/payments",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = fiservemea::FiservemeaRouterData::from((amount, req));
let connector_req =
fiservemea::FiservemeaPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: fiservemea::FiservemeaPaymentsResponse = res
.response
.parse_struct("Fiservemea PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Fiservemea {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/ipp/payments-gateway/v2/payments/{connector_payment_id}",
self.base_url(connectors)
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: fiservemea::FiservemeaPaymentsResponse = res
.response
.parse_struct("fiservemea PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Fiservemea {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/ipp/payments-gateway/v2/payments/{connector_payment_id}",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = fiservemea::FiservemeaRouterData::from((amount, req));
let connector_req = fiservemea::FiservemeaCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: fiservemea::FiservemeaPaymentsResponse = res
.response
.parse_struct("Fiservemea PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Fiservemea {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/ipp/payments-gateway/v2/payments/{connector_payment_id}",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = fiservemea::FiservemeaVoidRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: fiservemea::FiservemeaPaymentsResponse = res
.response
.parse_struct("Fiservemea PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Fiservemea {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/ipp/payments-gateway/v2/payments/{connector_payment_id}",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = fiservemea::FiservemeaRouterData::from((refund_amount, req));
let connector_req = fiservemea::FiservemeaRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: fiservemea::FiservemeaPaymentsResponse = res
.response
.parse_struct("fiservemea RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Fiservemea {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}/ipp/payments-gateway/v2/payments/{connector_payment_id}",
self.base_url(connectors)
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: fiservemea::FiservemeaPaymentsResponse = res
.response
.parse_struct("fiservemea RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Fiservemea {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static FISERVEMEA_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::CartesBancaires,
];
let mut fiservemea_supported_payment_methods = SupportedPaymentMethods::new();
fiservemea_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
fiservemea_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
fiservemea_supported_payment_methods
});
static FISERVEMEA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Fiservemea",
description: "Fiserv powers over 6+ million merchants and 10,000+ financial institutions enabling them to accept billions of payments a year.",
connector_type: enums::HyperswitchConnectorCategory::BankAcquirer,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static FISERVEMEA_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Fiservemea {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&FISERVEMEA_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*FISERVEMEA_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&FISERVEMEA_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__fiuu.rs
|
pub mod transformers;
use std::{
any::type_name,
borrow::Cow,
collections::{HashMap, HashSet},
sync::LazyLock,
};
use common_enums::{CaptureMethod, PaymentMethod, PaymentMethodType};
use common_utils::{
crypto::{self, GenerateDigest},
errors::{self as common_errors, CustomResult},
ext_traits::{ByteSliceExt, BytesExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use reqwest::multipart::Form;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use transformers::{self as fiuu, ExtraParameters, FiuuWebhooksResponse};
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, PaymentMethodDataType},
};
pub fn parse_and_log_keys_in_url_encoded_response<T>(data: &[u8]) {
match std::str::from_utf8(data) {
Ok(query_str) => {
let loggable_keys = [
"status",
"orderid",
"tranID",
"nbcb",
"amount",
"currency",
"paydate",
"channel",
"error_desc",
"error_code",
"extraP",
];
let keys: Vec<(Cow<'_, str>, String)> =
url::form_urlencoded::parse(query_str.as_bytes())
.map(|(key, value)| {
if loggable_keys.contains(&key.to_string().as_str()) {
(key, value.to_string())
} else {
(key, "SECRET".to_string())
}
})
.collect();
router_env::logger::info!("Keys in {} response\n{:?}", type_name::<T>(), keys);
}
Err(err) => {
router_env::logger::error!("Failed to convert bytes to string: {:?}", err);
}
}
}
fn parse_response<T>(data: &[u8]) -> Result<T, errors::ConnectorError>
where
T: for<'de> Deserialize<'de>,
{
let response_str = String::from_utf8(data.to_vec()).map_err(|e| {
router_env::logger::error!("Error in Deserializing Response Data: {:?}", e);
errors::ConnectorError::ResponseDeserializationFailed
})?;
let mut json = serde_json::Map::new();
let mut miscellaneous: HashMap<String, Secret<String>> = HashMap::new();
for line in response_str.lines() {
if let Some((key, value)) = line.split_once('=') {
if key.trim().is_empty() {
router_env::logger::error!("Null or empty key encountered in response.");
continue;
}
if let Some(old_value) = json.insert(key.to_string(), Value::String(value.to_string()))
{
router_env::logger::warn!("Repeated key encountered: {}", key);
miscellaneous.insert(key.to_string(), Secret::new(old_value.to_string()));
}
}
}
if !miscellaneous.is_empty() {
let misc_value = serde_json::to_value(miscellaneous).map_err(|e| {
router_env::logger::error!("Error serializing miscellaneous data: {:?}", e);
errors::ConnectorError::ResponseDeserializationFailed
})?;
json.insert("miscellaneous".to_string(), misc_value);
}
// TODO: Remove this after debugging
let loggable_keys = [
"StatCode",
"StatName",
"TranID",
"ErrorCode",
"ErrorDesc",
"miscellaneous",
];
let keys: Vec<(&str, Value)> = json
.iter()
.map(|(key, value)| {
if loggable_keys.contains(&key.as_str()) {
(key.as_str(), value.to_owned())
} else {
(key.as_str(), Value::String("SECRET".to_string()))
}
})
.collect();
router_env::logger::info!("Keys in response for type {}\n{:?}", type_name::<T>(), keys);
let response: T = serde_json::from_value(Value::Object(json)).map_err(|e| {
router_env::logger::error!("Error in Deserializing Response Data: {:?}", e);
errors::ConnectorError::ResponseDeserializationFailed
})?;
Ok(response)
}
#[derive(Clone)]
pub struct Fiuu {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Fiuu {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl api::Payment for Fiuu {}
impl api::PaymentSession for Fiuu {}
impl api::ConnectorAccessToken for Fiuu {}
impl api::MandateSetup for Fiuu {}
impl api::PaymentAuthorize for Fiuu {}
impl api::PaymentSync for Fiuu {}
impl api::PaymentCapture for Fiuu {}
impl api::PaymentVoid for Fiuu {}
impl api::Refund for Fiuu {}
impl api::RefundExecute for Fiuu {}
impl api::RefundSync for Fiuu {}
impl api::PaymentToken for Fiuu {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Fiuu
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Fiuu
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
_req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
Ok(header)
}
}
impl ConnectorCommon for Fiuu {
fn id(&self) -> &'static str {
"fiuu"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.fiuu.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: fiuu::FiuuErrorResponse = res
.response
.parse_struct("FiuuErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_code.clone(),
message: response.error_desc.clone(),
reason: Some(response.error_desc.clone()),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
pub fn build_form_from_struct<T: Serialize + Send + 'static>(
data: T,
) -> Result<RequestContent, common_errors::ParsingError> {
let mut form = Form::new();
let serialized = serde_json::to_value(&data).map_err(|e| {
router_env::logger::error!("Error serializing data to JSON value: {:?}", e);
common_errors::ParsingError::EncodeError("json-value")
})?;
let serialized_object = serialized.as_object().ok_or_else(|| {
router_env::logger::error!("Error: Expected JSON object but got something else");
common_errors::ParsingError::EncodeError("Expected object")
})?;
for (key, values) in serialized_object {
let value = match values {
Value::String(s) => s.clone(),
Value::Number(n) => n.to_string(),
Value::Bool(b) => b.to_string(),
Value::Array(_) | Value::Object(_) | Value::Null => {
router_env::logger::error!(serialization_error =? "Form Construction Failed.");
"".to_string()
}
};
form = form.text(key.clone(), value.clone());
}
Ok(RequestContent::FormData((form, Box::new(data))))
}
impl ConnectorValidation for Fiuu {
fn validate_mandate_payment(
&self,
pm_type: Option<PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd: HashSet<PaymentMethodDataType> =
HashSet::from([PaymentMethodDataType::Card]);
utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Fiuu {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Fiuu {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Fiuu {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Fiuu {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let optional_is_mit_flow = req.request.off_session;
let optional_is_nti_flow = req
.request
.mandate_id
.as_ref()
.map(|mandate_id| mandate_id.is_network_transaction_id_flow());
let url = match (optional_is_mit_flow, optional_is_nti_flow) {
(Some(true), Some(false)) => format!(
"{}/RMS/API/Recurring/input_v7.php",
self.base_url(connectors)
),
_ => {
format!(
"{}RMS/API/Direct/1.4.0/index.php",
self.base_url(connectors)
)
}
};
Ok(url)
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = fiuu::FiuuRouterData::from((amount, req));
let optional_is_mit_flow = req.request.off_session;
let optional_is_nti_flow = req
.request
.mandate_id
.as_ref()
.map(|mandate_id| mandate_id.is_network_transaction_id_flow());
match (optional_is_mit_flow, optional_is_nti_flow) {
(Some(true), Some(false)) => {
let recurring_request = fiuu::FiuuMandateRequest::try_from(&connector_router_data)?;
build_form_from_struct(recurring_request)
.change_context(errors::ConnectorError::ParsingFailed)
}
_ => {
let payment_request = fiuu::FiuuPaymentRequest::try_from(&connector_router_data)?;
build_form_from_struct(payment_request)
.change_context(errors::ConnectorError::ParsingFailed)
}
}
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: fiuu::FiuuPaymentsResponse = res
.response
.parse_struct("Fiuu FiuuPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Fiuu {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
_req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url = connectors.fiuu.secondary_base_url.clone();
Ok(format!("{base_url}RMS/API/gate-query/index.php"))
}
fn get_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let sync_request = fiuu::FiuuPaymentSyncRequest::try_from(req)?;
build_form_from_struct(sync_request).change_context(errors::ConnectorError::ParsingFailed)
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.set_body(types::PaymentsSyncType::get_request_body(
self, req, connectors,
)?)
.attach_default_headers()
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
match res.headers {
Some(headers) => {
let content_header = utils::get_http_header("Content-type", &headers)
.attach_printable("Missing content type in headers")
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let response: fiuu::FiuuPaymentResponse = if content_header
== "text/plain;charset=UTF-8"
{
parse_response(&res.response)
} else {
Err(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable(format!("Expected content type to be text/plain;charset=UTF-8 , but received different content type as {content_header} in response"))?
}?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
None => {
// We don't get headers for payment webhook response handling
let response: fiuu::FiuuPaymentResponse = res
.response
.parse_struct("fiuu::FiuuPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Fiuu {
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url = connectors.fiuu.secondary_base_url.clone();
Ok(format!("{base_url}RMS/API/capstxn/index.php"))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = fiuu::FiuuRouterData::from((amount, req));
build_form_from_struct(fiuu::PaymentCaptureRequest::try_from(
&connector_router_data,
)?)
.change_context(errors::ConnectorError::ParsingFailed)
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: fiuu::PaymentCaptureResponse = res
.response
.parse_struct("Fiuu PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Fiuu {
fn get_url(
&self,
_req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url = connectors.fiuu.secondary_base_url.clone();
Ok(format!("{base_url}RMS/API/refundAPI/refund.php"))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
build_form_from_struct(fiuu::FiuuPaymentCancelRequest::try_from(req)?)
.change_context(errors::ConnectorError::ParsingFailed)
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build(),
);
Ok(request)
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: fiuu::FiuuPaymentCancelResponse = parse_response(&res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Fiuu {
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url = connectors.fiuu.secondary_base_url.clone();
Ok(format!("{base_url}RMS/API/refundAPI/index.php"))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = fiuu::FiuuRouterData::from((refund_amount, req));
build_form_from_struct(fiuu::FiuuRefundRequest::try_from(&connector_router_data)?)
.change_context(errors::ConnectorError::ParsingFailed)
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: fiuu::FiuuRefundResponse = res
.response
.parse_struct("fiuu FiuuRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Fiuu {
fn get_url(
&self,
_req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url = connectors.fiuu.secondary_base_url.clone();
Ok(format!("{base_url}RMS/API/refundAPI/q_by_txn.php"))
}
fn get_request_body(
&self,
req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
build_form_from_struct(fiuu::FiuuRefundSyncRequest::try_from(req)?)
.change_context(errors::ConnectorError::ParsingFailed)
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: fiuu::FiuuRefundSyncResponse = res
.response
.parse_struct("fiuu FiuuRefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Fiuu {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::Md5))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let header = utils::get_header_key_value("content-type", request.headers)?;
let resource: FiuuWebhooksResponse = if header == "application/x-www-form-urlencoded" {
parse_and_log_keys_in_url_encoded_response::<FiuuWebhooksResponse>(request.body);
serde_urlencoded::from_bytes::<FiuuWebhooksResponse>(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?
} else {
request
.body
.parse_struct("fiuu::FiuuWebhooksResponse")
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?
};
let signature = match resource {
FiuuWebhooksResponse::FiuuWebhookPaymentResponse(webhooks_payment_response) => {
webhooks_payment_response.skey
}
FiuuWebhooksResponse::FiuuWebhookRefundResponse(webhooks_refunds_response) => {
webhooks_refunds_response.signature
}
};
hex::decode(signature.expose())
.change_context(errors::ConnectorError::WebhookVerificationSecretInvalid)
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let header = utils::get_header_key_value("content-type", request.headers)?;
let resource: FiuuWebhooksResponse = if header == "application/x-www-form-urlencoded" {
parse_and_log_keys_in_url_encoded_response::<FiuuWebhooksResponse>(request.body);
serde_urlencoded::from_bytes::<FiuuWebhooksResponse>(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?
} else {
request
.body
.parse_struct("fiuu::FiuuWebhooksResponse")
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?
};
let verification_message = match resource {
FiuuWebhooksResponse::FiuuWebhookPaymentResponse(webhooks_payment_response) => {
let key0 = format!(
"{}{}{}{}{}{}",
webhooks_payment_response.tran_id,
webhooks_payment_response.order_id,
webhooks_payment_response.status,
webhooks_payment_response.domain.clone().peek(),
webhooks_payment_response.amount.get_amount_as_string(),
webhooks_payment_response.currency
);
let md5_key0 = hex::encode(
crypto::Md5
.generate_digest(key0.as_bytes())
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
);
let key1 = format!(
"{}{}{}{}{}",
webhooks_payment_response.paydate,
webhooks_payment_response.domain.peek(),
md5_key0,
webhooks_payment_response
.appcode
.map_or("".to_string(), |appcode| appcode.expose()),
String::from_utf8_lossy(&connector_webhook_secrets.secret)
);
key1
}
FiuuWebhooksResponse::FiuuWebhookRefundResponse(webhooks_refunds_response) => {
format!(
"{}{}{}{}{}{}{}{}",
webhooks_refunds_response.refund_type,
webhooks_refunds_response.merchant_id.peek(),
webhooks_refunds_response.ref_id,
webhooks_refunds_response.refund_id,
webhooks_refunds_response.txn_id,
webhooks_refunds_response.amount.get_amount_as_string(),
webhooks_refunds_response.status,
String::from_utf8_lossy(&connector_webhook_secrets.secret)
)
}
};
Ok(verification_message.as_bytes().to_vec())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let header = utils::get_header_key_value("content-type", request.headers)?;
let resource: FiuuWebhooksResponse = if header == "application/x-www-form-urlencoded" {
parse_and_log_keys_in_url_encoded_response::<FiuuWebhooksResponse>(request.body);
serde_urlencoded::from_bytes::<FiuuWebhooksResponse>(request.body)
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?
} else {
request
.body
.parse_struct("fiuu::FiuuWebhooksResponse")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?
};
let resource_id = match resource {
FiuuWebhooksResponse::FiuuWebhookPaymentResponse(webhooks_payment_response) => {
api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::PaymentAttemptId(
webhooks_payment_response.order_id,
),
)
}
FiuuWebhooksResponse::FiuuWebhookRefundResponse(webhooks_refunds_response) => {
api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(
webhooks_refunds_response.refund_id,
),
)
}
};
Ok(resource_id)
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let header = utils::get_header_key_value("content-type", request.headers)?;
let resource: FiuuWebhooksResponse = if header == "application/x-www-form-urlencoded" {
parse_and_log_keys_in_url_encoded_response::<FiuuWebhooksResponse>(request.body);
serde_urlencoded::from_bytes::<FiuuWebhooksResponse>(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?
} else {
request
.body
.parse_struct("fiuu::FiuuWebhooksResponse")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?
};
match resource {
FiuuWebhooksResponse::FiuuWebhookPaymentResponse(webhooks_payment_response) => Ok(
api_models::webhooks::IncomingWebhookEvent::from(webhooks_payment_response.status),
),
FiuuWebhooksResponse::FiuuWebhookRefundResponse(webhooks_refunds_response) => Ok(
api_models::webhooks::IncomingWebhookEvent::from(webhooks_refunds_response.status),
),
}
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let header = utils::get_header_key_value("content-type", request.headers)?;
let payload: FiuuWebhooksResponse = if header == "application/x-www-form-urlencoded" {
parse_and_log_keys_in_url_encoded_response::<FiuuWebhooksResponse>(request.body);
serde_urlencoded::from_bytes::<FiuuWebhooksResponse>(request.body)
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?
} else {
request
.body
.parse_struct("fiuu::FiuuWebhooksResponse")
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?
};
match payload.clone() {
FiuuWebhooksResponse::FiuuWebhookPaymentResponse(webhook_payment_response) => Ok(
Box::new(fiuu::FiuuPaymentResponse::FiuuWebhooksPaymentResponse(
webhook_payment_response,
)),
),
FiuuWebhooksResponse::FiuuWebhookRefundResponse(webhook_refund_response) => {
Ok(Box::new(fiuu::FiuuRefundSyncResponse::Webhook(
webhook_refund_response,
)))
}
}
}
fn get_mandate_details(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Option<hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails>,
errors::ConnectorError,
> {
parse_and_log_keys_in_url_encoded_response::<transformers::FiuuWebhooksPaymentResponse>(
request.body,
);
let webhook_payment_response: transformers::FiuuWebhooksPaymentResponse =
serde_urlencoded::from_bytes::<transformers::FiuuWebhooksPaymentResponse>(request.body)
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
let mandate_reference = webhook_payment_response.extra_parameters.as_ref().and_then(|extra_p| {
let mandate_token: Result<ExtraParameters, _> = serde_json::from_str(&extra_p.clone().expose());
match mandate_token {
Ok(token) => {
token.token.as_ref().map(|token| hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails {
connector_mandate_id:token.clone(),
})
}
Err(err) => {
router_env::logger::warn!(
"Failed to convert 'extraP' from fiuu webhook response to fiuu::ExtraParameters. \
Input: '{:?}', Error: {}",
extra_p,
err
);
None
}
}
});
Ok(mandate_reference)
}
}
static FIUU_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
CaptureMethod::Automatic,
CaptureMethod::Manual,
CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Discover,
];
let mut fiuu_supported_payment_methods = SupportedPaymentMethods::new();
fiuu_supported_payment_methods.add(
PaymentMethod::RealTimePayment,
PaymentMethodType::DuitNow,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
fiuu_supported_payment_methods.add(
PaymentMethod::BankRedirect,
PaymentMethodType::OnlineBankingFpx,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
fiuu_supported_payment_methods.add(
PaymentMethod::Wallet,
PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
fiuu_supported_payment_methods.add(
PaymentMethod::Wallet,
PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
fiuu_supported_payment_methods.add(
PaymentMethod::Card,
PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
fiuu_supported_payment_methods.add(
PaymentMethod::Card,
PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
fiuu_supported_payment_methods
});
static FIUU_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Fiuu",
description:
"Fiuu, formerly known as Razer Merchant Services, is a leading online payment gateway in Southeast Asia, offering secure and seamless payment solutions for businesses of all sizes, including credit and debit cards, e-wallets, and bank transfers.",
connector_type: common_enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: common_enums::ConnectorIntegrationStatus::Live,
};
static FIUU_SUPPORTED_WEBHOOK_FLOWS: [common_enums::EventClass; 2] = [
common_enums::EventClass::Payments,
common_enums::EventClass::Refunds,
];
impl ConnectorSpecifications for Fiuu {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&FIUU_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*FIUU_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::EventClass]> {
Some(&FIUU_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__fiuu__transformers.rs
|
use std::collections::HashMap;
use api_models::payments;
use cards::CardNumber;
use common_enums::{enums, BankNames, CaptureMethod, Currency};
use common_types::payments::ApplePayPredecryptData;
use common_utils::{
crypto::{self, GenerateDigest},
errors::CustomResult,
ext_traits::Encode,
pii::Email,
request::Method,
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{Report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::{
BankRedirectData, Card, CardDetailsForNetworkTransactionId, GooglePayWalletData,
PaymentMethodData, RealTimePaymentData, WalletData,
},
router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use strum::Display;
use url::Url;
// These needs to be accepted from SDK, need to be done after 1.0.0 stability as API contract will change
const GOOGLEPAY_API_VERSION_MINOR: u8 = 0;
const GOOGLEPAY_API_VERSION: u8 = 2;
use crate::{
constants,
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
},
unimplemented_payment_method,
utils::{self, PaymentsAuthorizeRequestData, QrImage, RefundsRequestData, RouterData as _},
};
pub struct FiuuRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for FiuuRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub struct FiuuAuthType {
pub(super) merchant_id: Secret<String>,
pub(super) verify_key: Secret<String>,
pub(super) secret_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for FiuuAuthType {
type Error = Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
merchant_id: key1.to_owned(),
verify_key: api_key.to_owned(),
secret_key: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum TxnType {
Sals,
Auts,
}
impl TryFrom<Option<CaptureMethod>> for TxnType {
type Error = Report<errors::ConnectorError>;
fn try_from(capture_method: Option<CaptureMethod>) -> Result<Self, Self::Error> {
match capture_method {
Some(CaptureMethod::Automatic) | Some(CaptureMethod::SequentialAutomatic) | None => {
Ok(Self::Sals)
}
Some(CaptureMethod::Manual) => Ok(Self::Auts),
_ => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
}
#[derive(Serialize, Deserialize, Display, Debug, Clone)]
enum TxnChannel {
#[serde(rename = "CREDITAN")]
#[strum(serialize = "CREDITAN")]
Creditan,
#[serde(rename = "RPP_DUITNOWQR")]
#[strum(serialize = "RPP_DUITNOWQR")]
RppDuitNowQr,
}
#[derive(Serialize, Deserialize, Display, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
pub enum FPXTxnChannel {
FpxAbb,
FpxUob,
FpxAbmb,
FpxScb,
FpxBsn,
FpxKfh,
FpxBmmb,
FpxBkrm,
FpxHsbc,
FpxAgrobank,
FpxBocm,
FpxMb2u,
FpxCimbclicks,
FpxAmb,
FpxHlb,
FpxPbb,
FpxRhb,
FpxBimb,
FpxOcbc,
}
#[derive(Debug, Clone, Serialize)]
pub enum BankCode {
PHBMMYKL,
AGOBMYK1,
MFBBMYKL,
ARBKMYKL,
BKCHMYKL,
BIMBMYKL,
BMMBMYKL,
BKRMMYK1,
BSNAMYK1,
CIBBMYKL,
HLBBMYKL,
HBMBMYKL,
KFHOMYKL,
MBBEMYKL,
PBBEMYKL,
RHBBMYKL,
SCBLMYKX,
UOVBMYKL,
OCBCMYKL,
}
impl TryFrom<BankNames> for BankCode {
type Error = Report<errors::ConnectorError>;
fn try_from(bank: BankNames) -> Result<Self, Self::Error> {
match bank {
BankNames::AffinBank => Ok(Self::PHBMMYKL),
BankNames::AgroBank => Ok(Self::AGOBMYK1),
BankNames::AllianceBank => Ok(Self::MFBBMYKL),
BankNames::AmBank => Ok(Self::ARBKMYKL),
BankNames::BankOfChina => Ok(Self::BKCHMYKL),
BankNames::BankIslam => Ok(Self::BIMBMYKL),
BankNames::BankMuamalat => Ok(Self::BMMBMYKL),
BankNames::BankRakyat => Ok(Self::BKRMMYK1),
BankNames::BankSimpananNasional => Ok(Self::BSNAMYK1),
BankNames::CimbBank => Ok(Self::CIBBMYKL),
BankNames::HongLeongBank => Ok(Self::HLBBMYKL),
BankNames::HsbcBank => Ok(Self::HBMBMYKL),
BankNames::KuwaitFinanceHouse => Ok(Self::KFHOMYKL),
BankNames::Maybank => Ok(Self::MBBEMYKL),
BankNames::PublicBank => Ok(Self::PBBEMYKL),
BankNames::RhbBank => Ok(Self::RHBBMYKL),
BankNames::StandardCharteredBank => Ok(Self::SCBLMYKX),
BankNames::UobBank => Ok(Self::UOVBMYKL),
BankNames::OcbcBank => Ok(Self::OCBCMYKL),
bank => Err(errors::ConnectorError::NotSupported {
message: format!("Invalid BankName for FPX Refund: {bank:?}"),
connector: "Fiuu",
})?,
}
}
}
impl TryFrom<BankNames> for FPXTxnChannel {
type Error = Report<errors::ConnectorError>;
fn try_from(bank_names: BankNames) -> Result<Self, Self::Error> {
match bank_names {
BankNames::AffinBank => Ok(Self::FpxAbb),
BankNames::AgroBank => Ok(Self::FpxAgrobank),
BankNames::AllianceBank => Ok(Self::FpxAbmb),
BankNames::AmBank => Ok(Self::FpxAmb),
BankNames::BankOfChina => Ok(Self::FpxBocm),
BankNames::BankIslam => Ok(Self::FpxBimb),
BankNames::BankMuamalat => Ok(Self::FpxBmmb),
BankNames::BankRakyat => Ok(Self::FpxBkrm),
BankNames::BankSimpananNasional => Ok(Self::FpxBsn),
BankNames::CimbBank => Ok(Self::FpxCimbclicks),
BankNames::HongLeongBank => Ok(Self::FpxHlb),
BankNames::HsbcBank => Ok(Self::FpxHsbc),
BankNames::KuwaitFinanceHouse => Ok(Self::FpxKfh),
BankNames::Maybank => Ok(Self::FpxMb2u),
BankNames::PublicBank => Ok(Self::FpxPbb),
BankNames::RhbBank => Ok(Self::FpxRhb),
BankNames::StandardCharteredBank => Ok(Self::FpxScb),
BankNames::UobBank => Ok(Self::FpxUob),
BankNames::OcbcBank => Ok(Self::FpxOcbc),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Fiuu"),
))?,
}
}
}
#[derive(Serialize, Debug, Clone)]
pub struct FiuuMandateRequest {
#[serde(rename = "0")]
mandate_request: Secret<String>,
}
#[derive(Serialize, Debug, Clone)]
pub struct FiuuRecurringRequest {
record_type: FiuuRecordType,
merchant_id: Secret<String>,
token: Secret<String>,
order_id: String,
currency: Currency,
amount: StringMajorUnit,
billing_name: Secret<String>,
email: Email,
verify_key: Secret<String>,
}
#[derive(Serialize, Debug, Clone, strum::Display)]
pub enum FiuuRecordType {
T,
}
impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuMandateRequest {
type Error = Report<errors::ConnectorError>;
fn try_from(item: &FiuuRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
let auth: FiuuAuthType = FiuuAuthType::try_from(&item.router_data.connector_auth_type)?;
let record_type = FiuuRecordType::T;
let merchant_id = auth.merchant_id;
let order_id = item.router_data.connector_request_reference_id.clone();
let currency = item.router_data.request.currency;
let amount = item.amount.clone();
let billing_name = item
.router_data
.request
.get_card_holder_name_from_additional_payment_method_data()?;
let email = item.router_data.get_billing_email()?;
let token = Secret::new(item.router_data.request.get_connector_mandate_id()?);
let verify_key = auth.verify_key;
let recurring_request = FiuuRecurringRequest {
record_type: record_type.clone(),
merchant_id: merchant_id.clone(),
token: token.clone(),
order_id: order_id.clone(),
currency,
amount: amount.clone(),
billing_name: billing_name.clone(),
email: email.clone(),
verify_key: verify_key.clone(),
};
let check_sum = calculate_check_sum(recurring_request)?;
let mandate_request = format!(
"{}|{}||{}|{}|{}|{}|{}|{}|||{}",
record_type,
merchant_id.peek(),
token.peek(),
order_id,
currency,
amount.get_amount_as_string(),
billing_name.peek(),
email.peek(),
check_sum.peek()
);
Ok(Self {
mandate_request: mandate_request.into(),
})
}
}
pub fn calculate_check_sum(
req: FiuuRecurringRequest,
) -> CustomResult<Secret<String>, errors::ConnectorError> {
let formatted_string = format!(
"{}{}{}{}{}{}{}",
req.record_type,
req.merchant_id.peek(),
req.token.peek(),
req.order_id,
req.currency,
req.amount.get_amount_as_string(),
req.verify_key.peek()
);
Ok(Secret::new(hex::encode(
crypto::Md5
.generate_digest(formatted_string.as_bytes())
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
)))
}
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuPaymentRequest {
#[serde(rename = "MerchantID")]
merchant_id: Secret<String>,
reference_no: String,
txn_type: TxnType,
txn_currency: Currency,
txn_amount: StringMajorUnit,
signature: Secret<String>,
#[serde(rename = "ReturnURL")]
return_url: Option<String>,
#[serde(rename = "NotificationURL")]
notification_url: Option<Url>,
#[serde(flatten)]
payment_method_data: FiuuPaymentMethodData,
}
#[derive(Serialize, Debug, Clone)]
#[serde(untagged)]
pub enum FiuuPaymentMethodData {
FiuuQRData(Box<FiuuQRData>),
FiuuCardData(Box<FiuuCardData>),
FiuuCardWithNTI(Box<FiuuCardWithNTI>),
FiuuFpxData(Box<FiuuFPXData>),
FiuuGooglePayData(Box<FiuuGooglePayData>),
FiuuApplePayData(Box<FiuuApplePayData>),
}
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuFPXData {
#[serde(rename = "non_3DS")]
non_3ds: i32,
txn_channel: FPXTxnChannel,
}
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuQRData {
txn_channel: TxnChannel,
}
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct FiuuCardData {
#[serde(rename = "non_3DS")]
non_3ds: i32,
#[serde(rename = "TxnChannel")]
txn_channel: TxnChannel,
cc_pan: CardNumber,
cc_cvv2: Secret<String>,
cc_month: Secret<String>,
cc_year: Secret<String>,
#[serde(rename = "mpstokenstatus")]
mps_token_status: Option<i32>,
#[serde(rename = "CustEmail")]
customer_email: Option<Email>,
}
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct FiuuCardWithNTI {
#[serde(rename = "TxnChannel")]
txn_channel: TxnChannel,
cc_pan: CardNumber,
cc_month: Secret<String>,
cc_year: Secret<String>,
#[serde(rename = "OriginalSchemeID")]
original_scheme_id: Secret<String>,
}
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct FiuuApplePayData {
#[serde(rename = "TxnChannel")]
txn_channel: TxnChannel,
cc_month: Secret<String>,
cc_year: Secret<String>,
cc_token: CardNumber,
eci: Option<String>,
token_cryptogram: Secret<String>,
token_type: FiuuTokenType,
#[serde(rename = "non_3DS")]
non_3ds: i32,
}
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "PascalCase")]
pub enum FiuuTokenType {
ApplePay,
GooglePay,
}
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuGooglePayData {
txn_channel: TxnChannel,
#[serde(rename = "GooglePay[apiVersion]")]
api_version: u8,
#[serde(rename = "GooglePay[apiVersionMinor]")]
api_version_minor: u8,
#[serde(rename = "GooglePay[paymentMethodData][info][assuranceDetails][accountVerified]")]
account_verified: Option<bool>,
#[serde(
rename = "GooglePay[paymentMethodData][info][assuranceDetails][cardHolderAuthenticated]"
)]
card_holder_authenticated: Option<bool>,
#[serde(rename = "GooglePay[paymentMethodData][info][cardDetails]")]
card_details: String,
#[serde(rename = "GooglePay[paymentMethodData][info][cardNetwork]")]
card_network: String,
#[serde(rename = "GooglePay[paymentMethodData][tokenizationData][token]")]
token: Secret<String>,
#[serde(rename = "GooglePay[paymentMethodData][tokenizationData][type]")]
tokenization_data_type: Secret<String>,
#[serde(rename = "GooglePay[paymentMethodData][type]")]
pm_type: String,
#[serde(rename = "SCREAMING_SNAKE_CASE")]
token_type: FiuuTokenType,
#[serde(rename = "non_3DS")]
non_3ds: i32,
}
pub fn calculate_signature(
signature_data: String,
) -> Result<Secret<String>, Report<errors::ConnectorError>> {
let message = signature_data.as_bytes();
let encoded_data = hex::encode(
crypto::Md5
.generate_digest(message)
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
);
Ok(Secret::new(encoded_data))
}
impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuPaymentRequest {
type Error = Report<errors::ConnectorError>;
fn try_from(item: &FiuuRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
let auth = FiuuAuthType::try_from(&item.router_data.connector_auth_type)?;
let merchant_id = auth.merchant_id.peek().to_string();
let txn_currency = item.router_data.request.currency;
let txn_amount = item.amount.clone();
let reference_no = item.router_data.connector_request_reference_id.clone();
let verify_key = auth.verify_key.peek().to_string();
let signature = calculate_signature(format!(
"{}{merchant_id}{reference_no}{verify_key}",
txn_amount.get_amount_as_string()
))?;
let txn_type = match item.router_data.request.is_auto_capture()? {
true => TxnType::Sals,
false => TxnType::Auts,
};
let return_url = item.router_data.request.router_return_url.clone();
let non_3ds = match item.router_data.is_three_ds() {
false => 1,
true => 0,
};
let notification_url = Some(
Url::parse(&item.router_data.request.get_webhook_url()?)
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
);
let payment_method_data = match item
.router_data
.request
.mandate_id
.clone()
.and_then(|mandate_id| mandate_id.mandate_reference_id)
{
None => match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref card) => {
FiuuPaymentMethodData::try_from((card, item.router_data))
}
PaymentMethodData::RealTimePayment(ref real_time_payment_data) => {
match *real_time_payment_data.clone() {
RealTimePaymentData::DuitNow {} => {
Ok(FiuuPaymentMethodData::FiuuQRData(Box::new(FiuuQRData {
txn_channel: TxnChannel::RppDuitNowQr,
})))
}
RealTimePaymentData::Fps {}
| RealTimePaymentData::PromptPay {}
| RealTimePaymentData::VietQr {}
| RealTimePaymentData::Qris {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiuu"),
)
.into())
}
}
}
PaymentMethodData::BankRedirect(ref bank_redirect_data) => match bank_redirect_data
{
BankRedirectData::OnlineBankingFpx { ref issuer } => {
Ok(FiuuPaymentMethodData::FiuuFpxData(Box::new(FiuuFPXData {
txn_channel: FPXTxnChannel::try_from(*issuer)?,
non_3ds,
})))
}
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Bizum {}
| BankRedirectData::Blik { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Eps { .. }
| BankRedirectData::Giropay { .. }
| BankRedirectData::Ideal { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::Sofort { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {}
| BankRedirectData::OpenBanking { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiuu"),
)
.into())
}
},
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletData::GooglePay(google_pay_data) => {
FiuuPaymentMethodData::try_from(google_pay_data)
}
WalletData::ApplePay(_apple_pay_data) => {
let payment_method_token = item.router_data.get_payment_method_token()?;
match payment_method_token {
PaymentMethodToken::Token(_) => {
Err(unimplemented_payment_method!("Apple Pay", "Manual", "Fiuu"))?
}
PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
FiuuPaymentMethodData::try_from(decrypt_data)
}
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Fiuu"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Fiuu"))?
}
}
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiuu"),
)
.into()),
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Reward
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiuu"),
)
.into())
}
},
// Card payments using network transaction ID
Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => {
match item.router_data.request.payment_method_data {
PaymentMethodData::CardDetailsForNetworkTransactionId(ref raw_card_details) => {
FiuuPaymentMethodData::try_from((raw_card_details, network_transaction_id))
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiuu"),
)
.into()),
}
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiuu"),
)
.into()),
}?;
Ok(Self {
merchant_id: auth.merchant_id,
reference_no,
txn_type,
txn_currency,
txn_amount,
return_url,
payment_method_data,
signature,
notification_url,
})
}
}
impl TryFrom<(&Card, &PaymentsAuthorizeRouterData)> for FiuuPaymentMethodData {
type Error = Report<errors::ConnectorError>;
fn try_from(
(req_card, item): (&Card, &PaymentsAuthorizeRouterData),
) -> Result<Self, Self::Error> {
let (mps_token_status, customer_email) =
if item.request.is_customer_initiated_mandate_payment() {
(Some(1), Some(item.get_billing_email()?))
} else {
(Some(3), None)
};
let non_3ds = match item.is_three_ds() {
false => 1,
true => 0,
};
Ok(Self::FiuuCardData(Box::new(FiuuCardData {
txn_channel: TxnChannel::Creditan,
non_3ds,
cc_pan: req_card.card_number.clone(),
cc_cvv2: req_card.card_cvc.clone(),
cc_month: req_card.card_exp_month.clone(),
cc_year: req_card.card_exp_year.clone(),
mps_token_status,
customer_email,
})))
}
}
impl TryFrom<(&CardDetailsForNetworkTransactionId, String)> for FiuuPaymentMethodData {
type Error = Report<errors::ConnectorError>;
fn try_from(
(raw_card_data, network_transaction_id): (&CardDetailsForNetworkTransactionId, String),
) -> Result<Self, Self::Error> {
Ok(Self::FiuuCardWithNTI(Box::new(FiuuCardWithNTI {
txn_channel: TxnChannel::Creditan,
cc_pan: raw_card_data.card_number.clone(),
cc_month: raw_card_data.card_exp_month.clone(),
cc_year: raw_card_data.card_exp_year.clone(),
original_scheme_id: Secret::new(network_transaction_id),
})))
}
}
impl TryFrom<&GooglePayWalletData> for FiuuPaymentMethodData {
type Error = Report<errors::ConnectorError>;
fn try_from(data: &GooglePayWalletData) -> Result<Self, Self::Error> {
Ok(Self::FiuuGooglePayData(Box::new(FiuuGooglePayData {
txn_channel: TxnChannel::Creditan,
api_version: GOOGLEPAY_API_VERSION,
api_version_minor: GOOGLEPAY_API_VERSION_MINOR,
account_verified: data
.info
.assurance_details
.as_ref()
.map(|details| details.account_verified),
card_holder_authenticated: data
.info
.assurance_details
.as_ref()
.map(|details| details.card_holder_authenticated),
card_details: data.info.card_details.clone(),
card_network: data.info.card_network.clone(),
token: data
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?
.clone()
.into(),
tokenization_data_type: data
.tokenization_data
.get_encrypted_token_type()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet token type",
})?
.clone()
.into(),
pm_type: data.pm_type.clone(),
token_type: FiuuTokenType::GooglePay,
// non_3ds field Applicable to card processing via specific processor using specific currency for pre-approved partner only.
// Equal to 0 by default and 1 for non-3DS transaction, That is why it is hardcoded to 1 for googlepay transactions.
non_3ds: 1,
})))
}
}
impl TryFrom<Box<ApplePayPredecryptData>> for FiuuPaymentMethodData {
type Error = Report<errors::ConnectorError>;
fn try_from(decrypt_data: Box<ApplePayPredecryptData>) -> Result<Self, Self::Error> {
Ok(Self::FiuuApplePayData(Box::new(FiuuApplePayData {
txn_channel: TxnChannel::Creditan,
cc_month: decrypt_data.get_expiry_month().change_context(
errors::ConnectorError::InvalidDataFormat {
field_name: "expiration_month",
},
)?,
cc_year: decrypt_data.get_four_digit_expiry_year(),
cc_token: decrypt_data.application_primary_account_number,
eci: decrypt_data.payment_data.eci_indicator,
token_cryptogram: decrypt_data.payment_data.online_payment_cryptogram,
token_type: FiuuTokenType::ApplePay,
// non_3ds field Applicable to card processing via specific processor using specific currency for pre-approved partner only.
// Equal to 0 by default and 1 for non-3DS transaction, That is why it is hardcoded to 1 for apple pay decrypt flow transactions.
non_3ds: 1,
})))
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PaymentsResponse {
pub reference_no: String,
#[serde(rename = "TxnID")]
pub txn_id: String,
pub txn_type: TxnType,
pub txn_currency: Currency,
pub txn_amount: StringMajorUnit,
pub txn_channel: String,
pub txn_data: TxnData,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct DuitNowQrCodeResponse {
pub reference_no: String,
pub txn_type: TxnType,
pub txn_currency: Currency,
pub txn_amount: StringMajorUnit,
pub txn_channel: String,
#[serde(rename = "TxnID")]
pub txn_id: String,
pub txn_data: QrTxnData,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct QrTxnData {
pub request_data: QrRequestData,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct QrRequestData {
pub qr_data: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FiuuPaymentsResponse {
PaymentResponse(Box<PaymentsResponse>),
QRPaymentResponse(Box<DuitNowQrCodeResponse>),
Error(FiuuErrorResponse),
RecurringResponse(Vec<Box<FiuuRecurringResponse>>),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FiuuRecurringResponse {
status: FiuuRecurringStautus,
#[serde(rename = "orderid")]
order_id: String,
#[serde(rename = "tranID")]
tran_id: Option<String>,
reason: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum FiuuRecurringStautus {
Accepted,
Failed,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct TxnData {
#[serde(rename = "RequestURL")]
pub request_url: String,
pub request_type: RequestType,
pub request_data: RequestData,
pub request_method: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum RequestType {
Redirect,
Response,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RequestData {
NonThreeDS(NonThreeDSResponseData),
RedirectData(Option<HashMap<String, String>>),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct QrCodeData {
#[serde(rename = "tranID")]
pub tran_id: String,
pub status: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NonThreeDSResponseData {
#[serde(rename = "tranID")]
pub tran_id: String,
pub status: String,
#[serde(rename = "extraP")]
pub extra_parameters: Option<ExtraParameters>,
pub error_code: Option<String>,
pub error_desc: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ExtraParameters {
pub token: Option<Secret<String>>,
}
impl TryFrom<PaymentsResponseRouterData<FiuuPaymentsResponse>> for PaymentsAuthorizeRouterData {
type Error = Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<FiuuPaymentsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
FiuuPaymentsResponse::QRPaymentResponse(ref response) => Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.txn_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: get_qr_metadata(response)?,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
}),
FiuuPaymentsResponse::Error(error) => Ok(Self {
response: Err(ErrorResponse {
code: error.error_code.clone(),
message: error.error_desc.clone(),
reason: Some(error.error_desc),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
FiuuPaymentsResponse::PaymentResponse(data) => match data.txn_data.request_data {
RequestData::RedirectData(redirection_data) => {
let redirection_data = Some(RedirectForm::Form {
endpoint: data.txn_data.request_url.to_string(),
method: if data.txn_data.request_method.as_str() == "POST" {
Method::Post
} else {
Method::Get
},
form_fields: redirection_data.unwrap_or_default(),
});
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(data.txn_id),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
RequestData::NonThreeDS(non_threeds_data) => {
let mandate_reference =
non_threeds_data
.extra_parameters
.as_ref()
.and_then(|extra_p| {
extra_p.token.as_ref().map(|token| MandateReference {
connector_mandate_id: Some(token.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})
});
let status = match non_threeds_data.status.as_str() {
"00" => {
if item.data.request.is_auto_capture()? {
Ok(enums::AttemptStatus::Charged)
} else {
Ok(enums::AttemptStatus::Authorized)
}
}
"11" => Ok(enums::AttemptStatus::Failure),
"22" => Ok(enums::AttemptStatus::Pending),
other => Err(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(other.to_owned()),
)),
}?;
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: non_threeds_data
.error_code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: non_threeds_data
.error_desc
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: non_threeds_data.error_desc.clone(),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(data.txn_id),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(data.txn_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
},
FiuuPaymentsResponse::RecurringResponse(ref recurring_response_vec) => {
let recurring_response_item = recurring_response_vec.first();
let router_data_response = match recurring_response_item {
Some(recurring_response) => {
let status =
common_enums::AttemptStatus::from(recurring_response.status.clone());
let connector_transaction_id = recurring_response
.tran_id
.as_ref()
.map_or(ResponseId::NoResponseId, |tran_id| {
ResponseId::ConnectorTransactionId(tran_id.clone())
});
let response = if status == common_enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: recurring_response
.reason
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: recurring_response
.reason
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: recurring_response.reason.clone(),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: recurring_response.tran_id.clone(),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: connector_transaction_id,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Self {
status,
response,
..item.data
}
}
None => {
// It is not expected to get empty response from the connnector, if we get we are not updating the payment response since we don't have any info in the authorize response.
let response = Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
});
Self {
response,
..item.data
}
}
};
Ok(router_data_response)
}
}
}
}
impl From<FiuuRecurringStautus> for common_enums::AttemptStatus {
fn from(status: FiuuRecurringStautus) -> Self {
match status {
FiuuRecurringStautus::Accepted => Self::Charged,
FiuuRecurringStautus::Failed => Self::Failure,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuRefundRequest {
pub refund_type: RefundType,
#[serde(rename = "MerchantID")]
pub merchant_id: Secret<String>,
#[serde(rename = "RefID")]
pub ref_id: String,
#[serde(rename = "TxnID")]
pub txn_id: String,
pub amount: StringMajorUnit,
pub signature: Secret<String>,
#[serde(rename = "notify_url")]
pub notify_url: Option<Url>,
}
#[derive(Debug, Serialize, Display)]
pub enum RefundType {
#[serde(rename = "P")]
#[strum(serialize = "P")]
Partial,
}
impl TryFrom<&FiuuRouterData<&RefundsRouterData<Execute>>> for FiuuRefundRequest {
type Error = Report<errors::ConnectorError>;
fn try_from(item: &FiuuRouterData<&RefundsRouterData<Execute>>) -> Result<Self, Self::Error> {
let auth: FiuuAuthType = FiuuAuthType::try_from(&item.router_data.connector_auth_type)?;
let merchant_id = auth.merchant_id.peek().to_string();
let txn_amount = item.amount.clone();
let reference_no = item.router_data.connector_request_reference_id.clone();
let txn_id = item.router_data.request.connector_transaction_id.clone();
let secret_key = auth.secret_key.peek().to_string();
Ok(Self {
refund_type: RefundType::Partial,
merchant_id: auth.merchant_id,
ref_id: reference_no.clone(),
txn_id: txn_id.clone(),
amount: txn_amount.clone(),
signature: calculate_signature(format!(
"{}{merchant_id}{reference_no}{txn_id}{}{secret_key}",
RefundType::Partial,
txn_amount.get_amount_as_string()
))?,
notify_url: Some(
Url::parse(&item.router_data.request.get_webhook_url()?)
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuRefundSuccessResponse {
#[serde(rename = "RefundID")]
refund_id: i64,
status: String,
#[serde(rename = "reason")]
reason: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FiuuRefundResponse {
Success(FiuuRefundSuccessResponse),
Error(FiuuErrorResponse),
}
impl TryFrom<RefundsResponseRouterData<Execute, FiuuRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, FiuuRefundResponse>,
) -> Result<Self, Self::Error> {
match item.response {
FiuuRefundResponse::Error(error) => Ok(Self {
response: Err(ErrorResponse {
code: error.error_code.clone(),
message: error.error_desc.clone(),
reason: Some(error.error_desc),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
FiuuRefundResponse::Success(refund_data) => {
let refund_status = match refund_data.status.as_str() {
"00" => Ok(enums::RefundStatus::Success),
"11" => Ok(enums::RefundStatus::Failure),
"22" => Ok(enums::RefundStatus::Pending),
other => Err(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(other.to_owned()),
)),
}?;
if refund_status == enums::RefundStatus::Failure {
Ok(Self {
response: Err(ErrorResponse {
code: refund_data.status.clone(),
message: refund_data
.reason
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: refund_data.reason.clone(),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(refund_data.refund_id.to_string()),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
} else {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: refund_data.refund_id.clone().to_string(),
refund_status,
}),
..item.data
})
}
}
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FiuuErrorResponse {
pub error_code: String,
pub error_desc: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FiuuPaymentSyncRequest {
amount: StringMajorUnit,
#[serde(rename = "txID")]
tx_id: String,
domain: String,
skey: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum FiuuPaymentResponse {
FiuuPaymentSyncResponse(FiuuPaymentSyncResponse),
FiuuWebhooksPaymentResponse(FiuuWebhooksPaymentResponse),
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuPaymentSyncResponse {
stat_code: StatCode,
stat_name: StatName,
#[serde(rename = "TranID")]
tran_id: String,
error_code: Option<String>,
error_desc: Option<String>,
#[serde(rename = "miscellaneous")]
miscellaneous: Option<HashMap<String, Secret<String>>>,
#[serde(rename = "SchemeTransactionID")]
scheme_transaction_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, Display, Clone, PartialEq)]
pub enum StatCode {
#[serde(rename = "00")]
Success,
#[serde(rename = "11")]
Failure,
#[serde(rename = "22")]
Pending,
}
#[derive(Debug, Serialize, Deserialize, Display, Clone, Copy, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum StatName {
Captured,
Settled,
Authorized,
Failed,
Cancelled,
Chargeback,
Release,
#[serde(rename = "reject/hold")]
RejectHold,
Blocked,
#[serde(rename = "ReqCancel")]
ReqCancel,
#[serde(rename = "ReqChargeback")]
ReqChargeback,
#[serde(rename = "Pending")]
Pending,
#[serde(rename = "Unknown")]
Unknown,
}
impl TryFrom<&PaymentsSyncRouterData> for FiuuPaymentSyncRequest {
type Error = Report<errors::ConnectorError>;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let auth = FiuuAuthType::try_from(&item.connector_auth_type)?;
let txn_id = item
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
let merchant_id = auth.merchant_id.peek().to_string();
let verify_key = auth.verify_key.peek().to_string();
let amount = StringMajorUnitForConnector
.convert(item.request.amount, item.request.currency)
.change_context(errors::ConnectorError::AmountConversionFailed)?;
Ok(Self {
amount: amount.clone(),
tx_id: txn_id.clone(),
domain: merchant_id.clone(),
skey: calculate_signature(format!(
"{txn_id}{merchant_id}{verify_key}{}",
amount.get_amount_as_string()
))?,
})
}
}
struct ErrorInputs {
encoded_data: Option<String>,
response_error_code: Option<String>,
response_error_desc: Option<String>,
}
struct ErrorDetails {
pub code: String,
pub message: String,
pub reason: Option<String>,
}
impl TryFrom<ErrorInputs> for ErrorDetails {
type Error = Report<errors::ConnectorError>;
fn try_from(value: ErrorInputs) -> Result<Self, Self::Error> {
let query_params = value
.encoded_data
.as_ref()
.map(|encoded_data| {
serde_urlencoded::from_str::<FiuuPaymentRedirectResponse>(encoded_data)
})
.transpose()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable("Failed to deserialize FiuuPaymentRedirectResponse")?;
let error_message = value
.response_error_desc
.as_ref()
.filter(|s| !s.is_empty())
.cloned()
.or_else(|| {
query_params
.as_ref()
.and_then(|qp| qp.error_desc.as_ref())
.filter(|s| !s.is_empty())
.cloned()
});
let error_code = value
.response_error_code
.as_ref()
.filter(|s| !s.is_empty())
.cloned()
.or_else(|| {
query_params
.as_ref()
.and_then(|qp| qp.error_code.as_ref())
.filter(|s| !s.is_empty())
.cloned()
})
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_owned());
Ok(Self {
code: error_code,
message: error_message
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_owned()),
reason: error_message,
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSyncRouterData {
type Error = Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<FiuuPaymentResponse>,
) -> Result<Self, Self::Error> {
match item.response {
FiuuPaymentResponse::FiuuPaymentSyncResponse(response) => {
let stat_name = response.stat_name;
let stat_code = response.stat_code.clone();
let txn_id = response.tran_id;
let status = enums::AttemptStatus::try_from(FiuuSyncStatus {
stat_name,
stat_code,
})?;
let error_response = if status == enums::AttemptStatus::Failure {
let error_details = ErrorDetails::try_from(ErrorInputs {
encoded_data: item.data.request.encoded_data.clone(),
response_error_code: response.error_code.clone(),
response_error_desc: response.error_desc.clone(),
})?;
Some(ErrorResponse {
status_code: item.http_code,
code: error_details.code,
message: error_details.message,
reason: error_details.reason,
attempt_status: Some(enums::AttemptStatus::Failure),
connector_transaction_id: Some(txn_id.clone()),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(txn_id.clone().to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: response
.scheme_transaction_id
.as_ref()
.map(|id| id.clone().expose()),
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
};
Ok(Self {
status,
response: error_response.map_or_else(|| Ok(payments_response_data), Err),
..item.data
})
}
FiuuPaymentResponse::FiuuWebhooksPaymentResponse(response) => {
let status = enums::AttemptStatus::try_from(FiuuWebhookStatus {
capture_method: item.data.request.capture_method,
status: response.status,
})?;
let txn_id = response.tran_id;
let mandate_reference = response.extra_parameters.as_ref().and_then(|extra_p| {
let mandate_token: Result<ExtraParameters, _> = serde_json::from_str(&extra_p.clone().expose());
match mandate_token {
Ok(token) => {
token.token.as_ref().map(|token| MandateReference {
connector_mandate_id: Some(token.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id:None
})
}
Err(err) => {
router_env::logger::warn!(
"Failed to convert 'extraP' from fiuu webhook response to fiuu::ExtraParameters. \
Input: '{:?}', Error: {}",
extra_p,
err
);
None
}
}
});
let error_response = if status == enums::AttemptStatus::Failure {
let error_details = ErrorDetails::try_from(ErrorInputs {
encoded_data: item.data.request.encoded_data.clone(),
response_error_code: response.error_code.clone(),
response_error_desc: response.error_desc.clone(),
})?;
Some(ErrorResponse {
status_code: item.http_code,
code: error_details.code,
message: error_details.message,
reason: error_details.reason,
attempt_status: Some(enums::AttemptStatus::Failure),
connector_transaction_id: Some(txn_id.clone()),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(txn_id.clone().to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
};
Ok(Self {
status,
response: error_response.map_or_else(|| Ok(payments_response_data), Err),
..item.data
})
}
}
}
}
pub struct FiuuWebhookStatus {
pub capture_method: Option<CaptureMethod>,
pub status: FiuuPaymentWebhookStatus,
}
impl TryFrom<FiuuWebhookStatus> for enums::AttemptStatus {
type Error = Report<errors::ConnectorError>;
fn try_from(webhook_status: FiuuWebhookStatus) -> Result<Self, Self::Error> {
match webhook_status.status {
FiuuPaymentWebhookStatus::Success => match webhook_status.capture_method {
Some(CaptureMethod::Automatic) | Some(CaptureMethod::SequentialAutomatic) => {
Ok(Self::Charged)
}
Some(CaptureMethod::Manual) => Ok(Self::Authorized),
_ => Err(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(webhook_status.status.to_string()),
))?,
},
FiuuPaymentWebhookStatus::Failure => Ok(Self::Failure),
FiuuPaymentWebhookStatus::Pending => Ok(Self::AuthenticationPending),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentCaptureRequest {
domain: String,
#[serde(rename = "tranID")]
tran_id: String,
amount: StringMajorUnit,
#[serde(rename = "RefID")]
ref_id: String,
skey: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PaymentCaptureResponse {
#[serde(rename = "TranID")]
tran_id: String,
stat_code: String,
}
pub struct FiuuSyncStatus {
pub stat_name: StatName,
pub stat_code: StatCode,
}
impl TryFrom<FiuuSyncStatus> for enums::AttemptStatus {
type Error = errors::ConnectorError;
fn try_from(sync_status: FiuuSyncStatus) -> Result<Self, Self::Error> {
match (sync_status.stat_code, sync_status.stat_name) {
(StatCode::Success, StatName::Captured | StatName::Settled) => Ok(Self::Charged), // For Success as StatCode we can only expect Captured,Settled and Authorized as StatName.
(StatCode::Success, StatName::Authorized) => Ok(Self::Authorized),
(StatCode::Pending, StatName::Pending) => Ok(Self::AuthenticationPending), // For Pending as StatCode we can only expect Pending and Unknown as StatName.
(StatCode::Pending, StatName::Unknown) => Ok(Self::Pending),
(StatCode::Failure, StatName::Cancelled) | (StatCode::Failure, StatName::ReqCancel) => {
Ok(Self::Voided)
}
(StatCode::Failure, _) => Ok(Self::Failure),
(other, _) => Err(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(other.to_string()),
)),
}
}
}
impl TryFrom<&FiuuRouterData<&PaymentsCaptureRouterData>> for PaymentCaptureRequest {
type Error = Report<errors::ConnectorError>;
fn try_from(item: &FiuuRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let auth = FiuuAuthType::try_from(&item.router_data.connector_auth_type)?;
let merchant_id = auth.merchant_id.peek().to_string();
let amount = item.amount.clone();
let txn_id = item.router_data.request.connector_transaction_id.clone();
let verify_key = auth.verify_key.peek().to_string();
let signature = calculate_signature(format!(
"{txn_id}{}{merchant_id}{verify_key}",
amount.get_amount_as_string()
))?;
Ok(Self {
domain: merchant_id,
tran_id: txn_id,
amount,
ref_id: item.router_data.connector_request_reference_id.clone(),
skey: signature,
})
}
}
fn capture_status_codes() -> HashMap<&'static str, &'static str> {
[
("00", "Capture successful"),
("11", "Capture failed"),
("12", "Invalid or unmatched security hash string"),
("13", "Not a credit card transaction"),
("15", "Requested day is on settlement day"),
("16", "Forbidden transaction"),
("17", "Transaction not found"),
("18", "Missing required parameter"),
("19", "Domain not found"),
("20", "Temporary out of service"),
("21", "Authorization expired"),
("23", "Partial capture not allowed"),
("24", "Transaction already captured"),
("25", "Requested amount exceeds available capture amount"),
("99", "General error (contact payment gateway support)"),
]
.into_iter()
.collect()
}
impl TryFrom<PaymentsCaptureResponseRouterData<PaymentCaptureResponse>>
for PaymentsCaptureRouterData
{
type Error = Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<PaymentCaptureResponse>,
) -> Result<Self, Self::Error> {
let status_code = item.response.stat_code;
let status = match status_code.as_str() {
"00" => Ok(enums::AttemptStatus::Charged),
"22" => Ok(enums::AttemptStatus::Pending),
"11" | "12" | "13" | "15" | "16" | "17" | "18" | "19" | "20" | "21" | "23" | "24"
| "25" | "99" => Ok(enums::AttemptStatus::Failure),
other => Err(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(other.to_owned()),
)),
}?;
let capture_message_status = capture_status_codes();
let error_response = if status == enums::AttemptStatus::Failure {
let optional_message = capture_message_status
.get(status_code.as_str())
.copied()
.map(String::from);
Some(ErrorResponse {
status_code: item.http_code,
code: status_code.to_owned(),
message: optional_message
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: optional_message,
attempt_status: None,
connector_transaction_id: Some(item.response.tran_id.clone()),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.tran_id.clone().to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
};
Ok(Self {
status,
response: error_response.map_or_else(|| Ok(payments_response_data), Err),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FiuuPaymentCancelRequest {
#[serde(rename = "txnID")]
txn_id: String,
domain: String,
skey: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuPaymentCancelResponse {
#[serde(rename = "TranID")]
tran_id: String,
stat_code: String,
#[serde(rename = "miscellaneous")]
miscellaneous: Option<HashMap<String, Secret<String>>>,
}
impl TryFrom<&PaymentsCancelRouterData> for FiuuPaymentCancelRequest {
type Error = Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let auth = FiuuAuthType::try_from(&item.connector_auth_type)?;
let txn_id = item.request.connector_transaction_id.clone();
let merchant_id = auth.merchant_id.peek().to_string();
let secret_key = auth.secret_key.peek().to_string();
Ok(Self {
txn_id: txn_id.clone(),
domain: merchant_id.clone(),
skey: calculate_signature(format!("{txn_id}{merchant_id}{secret_key}"))?,
})
}
}
fn void_status_codes() -> HashMap<&'static str, &'static str> {
[
("00", "Success (will proceed the request)"),
("11", "Failure"),
("12", "Invalid or unmatched security hash string"),
("13", "Not a refundable transaction"),
("14", "Transaction date more than 180 days"),
("15", "Requested day is on settlement day"),
("16", "Forbidden transaction"),
("17", "Transaction not found"),
("18", "Duplicate partial refund request"),
("19", "Merchant not found"),
("20", "Missing required parameter"),
(
"21",
"Transaction must be in authorized/captured/settled status",
),
]
.into_iter()
.collect()
}
impl TryFrom<PaymentsCancelResponseRouterData<FiuuPaymentCancelResponse>>
for PaymentsCancelRouterData
{
type Error = Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<FiuuPaymentCancelResponse>,
) -> Result<Self, Self::Error> {
let status_code = item.response.stat_code;
let status = match status_code.as_str() {
"00" => Ok(enums::AttemptStatus::Voided),
"11" | "12" | "13" | "14" | "15" | "16" | "17" | "18" | "19" | "20" | "21" => {
Ok(enums::AttemptStatus::VoidFailed)
}
other => Err(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(other.to_owned()),
)),
}?;
let void_message_status = void_status_codes();
let error_response = if status == enums::AttemptStatus::VoidFailed {
let optional_message = void_message_status
.get(status_code.as_str())
.copied()
.map(String::from);
Some(ErrorResponse {
status_code: item.http_code,
code: status_code.to_owned(),
message: optional_message
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: optional_message,
attempt_status: None,
connector_transaction_id: Some(item.response.tran_id.clone()),
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.tran_id.clone().to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
};
Ok(Self {
status,
response: error_response.map_or_else(|| Ok(payments_response_data), Err),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuRefundSyncRequest {
#[serde(rename = "TxnID")]
txn_id: String,
#[serde(rename = "MerchantID")]
merchant_id: Secret<String>,
signature: Secret<String>,
}
impl TryFrom<&RefundSyncRouterData> for FiuuRefundSyncRequest {
type Error = Report<errors::ConnectorError>;
fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> {
let auth = FiuuAuthType::try_from(&item.connector_auth_type)?;
let (txn_id, merchant_id, verify_key) = (
item.request.connector_transaction_id.clone(),
auth.merchant_id.peek().to_string(),
auth.verify_key.peek().to_string(),
);
let signature = calculate_signature(format!("{txn_id}{merchant_id}{verify_key}"))?;
Ok(Self {
txn_id,
merchant_id: auth.merchant_id,
signature,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FiuuRefundSyncResponse {
Success(Vec<RefundData>),
Error(FiuuErrorResponse),
Webhook(FiuuWebhooksRefundResponse),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct RefundData {
#[serde(rename = "RefundID")]
refund_id: String,
status: RefundStatus,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RefundStatus {
Success,
Pending,
Rejected,
Processing,
}
impl TryFrom<RefundsResponseRouterData<RSync, FiuuRefundSyncResponse>>
for RefundsRouterData<RSync>
{
type Error = Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, FiuuRefundSyncResponse>,
) -> Result<Self, Self::Error> {
match item.response {
FiuuRefundSyncResponse::Error(error) => Ok(Self {
response: Err(ErrorResponse {
code: error.error_code.clone(),
message: error.error_desc.clone(),
reason: Some(error.error_desc),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
FiuuRefundSyncResponse::Success(refund_data) => {
let refund = refund_data
.iter()
.find(|refund| {
Some(refund.refund_id.clone()) == item.data.request.connector_refund_id
})
.ok_or_else(|| errors::ConnectorError::MissingConnectorRefundID)?;
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: refund.refund_id.clone(),
refund_status: enums::RefundStatus::from(refund.status.clone()),
}),
..item.data
})
}
FiuuRefundSyncResponse::Webhook(fiuu_webhooks_refund_response) => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: fiuu_webhooks_refund_response.refund_id,
refund_status: enums::RefundStatus::from(
fiuu_webhooks_refund_response.status.clone(),
),
}),
..item.data
}),
}
}
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Pending => Self::Pending,
RefundStatus::Success => Self::Success,
RefundStatus::Rejected => Self::Failure,
RefundStatus::Processing => Self::Pending,
}
}
}
pub fn get_qr_metadata(
response: &DuitNowQrCodeResponse,
) -> CustomResult<Option<serde_json::Value>, errors::ConnectorError> {
let image_data = QrImage::new_colored_from_data(
response.txn_data.request_data.qr_data.peek().clone(),
constants::DUIT_NOW_BRAND_COLOR,
)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let image_data_url = Url::parse(image_data.data.clone().as_str()).ok();
let display_to_timestamp = None;
if let Some(color_image_data_url) = image_data_url {
let qr_code_info = payments::QrCodeInformation::QrColorDataUrl {
color_image_data_url,
display_to_timestamp,
display_text: Some(constants::DUIT_NOW_BRAND_TEXT.to_string()),
border_color: Some(constants::DUIT_NOW_BRAND_COLOR.to_string()),
};
Some(qr_code_info.encode_to_value())
.transpose()
.change_context(errors::ConnectorError::ResponseHandlingFailed)
} else {
Ok(None)
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum FiuuWebhooksResponse {
FiuuWebhookPaymentResponse(FiuuWebhooksPaymentResponse),
FiuuWebhookRefundResponse(FiuuWebhooksRefundResponse),
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct FiuuWebhooksPaymentResponse {
pub skey: Secret<String>,
pub status: FiuuPaymentWebhookStatus,
#[serde(rename = "orderid")]
pub order_id: String,
#[serde(rename = "tranID")]
pub tran_id: String,
pub nbcb: String,
pub amount: StringMajorUnit,
pub currency: String,
pub domain: Secret<String>,
pub appcode: Option<Secret<String>>,
pub paydate: String,
pub channel: String,
pub error_desc: Option<String>,
pub error_code: Option<String>,
#[serde(rename = "extraP")]
pub extra_parameters: Option<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct FiuuPaymentRedirectResponse {
pub skey: Secret<String>,
#[serde(rename = "tranID")]
pub tran_id: String,
pub status: FiuuPaymentWebhookStatus,
pub appcode: Option<String>,
pub error_code: Option<String>,
pub error_desc: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuWebhooksRefundResponse {
pub refund_type: FiuuWebhooksRefundType,
#[serde(rename = "MerchantID")]
pub merchant_id: Secret<String>,
#[serde(rename = "RefID")]
pub ref_id: String,
#[serde(rename = "RefundID")]
pub refund_id: String,
#[serde(rename = "TxnID")]
pub txn_id: String,
pub amount: StringMajorUnit,
pub status: FiuuRefundsWebhookStatus,
pub signature: Secret<String>,
}
#[derive(Debug, Deserialize, Serialize, Clone, strum::Display)]
pub enum FiuuRefundsWebhookStatus {
#[strum(serialize = "00")]
#[serde(rename = "00")]
RefundSuccess,
#[strum(serialize = "11")]
#[serde(rename = "11")]
RefundFailure,
#[strum(serialize = "22")]
#[serde(rename = "22")]
RefundPending,
}
#[derive(Debug, Deserialize, Serialize, Clone, strum::Display)]
pub enum FiuuWebhooksRefundType {
P,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct FiuuWebhookSignature {
pub skey: Secret<String>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct FiuuWebhookResourceId {
pub skey: Secret<String>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct FiuWebhookEvent {
pub status: FiuuPaymentWebhookStatus,
}
#[derive(Debug, Deserialize, Serialize, Clone, strum::Display)]
pub enum FiuuPaymentWebhookStatus {
#[strum(serialize = "00")]
#[serde(rename = "00")]
Success,
#[strum(serialize = "11")]
#[serde(rename = "11")]
Failure,
#[strum(serialize = "22")]
#[serde(rename = "22")]
Pending,
}
impl From<FiuuPaymentWebhookStatus> for StatCode {
fn from(value: FiuuPaymentWebhookStatus) -> Self {
match value {
FiuuPaymentWebhookStatus::Success => Self::Success,
FiuuPaymentWebhookStatus::Failure => Self::Failure,
FiuuPaymentWebhookStatus::Pending => Self::Pending,
}
}
}
impl From<FiuuPaymentWebhookStatus> for api_models::webhooks::IncomingWebhookEvent {
fn from(value: FiuuPaymentWebhookStatus) -> Self {
match value {
FiuuPaymentWebhookStatus::Success => Self::PaymentIntentSuccess,
FiuuPaymentWebhookStatus::Failure => Self::PaymentIntentFailure,
FiuuPaymentWebhookStatus::Pending => Self::PaymentIntentProcessing,
}
}
}
impl From<FiuuRefundsWebhookStatus> for api_models::webhooks::IncomingWebhookEvent {
fn from(value: FiuuRefundsWebhookStatus) -> Self {
match value {
FiuuRefundsWebhookStatus::RefundSuccess => Self::RefundSuccess,
FiuuRefundsWebhookStatus::RefundFailure => Self::RefundFailure,
FiuuRefundsWebhookStatus::RefundPending => Self::EventNotSupported,
}
}
}
impl From<FiuuRefundsWebhookStatus> for enums::RefundStatus {
fn from(value: FiuuRefundsWebhookStatus) -> Self {
match value {
FiuuRefundsWebhookStatus::RefundFailure => Self::Failure,
FiuuRefundsWebhookStatus::RefundSuccess => Self::Success,
FiuuRefundsWebhookStatus::RefundPending => Self::Pending,
}
}
}
|
crates__hyperswitch_connectors__src__connectors__flexiti.rs
|
pub mod transformers;
use std::sync::LazyLock;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::PeekInterface;
use transformers as flexiti;
use uuid::Uuid;
use crate::{
capture_method_not_supported,
constants::headers,
types::{RefreshTokenRouterData, ResponseRouterData},
utils,
};
#[derive(Clone)]
pub struct Flexiti {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Flexiti {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Flexiti {}
impl api::PaymentSession for Flexiti {}
impl api::ConnectorAccessToken for Flexiti {}
impl api::MandateSetup for Flexiti {}
impl api::PaymentAuthorize for Flexiti {}
impl api::PaymentSync for Flexiti {}
impl api::PaymentCapture for Flexiti {}
impl api::PaymentVoid for Flexiti {}
impl api::Refund for Flexiti {}
impl api::RefundExecute for Flexiti {}
impl api::RefundSync for Flexiti {}
impl api::PaymentToken for Flexiti {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Flexiti
{
// Not Implemented (R)
}
impl Flexiti {
fn get_default_header() -> (String, masking::Maskable<String>) {
(
"x-reference-id".to_string(),
Uuid::new_v4().to_string().into(),
)
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Flexiti
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let access_token = req
.access_token
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let mut header = vec![(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", access_token.token.peek()).into(),
)];
header.push(Self::get_default_header());
Ok(header)
}
}
impl ConnectorCommon for Flexiti {
fn id(&self) -> &'static str {
"flexiti"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.flexiti.base_url.as_ref()
}
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: flexiti::FlexitiErrorResponse = res
.response
.parse_struct("FlexitiErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.to_owned(),
message: response.message.to_owned(),
reason: Some(response.message.to_owned()),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Flexiti {
fn validate_mandate_payment(
&self,
_pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
match pm_data {
PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
"validate_mandate_payment does not support cards".to_string(),
)
.into()),
_ => Ok(()),
}
}
fn validate_connector_against_payment_request(
&self,
capture_method: Option<common_enums::CaptureMethod>,
_payment_method: common_enums::PaymentMethod,
pmt: Option<common_enums::PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
match capture_method {
enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::Automatic
| enums::CaptureMethod::SequentialAutomatic
| enums::CaptureMethod::ManualMultiple
| enums::CaptureMethod::Scheduled => {
let connector = self.id();
match pmt {
Some(payment_method_type) => {
capture_method_not_supported!(
connector,
capture_method,
payment_method_type
)
}
None => capture_method_not_supported!(connector, capture_method),
}
}
}
}
fn validate_psync_reference_id(
&self,
_data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
Ok(())
}
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Flexiti {
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}oauth/token", self.base_url(connectors)))
}
fn get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn get_headers(
&self,
_req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![(Self::get_default_header())])
}
fn get_request_body(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = flexiti::FlexitiAccessTokenRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let req = Some(
RequestBuilder::new()
.method(Method::Post)
.attach_default_headers()
.headers(types::RefreshTokenType::get_headers(self, req, connectors)?)
.url(&types::RefreshTokenType::get_url(self, req, connectors)?)
.set_body(types::RefreshTokenType::get_request_body(
self, req, connectors,
)?)
.build(),
);
Ok(req)
}
fn handle_response(
&self,
data: &RefreshTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
let response: flexiti::FlexitiAccessTokenResponse = res
.response
.parse_struct("FlexitiAccessTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Flexiti {
//TODO: implement sessions flow
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Flexiti {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Flexiti {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth_details = flexiti::FlexitiAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
"{}online/v2/client-id/{:?}/systems/init",
self.base_url(connectors),
auth_details.client_id.peek()
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = flexiti::FlexitiRouterData::from((amount, req));
let connector_req = flexiti::FlexitiPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: flexiti::FlexitiPaymentsResponse = res
.response
.parse_struct("Flexiti PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Flexiti {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth_details = flexiti::FlexitiAuthType::try_from(&req.connector_auth_type.to_owned())?;
let order_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(format!(
"{}online/client-id/{}/notifications/order-id/{}",
self.base_url(connectors),
auth_details.client_id.peek(),
order_id
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: flexiti::FlexitiSyncResponse = res
.response
.parse_struct("flexiti FlexitiSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Flexiti {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: flexiti::FlexitiPaymentsResponse = res
.response
.parse_struct("Flexiti PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Flexiti {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Flexiti {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = flexiti::FlexitiRouterData::from((refund_amount, req));
let connector_req = flexiti::FlexitiRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: flexiti::RefundResponse = res
.response
.parse_struct("flexiti RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Flexiti {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: flexiti::RefundResponse = res
.response
.parse_struct("flexiti RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Flexiti {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static FLEXITI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![enums::CaptureMethod::Manual];
let mut flexiti_supported_payment_methods = SupportedPaymentMethods::new();
flexiti_supported_payment_methods.add(
enums::PaymentMethod::PayLater,
enums::PaymentMethodType::Klarna,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods,
specific_features: None,
},
);
flexiti_supported_payment_methods
});
static FLEXITI_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Flexiti",
description: "Flexiti connector",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static FLEXITI_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Flexiti {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&FLEXITI_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*FLEXITI_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&FLEXITI_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__forte.rs
|
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts::NO_ERROR_CODE,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},
};
use masking::{Mask, PeekInterface};
use transformers as forte;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{convert_amount, PaymentsSyncRequestData, RefundsRequestData},
};
#[derive(Clone)]
pub struct Forte {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Forte {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Forte {}
impl api::PaymentSession for Forte {}
impl api::ConnectorAccessToken for Forte {}
impl api::MandateSetup for Forte {}
impl api::PaymentAuthorize for Forte {}
impl api::PaymentSync for Forte {}
impl api::PaymentCapture for Forte {}
impl api::PaymentVoid for Forte {}
impl api::Refund for Forte {}
impl api::RefundExecute for Forte {}
impl api::RefundSync for Forte {}
impl api::PaymentToken for Forte {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Forte
{
}
pub const AUTH_ORG_ID_HEADER: &str = "X-Forte-Auth-Organization-Id";
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Forte
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let content_type = ConnectorCommon::common_get_content_type(self);
let mut common_headers = self.get_auth_header(&req.connector_auth_type)?;
common_headers.push((
headers::CONTENT_TYPE.to_string(),
content_type.to_string().into(),
));
Ok(common_headers)
}
}
impl ConnectorCommon for Forte {
fn id(&self) -> &'static str {
"forte"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.forte.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = forte::ForteAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let raw_basic_token = format!(
"{}:{}",
auth.api_access_id.peek(),
auth.api_secret_key.peek()
);
let basic_token = format!("Basic {}", BASE64_ENGINE.encode(raw_basic_token));
Ok(vec![
(
headers::AUTHORIZATION.to_string(),
basic_token.into_masked(),
),
(
AUTH_ORG_ID_HEADER.to_string(),
auth.organization_id.into_masked(),
),
])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: forte::ForteErrorResponse = res
.response
.parse_struct("Forte ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let message = response.response.response_desc;
let code = response
.response
.response_code
.unwrap_or_else(|| NO_ERROR_CODE.to_string());
Ok(ErrorResponse {
status_code: res.status_code,
code,
message,
reason: None,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Forte {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Forte {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Forte {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Forte {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Forte".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Forte {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
"{}/organizations/{}/locations/{}/transactions",
self.base_url(connectors),
auth.organization_id.peek(),
auth.location_id.peek()
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = forte::ForteRouterData::from((amount, req));
let connector_req = forte::FortePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: forte::FortePaymentsResponse = res
.response
.parse_struct("Forte AuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Forte {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
let txn_id = PaymentsSyncRequestData::get_connector_transaction_id(&req.request)
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/organizations/{}/locations/{}/transactions/{}",
self.base_url(connectors),
auth.organization_id.peek(),
auth.location_id.peek(),
txn_id
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: forte::FortePaymentsSyncResponse = res
.response
.parse_struct("forte PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Forte {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
"{}/organizations/{}/locations/{}/transactions",
self.base_url(connectors),
auth.organization_id.peek(),
auth.location_id.peek()
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = forte::ForteCaptureRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Put)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: forte::ForteCaptureResponse = res
.response
.parse_struct("Forte PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Forte {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
"{}/organizations/{}/locations/{}/transactions/{}",
self.base_url(connectors),
auth.organization_id.peek(),
auth.location_id.peek(),
req.request.connector_transaction_id
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = forte::ForteCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Put)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: forte::ForteCancelResponse = res
.response
.parse_struct("forte CancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Forte {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
"{}/organizations/{}/locations/{}/transactions",
self.base_url(connectors),
auth.organization_id.peek(),
auth.location_id.peek()
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = forte::ForteRouterData::from((refund_amount, req));
let connector_req = forte::ForteRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: forte::RefundResponse = res
.response
.parse_struct("forte RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Forte {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
"{}/organizations/{}/locations/{}/transactions/{}",
self.base_url(connectors),
auth.organization_id.peek(),
auth.location_id.peek(),
req.request.get_connector_refund_id()?
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: forte::RefundSyncResponse = res
.response
.parse_struct("forte RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Forte {
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
Ok(IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static FORTE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
];
let mut forte_supported_payment_methods = SupportedPaymentMethods::new();
forte_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
forte_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
forte_supported_payment_methods
});
static FORTE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Forte",
description:
"CSG Forte offers a unified payments platform, enabling businesses to securely process credit cards, debit cards, ACH/eCheck transactions, and more, with advanced fraud prevention and seamless integration.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static FORTE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Forte {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&FORTE_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*FORTE_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&FORTE_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__forte__transformers.rs
|
use cards::CardNumber;
use common_enums::enums;
use common_utils::types::FloatMajorUnit;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{PaymentsCaptureResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, CardData as _PaymentsAuthorizeRequestData,
PaymentsAuthorizeRequestData, RouterData as _,
},
};
#[derive(Debug, Serialize)]
pub struct ForteRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for ForteRouterData<T> {
fn from((amount, router_data): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Serialize)]
pub struct FortePaymentsRequest {
action: ForteAction,
authorization_amount: FloatMajorUnit,
billing_address: BillingAddress,
card: Card,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BillingAddress {
first_name: Secret<String>,
last_name: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct Card {
card_type: ForteCardType,
name_on_card: Secret<String>,
account_number: CardNumber,
expire_month: Secret<String>,
expire_year: Secret<String>,
card_verification_value: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ForteCardType {
Visa,
MasterCard,
Amex,
Discover,
DinersClub,
Jcb,
}
impl TryFrom<utils::CardIssuer> for ForteCardType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(issuer: utils::CardIssuer) -> Result<Self, Self::Error> {
match issuer {
utils::CardIssuer::AmericanExpress => Ok(Self::Amex),
utils::CardIssuer::Master => Ok(Self::MasterCard),
utils::CardIssuer::Discover => Ok(Self::Discover),
utils::CardIssuer::Visa => Ok(Self::Visa),
utils::CardIssuer::DinersClub => Ok(Self::DinersClub),
utils::CardIssuer::JCB => Ok(Self::Jcb),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Forte"),
)
.into()),
}
}
}
impl TryFrom<&ForteRouterData<&types::PaymentsAuthorizeRouterData>> for FortePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item_data: &ForteRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let item = item_data.router_data;
match item.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => {
if item.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Cards 3DS".to_string(),
connector: "Forte",
})?
}
let action = match item.request.is_auto_capture()? {
true => ForteAction::Sale,
false => ForteAction::Authorize,
};
let card_type = ForteCardType::try_from(ccard.get_card_issuer()?)?;
let address = item.get_billing_address()?;
let card = Card {
card_type,
name_on_card: item
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string())),
account_number: ccard.card_number.clone(),
expire_month: ccard.card_exp_month.clone(),
expire_year: ccard.card_exp_year.clone(),
card_verification_value: ccard.card_cvc.clone(),
};
let first_name = address.get_first_name()?;
let billing_address = BillingAddress {
first_name: first_name.clone(),
last_name: address.get_last_name().unwrap_or(first_name).clone(),
};
let authorization_amount = item_data.amount;
Ok(Self {
action,
authorization_amount,
billing_address,
card,
})
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Forte"),
))?
}
}
}
}
// Auth Struct
pub struct ForteAuthType {
pub(super) api_access_id: Secret<String>,
pub(super) organization_id: Secret<String>,
pub(super) location_id: Secret<String>,
pub(super) api_secret_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for ForteAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Ok(Self {
api_access_id: api_key.to_owned(),
organization_id: Secret::new(format!("org_{}", key1.peek())),
location_id: Secret::new(format!("loc_{}", key2.peek())),
api_secret_key: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
}
// PaymentsResponse
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum FortePaymentStatus {
Complete,
Failed,
Authorized,
Ready,
Voided,
Settled,
}
impl From<FortePaymentStatus> for enums::AttemptStatus {
fn from(item: FortePaymentStatus) -> Self {
match item {
FortePaymentStatus::Complete | FortePaymentStatus::Settled => Self::Charged,
FortePaymentStatus::Failed => Self::Failure,
FortePaymentStatus::Ready => Self::Pending,
FortePaymentStatus::Authorized => Self::Authorized,
FortePaymentStatus::Voided => Self::Voided,
}
}
}
fn get_status(response_code: ForteResponseCode, action: ForteAction) -> enums::AttemptStatus {
match response_code {
ForteResponseCode::A01 => match action {
ForteAction::Authorize => enums::AttemptStatus::Authorized,
ForteAction::Sale => enums::AttemptStatus::Pending,
ForteAction::Verify | ForteAction::Capture => enums::AttemptStatus::Charged,
},
ForteResponseCode::A05 | ForteResponseCode::A06 => enums::AttemptStatus::Authorizing,
_ => enums::AttemptStatus::Failure,
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CardResponse {
pub name_on_card: Option<Secret<String>>,
pub last_4_account_number: String,
pub masked_account_number: String,
pub card_type: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub enum ForteResponseCode {
A01,
A05,
A06,
U13,
U14,
U18,
U20,
}
impl From<ForteResponseCode> for enums::AttemptStatus {
fn from(item: ForteResponseCode) -> Self {
match item {
ForteResponseCode::A01 | ForteResponseCode::A05 | ForteResponseCode::A06 => {
Self::Pending
}
_ => Self::Failure,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ResponseStatus {
pub environment: String,
pub response_type: String,
pub response_code: ForteResponseCode,
pub response_desc: String,
pub authorization_code: String,
pub avs_result: Option<String>,
pub cvv_result: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ForteAction {
Sale,
Authorize,
Verify,
Capture,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct FortePaymentsResponse {
pub transaction_id: String,
pub location_id: Secret<String>,
pub action: ForteAction,
pub authorization_amount: Option<FloatMajorUnit>,
pub authorization_code: String,
pub entered_by: String,
pub billing_address: Option<BillingAddress>,
pub card: Option<CardResponse>,
pub response: ResponseStatus,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ForteMeta {
pub auth_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, FortePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FortePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response_code = item.response.response.response_code;
let action = item.response.action;
let transaction_id = &item.response.transaction_id;
Ok(Self {
status: get_status(response_code, action),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(ForteMeta {
auth_id: item.response.authorization_code,
})),
network_txn_id: None,
connector_response_reference_id: Some(transaction_id.to_string()),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
//PsyncResponse
#[derive(Debug, Deserialize, Serialize)]
pub struct FortePaymentsSyncResponse {
pub transaction_id: String,
pub organization_id: Secret<String>,
pub location_id: Secret<String>,
pub original_transaction_id: Option<String>,
pub status: FortePaymentStatus,
pub action: ForteAction,
pub authorization_code: String,
pub authorization_amount: Option<FloatMajorUnit>,
pub billing_address: Option<BillingAddress>,
pub entered_by: String,
pub received_date: String,
pub origination_date: Option<String>,
pub card: Option<CardResponse>,
pub attempt_number: i64,
pub response: ResponseStatus,
pub links: ForteLink,
pub biller_name: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ForteLink {
pub disputes: String,
pub settlements: String,
#[serde(rename = "self")]
pub self_url: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, FortePaymentsSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FortePaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction_id = &item.response.transaction_id;
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(ForteMeta {
auth_id: item.response.authorization_code,
})),
network_txn_id: None,
connector_response_reference_id: Some(transaction_id.to_string()),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
// Capture
#[derive(Debug, Serialize)]
pub struct ForteCaptureRequest {
action: String,
transaction_id: String,
authorization_code: String,
}
impl TryFrom<&types::PaymentsCaptureRouterData> for ForteCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
let trn_id = item.request.connector_transaction_id.clone();
let connector_auth_id: ForteMeta =
utils::to_connector_meta(item.request.connector_meta.clone())?;
let auth_code = connector_auth_id.auth_id;
Ok(Self {
action: "capture".to_string(),
transaction_id: trn_id,
authorization_code: auth_code,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CaptureResponseStatus {
pub environment: String,
pub response_type: String,
pub response_code: ForteResponseCode,
pub response_desc: String,
pub authorization_code: String,
}
// Capture Response
#[derive(Debug, Deserialize, Serialize)]
pub struct ForteCaptureResponse {
pub transaction_id: String,
pub original_transaction_id: String,
pub entered_by: String,
pub authorization_code: String,
pub response: CaptureResponseStatus,
}
impl TryFrom<PaymentsCaptureResponseRouterData<ForteCaptureResponse>>
for types::PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<ForteCaptureResponse>,
) -> Result<Self, Self::Error> {
let transaction_id = &item.response.transaction_id;
Ok(Self {
status: enums::AttemptStatus::from(item.response.response.response_code),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(ForteMeta {
auth_id: item.response.authorization_code,
})),
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.to_string()),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
amount_captured: None,
..item.data
})
}
}
//Cancel
#[derive(Debug, Serialize)]
pub struct ForteCancelRequest {
action: String,
authorization_code: String,
}
impl TryFrom<&types::PaymentsCancelRouterData> for ForteCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let action = "void".to_string();
let connector_auth_id: ForteMeta =
utils::to_connector_meta(item.request.connector_meta.clone())?;
let authorization_code = connector_auth_id.auth_id;
Ok(Self {
action,
authorization_code,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CancelResponseStatus {
pub response_type: String,
pub response_code: ForteResponseCode,
pub response_desc: String,
pub authorization_code: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ForteCancelResponse {
pub transaction_id: String,
pub location_id: Secret<String>,
pub action: String,
pub authorization_code: String,
pub entered_by: String,
pub response: CancelResponseStatus,
}
impl<F, T> TryFrom<ResponseRouterData<F, ForteCancelResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ForteCancelResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction_id = &item.response.transaction_id;
Ok(Self {
status: enums::AttemptStatus::from(item.response.response.response_code),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(ForteMeta {
auth_id: item.response.authorization_code,
})),
network_txn_id: None,
connector_response_reference_id: Some(transaction_id.to_string()),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
#[derive(Default, Debug, Serialize)]
pub struct ForteRefundRequest {
action: String,
authorization_amount: FloatMajorUnit,
original_transaction_id: String,
authorization_code: String,
}
impl<F> TryFrom<&ForteRouterData<&types::RefundsRouterData<F>>> for ForteRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item_data: &ForteRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let item = item_data.router_data;
let trn_id = item.request.connector_transaction_id.clone();
let connector_auth_id: ForteMeta =
utils::to_connector_meta(item.request.connector_metadata.clone())?;
let auth_code = connector_auth_id.auth_id;
let authorization_amount = item_data.amount;
Ok(Self {
action: "reverse".to_string(),
authorization_amount,
original_transaction_id: trn_id,
authorization_code: auth_code,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum RefundStatus {
Complete,
Ready,
Failed,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Complete => Self::Success,
RefundStatus::Ready => Self::Pending,
RefundStatus::Failed => Self::Failure,
}
}
}
impl From<ForteResponseCode> for enums::RefundStatus {
fn from(item: ForteResponseCode) -> Self {
match item {
ForteResponseCode::A01 | ForteResponseCode::A05 | ForteResponseCode::A06 => {
Self::Pending
}
_ => Self::Failure,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RefundResponse {
pub transaction_id: String,
pub original_transaction_id: String,
pub action: String,
pub authorization_amount: Option<FloatMajorUnit>,
pub authorization_code: String,
pub response: ResponseStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.response.response_code),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RefundSyncResponse {
status: RefundStatus,
transaction_id: String,
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundSyncResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ErrorResponseStatus {
pub environment: String,
pub response_type: Option<String>,
pub response_code: Option<String>,
pub response_desc: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ForteErrorResponse {
pub response: ErrorResponseStatus,
}
|
crates__hyperswitch_connectors__src__connectors__getnet.rs
|
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::IncomingWebhookEvent;
use base64::{self, Engine};
use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE,
crypto,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors::{self},
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks::{self},
};
use masking::{Mask, PeekInterface, Secret};
use ring::hmac;
use transformers as getnet;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Getnet {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Getnet {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Getnet {}
impl api::PaymentSession for Getnet {}
impl api::ConnectorAccessToken for Getnet {}
impl api::MandateSetup for Getnet {}
impl api::PaymentAuthorize for Getnet {}
impl api::PaymentSync for Getnet {}
impl api::PaymentCapture for Getnet {}
impl api::PaymentVoid for Getnet {}
impl api::Refund for Getnet {}
impl api::RefundExecute for Getnet {}
impl api::RefundSync for Getnet {}
impl api::PaymentToken for Getnet {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Getnet
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Getnet
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
headers::ACCEPT.to_string(),
self.get_accept_type().to_string().into(),
),
];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Getnet {
fn id(&self) -> &'static str {
"getnet"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.getnet.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = getnet::GetnetAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let encoded_api_key =
BASE64_ENGINE.encode(format!("{}:{}", auth.username.peek(), auth.password.peek()));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Basic {encoded_api_key}").into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: getnet::GetnetErrorResponse = res
.response
.parse_struct("GetnetErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code,
message: response.message,
reason: response.reason,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Getnet {
fn validate_psync_reference_id(
&self,
data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
if data.encoded_data.is_some()
|| data
.connector_transaction_id
.get_connector_transaction_id()
.is_ok()
{
return Ok(());
}
Err(errors::ConnectorError::MissingConnectorTransactionID.into())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Getnet {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Getnet {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Getnet {
// Not Implemented (R)
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Getnet".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Getnet {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
Ok(format!("{endpoint}/payments/"))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = getnet::GetnetRouterData::from((amount, req));
let connector_req = getnet::GetnetPaymentsRequest::try_from(&connector_router_data)?;
let res = RequestContent::Json(Box::new(connector_req));
Ok(res)
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: getnet::GetnetPaymentsResponse = res
.response
.parse_struct("Getnet PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Getnet {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth = getnet::GetnetAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let merchant_id = auth.merchant_id.peek();
let endpoint = self.base_url(connectors);
let transaction_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{endpoint}/merchants/{merchant_id}/payments/{transaction_id}",
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: getnet::GetnetPaymentsResponse = res
.response
.parse_struct("getnet PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Getnet {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
Ok(format!("{endpoint}/payments/"))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = getnet::GetnetRouterData::from((amount, req));
let connector_req = getnet::GetnetCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: getnet::GetnetCaptureResponse = res
.response
.parse_struct("Getnet PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Getnet {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
Ok(format!("{endpoint}/payments/"))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = getnet::GetnetCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: getnet::GetnetCancelResponse = res
.response
.parse_struct("GetnetPaymentsVoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Getnet {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
Ok(format!("{endpoint}/payments/"))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = getnet::GetnetRouterData::from((refund_amount, req));
let connector_req = getnet::GetnetRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: getnet::RefundResponse =
res.response
.parse_struct("getnet RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Getnet {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth = getnet::GetnetAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let merchant_id = auth.merchant_id.peek();
let endpoint = self.base_url(connectors);
let transaction_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{endpoint}/merchants/{merchant_id}/payments/{transaction_id}",
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: getnet::RefundResponse = res
.response
.parse_struct("getnet RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Getnet {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let notif_item = getnet::get_webhook_response(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let response_base64 = ¬if_item.response_base64.peek().clone();
BASE64_ENGINE
.decode(response_base64)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let notif = getnet::get_webhook_response(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
Ok(notif.response_base64.peek().clone().into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif = getnet::get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let transaction_type = ¬if.payment.transaction_type;
if getnet::is_refund_event(transaction_type) {
Ok(api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(
notif.payment.transaction_id.to_string(),
),
))
} else {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
notif.payment.transaction_id.to_string(),
),
))
}
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let notif = getnet::get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
let incoming_webhook_event = getnet::get_incoming_webhook_event(
notif.payment.transaction_type,
notif.payment.transaction_state,
);
Ok(incoming_webhook_event)
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif = getnet::get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(notif))
}
async fn verify_webhook_source(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_name: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let notif_item = getnet::get_webhook_response(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_name,
connector_webhook_details,
)
.await?;
let signature = notif_item.response_signature_base64.peek().clone();
let message = self.get_webhook_source_verification_message(
request,
merchant_id,
&connector_webhook_secrets,
)?;
let secret = connector_webhook_secrets.secret;
let key = hmac::Key::new(hmac::HMAC_SHA256, &secret);
let result = hmac::sign(&key, &message);
let computed_signature = BASE64_ENGINE.encode(result.as_ref());
let normalized_computed_signature = computed_signature.replace("+", " ");
Ok(signature == normalized_computed_signature)
}
}
static GETNET_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::RuPay,
common_enums::CardNetwork::Maestro,
];
let mut getnet_supported_payment_methods = SupportedPaymentMethods::new();
getnet_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network,
}
}),
),
},
);
getnet_supported_payment_methods
});
static GETNET_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Getnet",
description: "Getnet is a high-tech global payment platform that helps businesses accept payments securely while providing the best frictionless experience for customers everywhere.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static GETNET_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] =
[enums::EventClass::Payments, enums::EventClass::Refunds];
impl ConnectorSpecifications for Getnet {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&GETNET_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*GETNET_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&GETNET_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__getnet__transformers.rs
|
use api_models::webhooks::IncomingWebhookEvent;
use base64::Engine;
use cards::CardNumber;
use common_enums::{enums, AttemptStatus, CaptureMethod, CountryAlpha2};
use common_utils::{
consts::BASE64_ENGINE,
errors::CustomResult,
pii::{Email, IpAddress},
types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::ConnectorAuthType,
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
connectors::paybox::transformers::parse_url_encoded_to_struct,
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
},
utils::{
BrowserInformationData, PaymentsAuthorizeRequestData, PaymentsSyncRequestData,
RouterData as _,
},
};
pub struct GetnetRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for GetnetRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Amount {
pub value: FloatMajorUnit,
pub currency: enums::Currency,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Address {
#[serde(rename = "street1")]
pub street1: Option<Secret<String>>,
pub city: Option<String>,
pub state: Option<Secret<String>>,
pub country: Option<CountryAlpha2>,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct AccountHolder {
#[serde(rename = "first-name")]
pub first_name: Option<Secret<String>>,
#[serde(rename = "last-name")]
pub last_name: Option<Secret<String>>,
pub email: Option<Email>,
pub phone: Option<Secret<String>>,
pub address: Option<Address>,
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct Card {
#[serde(rename = "account-number")]
pub account_number: CardNumber,
#[serde(rename = "expiration-month")]
pub expiration_month: Secret<String>,
#[serde(rename = "expiration-year")]
pub expiration_year: Secret<String>,
#[serde(rename = "card-security-code")]
pub card_security_code: Secret<String>,
#[serde(rename = "card-type")]
pub card_type: String,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum GetnetPaymentMethods {
CreditCard,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct PaymentMethod {
pub name: GetnetPaymentMethods,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Notification {
pub url: Option<String>,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct PaymentMethodContainer {
#[serde(rename = "payment-method")]
pub payment_method: Vec<PaymentMethod>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum NotificationFormat {
#[serde(rename = "application/json-signed")]
JsonSigned,
#[serde(rename = "application/json")]
Json,
#[serde(rename = "application/xml")]
Xml,
#[serde(rename = "application/html")]
Html,
#[serde(rename = "application/x-www-form-urlencoded")]
Urlencoded,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct NotificationContainer {
pub notification: Vec<Notification>,
pub format: NotificationFormat,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct MerchantAccountId {
pub value: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct PaymentData {
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
#[serde(rename = "account-holder")]
pub account_holder: Option<AccountHolder>,
pub card: Card,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
#[serde(rename = "payment-methods")]
pub payment_methods: PaymentMethodContainer,
pub notifications: Option<NotificationContainer>,
}
#[derive(Debug, Serialize)]
pub struct GetnetPaymentsRequest {
payment: PaymentData,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct GetnetCard {
number: CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<enums::PaymentMethodType> for PaymentMethodContainer {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(payment_method_type: enums::PaymentMethodType) -> Result<Self, Self::Error> {
match payment_method_type {
enums::PaymentMethodType::Credit => Ok(Self {
payment_method: vec![PaymentMethod {
name: GetnetPaymentMethods::CreditCard,
}],
}),
_ => Err(errors::ConnectorError::NotSupported {
message: "Payment method type not supported".to_string(),
connector: "Getnet",
}
.into()),
}
}
}
impl TryFrom<&GetnetRouterData<&PaymentsAuthorizeRouterData>> for GetnetPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &GetnetRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ref req_card) => {
if item.router_data.is_three_ds() {
return Err(errors::ConnectorError::NotSupported {
message: "3DS payments".to_string(),
connector: "Getnet",
}
.into());
}
let request = &item.router_data.request;
let auth_type = GetnetAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let merchant_account_id = MerchantAccountId {
value: auth_type.merchant_id,
};
let requested_amount = Amount {
value: item.amount,
currency: request.currency,
};
let account_holder = AccountHolder {
first_name: item.router_data.get_optional_billing_first_name(),
last_name: item.router_data.get_optional_billing_last_name(),
email: item.router_data.request.get_optional_email(),
phone: item.router_data.get_optional_billing_phone_number(),
address: Some(Address {
street1: item.router_data.get_optional_billing_line2(),
city: item.router_data.get_optional_billing_city(),
state: item.router_data.get_optional_billing_state(),
country: item.router_data.get_optional_billing_country(),
}),
};
let card = Card {
account_number: req_card.card_number.clone(),
expiration_month: req_card.card_exp_month.clone(),
expiration_year: req_card.card_exp_year.clone(),
card_security_code: req_card.card_cvc.clone(),
card_type: req_card
.card_network
.as_ref()
.map(|network| network.to_string().to_lowercase())
.unwrap_or_default(),
};
let pmt = item.router_data.request.get_payment_method_type()?;
let payment_method = PaymentMethodContainer::try_from(pmt)?;
let notifications: NotificationContainer = NotificationContainer {
format: NotificationFormat::JsonSigned,
notification: vec![Notification {
url: Some(item.router_data.request.get_webhook_url()?),
}],
};
let transaction_type = if request.is_auto_capture()? {
GetnetTransactionType::Purchase
} else {
GetnetTransactionType::Authorization
};
let payment_data = PaymentData {
merchant_account_id,
request_id: item.router_data.payment_id.clone(),
transaction_type,
requested_amount,
account_holder: Some(account_holder),
card,
ip_address: Some(request.get_browser_info()?.get_ip_address()?),
payment_methods: payment_method,
notifications: Some(notifications),
};
Ok(Self {
payment: payment_data,
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
pub struct GetnetAuthType {
pub username: Secret<String>,
pub password: Secret<String>,
pub merchant_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for GetnetAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
username: key1.to_owned(),
password: api_key.to_owned(),
merchant_id: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum GetnetPaymentStatus {
Success,
Failed,
#[default]
InProgress,
}
impl From<GetnetPaymentStatus> for AttemptStatus {
fn from(item: GetnetPaymentStatus) -> Self {
match item {
GetnetPaymentStatus::Success => Self::Charged,
GetnetPaymentStatus::Failed => Self::Failure,
GetnetPaymentStatus::InProgress => Self::Pending,
}
}
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Status {
pub code: String,
pub description: String,
pub severity: String,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Statuses {
pub status: Vec<Status>,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct CardToken {
#[serde(rename = "token-id")]
pub token_id: Secret<String>,
#[serde(rename = "masked-account-number")]
pub masked_account_number: Secret<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct PaymentResponseData {
pub statuses: Statuses,
pub descriptor: Option<String>,
pub notifications: NotificationContainer,
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "transaction-id")]
pub transaction_id: String,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "transaction-state")]
pub transaction_state: GetnetPaymentStatus,
#[serde(rename = "completion-time-stamp")]
pub completion_time_stamp: Option<i64>,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
#[serde(rename = "account-holder")]
pub account_holder: Option<AccountHolder>,
#[serde(rename = "card-token")]
pub card_token: CardToken,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
#[serde(rename = "payment-methods")]
pub payment_methods: PaymentMethodContainer,
#[serde(rename = "api-id")]
pub api_id: String,
#[serde(rename = "self")]
pub self_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentsResponse {
payment: PaymentResponseData,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetnetPaymentsResponse {
PaymentsResponse(Box<PaymentsResponse>),
GetnetWebhookNotificationResponse(Box<GetnetWebhookNotificationResponseBody>),
}
pub fn authorization_attempt_status_from_transaction_state(
getnet_status: GetnetPaymentStatus,
is_auto_capture: bool,
) -> AttemptStatus {
match getnet_status {
GetnetPaymentStatus::Success => {
if is_auto_capture {
AttemptStatus::Charged
} else {
AttemptStatus::Authorized
}
}
GetnetPaymentStatus::InProgress => AttemptStatus::Pending,
GetnetPaymentStatus::Failed => AttemptStatus::Failure,
}
}
impl TryFrom<PaymentsResponseRouterData<GetnetPaymentsResponse>> for PaymentsAuthorizeRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<GetnetPaymentsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
GetnetPaymentsResponse::PaymentsResponse(ref payment_response) => Ok(Self {
status: authorization_attempt_status_from_transaction_state(
payment_response.payment.transaction_state.clone(),
item.data.request.is_auto_capture()?,
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
payment_response.payment.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
}),
_ => Err(error_stack::Report::new(
errors::ConnectorError::ResponseHandlingFailed,
)),
}
}
}
pub fn psync_attempt_status_from_transaction_state(
getnet_status: GetnetPaymentStatus,
is_auto_capture: bool,
transaction_type: GetnetTransactionType,
) -> AttemptStatus {
match getnet_status {
GetnetPaymentStatus::Success => {
if is_auto_capture && transaction_type == GetnetTransactionType::CaptureAuthorization {
AttemptStatus::Charged
} else {
AttemptStatus::Authorized
}
}
GetnetPaymentStatus::InProgress => AttemptStatus::Pending,
GetnetPaymentStatus::Failed => AttemptStatus::Failure,
}
}
impl TryFrom<PaymentsSyncResponseRouterData<GetnetPaymentsResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<GetnetPaymentsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
GetnetPaymentsResponse::PaymentsResponse(ref payment_response) => Ok(Self {
status: authorization_attempt_status_from_transaction_state(
payment_response.payment.transaction_state.clone(),
item.data.request.is_auto_capture()?,
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
payment_response.payment.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
}),
GetnetPaymentsResponse::GetnetWebhookNotificationResponse(ref webhook_response) => {
Ok(Self {
status: psync_attempt_status_from_transaction_state(
webhook_response.payment.transaction_state.clone(),
item.data.request.is_auto_capture()?,
webhook_response.payment.transaction_type.clone(),
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
webhook_response.payment.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CapturePaymentData {
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "parent-transaction-id")]
pub parent_transaction_id: String,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
pub notifications: NotificationContainer,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
}
#[derive(Debug, Serialize)]
pub struct GetnetCaptureRequest {
pub payment: CapturePaymentData,
}
impl TryFrom<&GetnetRouterData<&PaymentsCaptureRouterData>> for GetnetCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &GetnetRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
let auth_type = GetnetAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let merchant_account_id = MerchantAccountId {
value: auth_type.merchant_id,
};
let requested_amount = Amount {
value: item.amount,
currency: request.currency,
};
let req = &item.router_data.request;
let webhook_url = &req.webhook_url;
let notifications = NotificationContainer {
format: NotificationFormat::JsonSigned,
notification: vec![Notification {
url: webhook_url.clone(),
}],
};
let transaction_type = GetnetTransactionType::CaptureAuthorization;
let ip_address = req
.browser_info
.as_ref()
.and_then(|info| info.ip_address.as_ref())
.map(|ip| Secret::new(ip.to_string()));
let request_id = item.router_data.connector_request_reference_id.clone();
let parent_transaction_id = item.router_data.request.connector_transaction_id.clone();
let capture_payment_data = CapturePaymentData {
merchant_account_id,
request_id,
transaction_type,
parent_transaction_id,
requested_amount,
notifications,
ip_address,
};
Ok(Self {
payment: capture_payment_data,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CaptureResponseData {
pub statuses: Statuses,
pub descriptor: String,
pub notifications: NotificationContainer,
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "transaction-id")]
pub transaction_id: String,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "transaction-state")]
pub transaction_state: GetnetPaymentStatus,
#[serde(rename = "completion-time-stamp")]
pub completion_time_stamp: Option<i64>,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
#[serde(rename = "parent-transaction-id")]
pub parent_transaction_id: String,
#[serde(rename = "account-holder")]
pub account_holder: Option<AccountHolder>,
#[serde(rename = "card-token")]
pub card_token: CardToken,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
#[serde(rename = "payment-methods")]
pub payment_methods: PaymentMethodContainer,
#[serde(rename = "parent-transaction-amount")]
pub parent_transaction_amount: Amount,
#[serde(rename = "authorization-code")]
pub authorization_code: String,
#[serde(rename = "api-id")]
pub api_id: String,
#[serde(rename = "self")]
pub self_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetnetCaptureResponse {
payment: CaptureResponseData,
}
pub fn capture_status_from_transaction_state(getnet_status: GetnetPaymentStatus) -> AttemptStatus {
match getnet_status {
GetnetPaymentStatus::Success => AttemptStatus::Charged,
GetnetPaymentStatus::InProgress => AttemptStatus::Pending,
GetnetPaymentStatus::Failed => AttemptStatus::Authorized,
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<GetnetCaptureResponse>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<GetnetCaptureResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: capture_status_from_transaction_state(item.response.payment.transaction_state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.payment.transaction_id,
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct RefundPaymentData {
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "parent-transaction-id")]
pub parent_transaction_id: String,
pub notifications: NotificationContainer,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
}
#[derive(Debug, Serialize)]
pub struct GetnetRefundRequest {
pub payment: RefundPaymentData,
}
impl<F> TryFrom<&GetnetRouterData<&RefundsRouterData<F>>> for GetnetRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &GetnetRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
let auth_type = GetnetAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let url = request.webhook_url.clone();
let merchant_account_id = MerchantAccountId {
value: auth_type.merchant_id,
};
let notifications = NotificationContainer {
format: NotificationFormat::JsonSigned,
notification: vec![Notification { url }],
};
let capture_method = request.capture_method;
let transaction_type = match capture_method {
Some(CaptureMethod::Automatic) => GetnetTransactionType::RefundPurchase,
Some(CaptureMethod::Manual) => GetnetTransactionType::RefundCapture,
Some(CaptureMethod::ManualMultiple)
| Some(CaptureMethod::Scheduled)
| Some(CaptureMethod::SequentialAutomatic)
| None => {
return Err(errors::ConnectorError::CaptureMethodNotSupported {}.into());
}
};
let ip_address = request
.browser_info
.as_ref()
.and_then(|browser_info| browser_info.ip_address.as_ref())
.map(|ip| Secret::new(ip.to_string()));
let request_id = item
.router_data
.refund_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?;
let parent_transaction_id = item.router_data.request.connector_transaction_id.clone();
let refund_payment_data = RefundPaymentData {
merchant_account_id,
request_id,
transaction_type,
parent_transaction_id,
notifications,
ip_address,
};
Ok(Self {
payment: refund_payment_data,
})
}
}
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum RefundStatus {
Success,
Failed,
#[default]
InProgress,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Success => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::InProgress => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RefundResponseData {
pub statuses: Statuses,
pub descriptor: String,
pub notifications: NotificationContainer,
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "transaction-id")]
pub transaction_id: String,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "transaction-state")]
pub transaction_state: RefundStatus,
#[serde(rename = "completion-time-stamp")]
pub completion_time_stamp: Option<i64>,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
#[serde(rename = "parent-transaction-id")]
#[serde(skip_serializing_if = "Option::is_none")]
pub parent_transaction_id: Option<String>,
#[serde(rename = "account-holder")]
pub account_holder: Option<AccountHolder>,
#[serde(rename = "card-token")]
pub card_token: CardToken,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
#[serde(rename = "payment-methods")]
pub payment_methods: PaymentMethodContainer,
#[serde(rename = "parent-transaction-amount")]
#[serde(skip_serializing_if = "Option::is_none")]
pub parent_transaction_amount: Option<Amount>,
#[serde(rename = "api-id")]
pub api_id: String,
#[serde(rename = "self")]
pub self_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
payment: RefundResponseData,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.payment.transaction_id,
refund_status: enums::RefundStatus::from(item.response.payment.transaction_state),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.payment.transaction_id,
refund_status: enums::RefundStatus::from(item.response.payment.transaction_state),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CancelPaymentData {
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "parent-transaction-id")]
pub parent_transaction_id: String,
pub notifications: NotificationContainer,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
}
#[derive(Debug, Serialize)]
pub struct GetnetCancelRequest {
pub payment: CancelPaymentData,
}
impl TryFrom<&PaymentsCancelRouterData> for GetnetCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let request = &item.request;
let auth_type = GetnetAuthType::try_from(&item.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let merchant_account_id = MerchantAccountId {
value: auth_type.merchant_id,
};
let webhook_url = &item.request.webhook_url;
let notifications = NotificationContainer {
format: NotificationFormat::JsonSigned,
notification: vec![Notification {
url: webhook_url.clone(),
}],
};
let capture_method = &item.request.capture_method;
let transaction_type = match capture_method {
Some(CaptureMethod::Automatic) => GetnetTransactionType::VoidPurchase,
Some(CaptureMethod::Manual) => GetnetTransactionType::VoidAuthorization,
Some(CaptureMethod::ManualMultiple)
| Some(CaptureMethod::Scheduled)
| Some(CaptureMethod::SequentialAutomatic) => {
return Err(errors::ConnectorError::CaptureMethodNotSupported {}.into());
}
None => {
return Err(errors::ConnectorError::CaptureMethodNotSupported {}.into());
}
};
let ip_address = request
.browser_info
.as_ref()
.and_then(|browser_info| browser_info.ip_address.as_ref())
.map(|ip| Secret::new(ip.to_string()));
let request_id = &item.connector_request_reference_id.clone();
let parent_transaction_id = item.request.connector_transaction_id.clone();
let cancel_payment_data = CancelPaymentData {
merchant_account_id,
request_id: request_id.to_string(),
transaction_type,
parent_transaction_id,
notifications,
ip_address,
};
Ok(Self {
payment: cancel_payment_data,
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum GetnetTransactionType {
Purchase,
#[serde(rename = "capture-authorization")]
CaptureAuthorization,
#[serde(rename = "refund-purchase")]
RefundPurchase,
#[serde(rename = "refund-capture")]
RefundCapture,
#[serde(rename = "void-authorization")]
VoidAuthorization,
#[serde(rename = "void-purchase")]
VoidPurchase,
Authorization,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub struct CancelResponseData {
pub statuses: Statuses,
pub descriptor: String,
pub notifications: NotificationContainer,
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "transaction-id")]
pub transaction_id: String,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "transaction-state")]
pub transaction_state: GetnetPaymentStatus,
#[serde(rename = "completion-time-stamp")]
pub completion_time_stamp: Option<i64>,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
#[serde(rename = "parent-transaction-id")]
pub parent_transaction_id: String,
#[serde(rename = "account-holder")]
pub account_holder: Option<AccountHolder>,
#[serde(rename = "card-token")]
pub card_token: CardToken,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
#[serde(rename = "payment-methods")]
pub payment_methods: PaymentMethodContainer,
#[serde(rename = "parent-transaction-amount")]
pub parent_transaction_amount: Amount,
#[serde(rename = "api-id")]
pub api_id: String,
#[serde(rename = "self")]
pub self_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetnetCancelResponse {
payment: CancelResponseData,
}
pub fn cancel_status_from_transaction_state(getnet_status: GetnetPaymentStatus) -> AttemptStatus {
match getnet_status {
GetnetPaymentStatus::Success => AttemptStatus::Voided,
GetnetPaymentStatus::InProgress => AttemptStatus::Pending,
GetnetPaymentStatus::Failed => AttemptStatus::VoidFailed,
}
}
impl TryFrom<PaymentsCancelResponseRouterData<GetnetCancelResponse>> for PaymentsCancelRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<GetnetCancelResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: cancel_status_from_transaction_state(item.response.payment.transaction_state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.payment.transaction_id,
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct GetnetErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct GetnetWebhookNotificationResponse {
#[serde(rename = "response-signature-base64")]
pub response_signature_base64: Secret<String>,
#[serde(rename = "response-signature-algorithm")]
pub response_signature_algorithm: Secret<String>,
#[serde(rename = "response-base64")]
pub response_base64: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct WebhookResponseData {
pub statuses: Statuses,
pub descriptor: String,
pub notifications: NotificationContainer,
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "transaction-id")]
pub transaction_id: String,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "transaction-state")]
pub transaction_state: GetnetPaymentStatus,
#[serde(rename = "completion-time-stamp")]
pub completion_time_stamp: u64,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
#[serde(rename = "parent-transaction-id")]
#[serde(skip_serializing_if = "Option::is_none")]
pub parent_transaction_id: Option<String>,
#[serde(rename = "account-holder")]
pub account_holder: Option<AccountHolder>,
#[serde(rename = "card-token")]
pub card_token: CardToken,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
#[serde(rename = "payment-methods")]
pub payment_methods: PaymentMethodContainer,
#[serde(rename = "parent-transaction-amount")]
#[serde(skip_serializing_if = "Option::is_none")]
pub parent_transaction_amount: Option<Amount>,
#[serde(rename = "authorization-code")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization_code: Option<String>,
#[serde(rename = "api-id")]
pub api_id: String,
#[serde(rename = "provider-account-id")]
#[serde(skip_serializing_if = "Option::is_none")]
pub provider_account_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct GetnetWebhookNotificationResponseBody {
pub payment: WebhookResponseData,
}
pub fn is_refund_event(transaction_type: &GetnetTransactionType) -> bool {
matches!(
transaction_type,
GetnetTransactionType::RefundPurchase | GetnetTransactionType::RefundCapture
)
}
pub fn get_webhook_object_from_body(
body: &[u8],
) -> CustomResult<GetnetWebhookNotificationResponseBody, errors::ConnectorError> {
let body_bytes = bytes::Bytes::copy_from_slice(body);
let parsed_param: GetnetWebhookNotificationResponse =
parse_url_encoded_to_struct(body_bytes)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let response_base64 = &parsed_param.response_base64.peek();
let decoded_response = BASE64_ENGINE
.decode(response_base64)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let getnet_webhook_notification_response: GetnetWebhookNotificationResponseBody =
match serde_json::from_slice::<GetnetWebhookNotificationResponseBody>(&decoded_response) {
Ok(response) => response,
Err(_e) => {
return Err(errors::ConnectorError::WebhookBodyDecodingFailed)?;
}
};
Ok(getnet_webhook_notification_response)
}
pub fn get_webhook_response(
body: &[u8],
) -> CustomResult<GetnetWebhookNotificationResponse, errors::ConnectorError> {
let body_bytes = bytes::Bytes::copy_from_slice(body);
let parsed_param: GetnetWebhookNotificationResponse =
parse_url_encoded_to_struct(body_bytes)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(parsed_param)
}
pub fn get_incoming_webhook_event(
transaction_type: GetnetTransactionType,
transaction_status: GetnetPaymentStatus,
) -> IncomingWebhookEvent {
match transaction_type {
GetnetTransactionType::Purchase => match transaction_status {
GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentSuccess,
GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentFailure,
GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentProcessing,
},
GetnetTransactionType::Authorization => match transaction_status {
GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentAuthorizationSuccess,
GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentAuthorizationFailure,
GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentProcessing,
},
GetnetTransactionType::CaptureAuthorization => match transaction_status {
GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentCaptureSuccess,
GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentCaptureFailure,
GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentCaptureFailure,
},
GetnetTransactionType::RefundPurchase => match transaction_status {
GetnetPaymentStatus::Success => IncomingWebhookEvent::RefundSuccess,
GetnetPaymentStatus::Failed => IncomingWebhookEvent::RefundFailure,
GetnetPaymentStatus::InProgress => IncomingWebhookEvent::RefundFailure,
},
GetnetTransactionType::RefundCapture => match transaction_status {
GetnetPaymentStatus::Success => IncomingWebhookEvent::RefundSuccess,
GetnetPaymentStatus::Failed => IncomingWebhookEvent::RefundFailure,
GetnetPaymentStatus::InProgress => IncomingWebhookEvent::RefundFailure,
},
GetnetTransactionType::VoidAuthorization => match transaction_status {
GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentCancelled,
GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentCancelFailure,
GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentCancelFailure,
},
GetnetTransactionType::VoidPurchase => match transaction_status {
GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentCancelled,
GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentCancelFailure,
GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentCancelFailure,
},
}
}
|
crates__hyperswitch_connectors__src__connectors__gigadat.rs
|
pub mod transformers;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts,
crypto::Encryptable,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundsRouterData,
},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::{PoCreate, PoFulfill, PoQuote, PoSync},
types::{PayoutsData, PayoutsResponseData, PayoutsRouterData},
};
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::types::{
PayoutCreateType, PayoutFulfillType, PayoutQuoteType, PayoutSyncType,
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts as api_consts, errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use lazy_static::lazy_static;
#[cfg(feature = "payouts")]
use masking::ExposeInterface;
use masking::{Mask, PeekInterface};
#[cfg(feature = "payouts")]
use router_env::{instrument, tracing};
use transformers as gigadat;
use uuid::Uuid;
#[cfg(feature = "payouts")]
use crate::utils::{to_payout_connector_meta, RouterData as RouterDataTrait};
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Gigadat {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Gigadat {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Gigadat {}
impl api::PaymentSession for Gigadat {}
impl api::ConnectorAccessToken for Gigadat {}
impl api::MandateSetup for Gigadat {}
impl api::PaymentAuthorize for Gigadat {}
impl api::PaymentSync for Gigadat {}
impl api::PaymentCapture for Gigadat {}
impl api::PaymentVoid for Gigadat {}
impl api::Refund for Gigadat {}
impl api::RefundExecute for Gigadat {}
impl api::RefundSync for Gigadat {}
impl api::PaymentToken for Gigadat {}
impl api::Payouts for Gigadat {}
#[cfg(feature = "payouts")]
impl api::PayoutQuote for Gigadat {}
#[cfg(feature = "payouts")]
impl api::PayoutCreate for Gigadat {}
#[cfg(feature = "payouts")]
impl api::PayoutFulfill for Gigadat {}
#[cfg(feature = "payouts")]
impl api::PayoutSync for Gigadat {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Gigadat
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Gigadat
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Gigadat {
fn id(&self) -> &'static str {
"gigadat"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.gigadat.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = gigadat::GigadatAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_key = format!(
"{}:{}",
auth.access_token.peek(),
auth.security_token.peek()
);
let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth_header.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: gigadat::GigadatErrorResponse = res
.response
.parse_struct("GigadatErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.err.clone(),
message: response.err.clone(),
reason: Some(response.err).clone(),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Gigadat {
fn validate_mandate_payment(
&self,
_pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
match pm_data {
PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
"validate_mandate_payment does not support cards".to_string(),
)
.into()),
_ => Ok(()),
}
}
fn validate_psync_reference_id(
&self,
_data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
Ok(())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Gigadat {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Gigadat {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Gigadat {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Gigadat {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth = gigadat::GigadatAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(format!(
"{}api/payment-token/{}",
self.base_url(connectors),
auth.campaign_id.peek()
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = gigadat::GigadatRouterData::from((amount, req));
let connector_req = gigadat::GigadatCpiRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: gigadat::GigadatPaymentResponse = res
.response
.parse_struct("GigadatPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Gigadat {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let transaction_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}api/transactions/{transaction_id}",
self.base_url(connectors)
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: gigadat::GigadatTransactionStatusResponse = res
.response
.parse_struct("gigadat PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Gigadat {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: gigadat::GigadatTransactionStatusResponse = res
.response
.parse_struct("Gigadat PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Gigadat {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Gigadat {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = gigadat::GigadatAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_key = format!(
"{}:{}",
auth.access_token.peek(),
auth.security_token.peek()
);
let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key));
Ok(vec![
(
headers::AUTHORIZATION.to_string(),
auth_header.into_masked(),
),
(
headers::IDEMPOTENCY_KEY.to_string(),
Uuid::new_v4().to_string().into_masked(),
),
])
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}refunds", self.base_url(connectors),))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = gigadat::GigadatRouterData::from((refund_amount, req));
let connector_req = gigadat::GigadatRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: gigadat::RefundResponse = res
.response
.parse_struct("gigadat RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: gigadat::GigadatRefundErrorResponse = res
.response
.parse_struct("GigadatRefundErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let code = response
.error
.first()
.and_then(|error_detail| error_detail.code.clone())
.unwrap_or(api_consts::NO_ERROR_CODE.to_string());
let message = response
.error
.first()
.map(|error_detail| error_detail.detail.clone())
.unwrap_or(api_consts::NO_ERROR_MESSAGE.to_string());
Ok(ErrorResponse {
status_code: res.status_code,
code,
message,
reason: Some(response.message).clone(),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Gigadat {
//Gigadat does not support Refund Sync
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData> for Gigadat {
fn get_headers(
&self,
req: &PayoutsRouterData<PoQuote>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PayoutsRouterData<PoQuote>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth = gigadat::GigadatAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(format!(
"{}api/payment-token/{}",
self.base_url(connectors),
auth.campaign_id.peek()
))
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoQuote>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.destination_currency,
)?;
let connector_router_data = gigadat::GigadatRouterData::from((amount, req));
let connector_req = gigadat::GigadatPayoutQuoteRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoQuote>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutQuoteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutQuoteType::get_headers(self, req, connectors)?)
.set_body(PayoutQuoteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoQuote>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoQuote>, errors::ConnectorError> {
let response: gigadat::GigadatPayoutQuoteResponse = res
.response
.parse_struct("GigadatPayoutQuoteResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> for Gigadat {
fn get_headers(
&self,
req: &PayoutsRouterData<PoCreate>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PayoutsRouterData<PoCreate>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let transfer_id = req.get_quote_id()?;
let metadata = Some(req.get_connector_meta()?.clone().expose());
let gigatad_meta: gigadat::GigadatPayoutMeta = to_payout_connector_meta(metadata.clone())?;
Ok(format!(
"{}webflow?transaction={}&token={}",
self.base_url(connectors),
transfer_id,
gigatad_meta.token.peek(),
))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoCreate>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutCreateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutCreateType::get_headers(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoCreate>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoCreate>, errors::ConnectorError> {
let response: gigadat::GigadatPayoutResponse = res
.response
.parse_struct("GigadatPayoutResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Gigadat {
fn get_headers(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let transfer_id = req.request.connector_payout_id.to_owned().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "transaction_id",
},
)?;
let metadata = req
.request
.payout_connector_metadata
.clone()
.map(|secret| secret.peek().clone());
let gigatad_meta: gigadat::GigadatPayoutMeta = to_payout_connector_meta(metadata.clone())?;
Ok(format!(
"{}webflow/deposit?transaction={}&token={}",
self.base_url(connectors),
transfer_id,
gigatad_meta.token.peek(),
))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Get)
.url(&PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutFulfillType::get_headers(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoFulfill>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoFulfill>, errors::ConnectorError> {
let response: gigadat::GigadatPayoutResponse = res
.response
.parse_struct("GigadatPayoutResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> for Gigadat {
fn get_url(
&self,
req: &PayoutsRouterData<PoSync>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let transfer_id = req.request.connector_payout_id.to_owned().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "transaction_id",
},
)?;
Ok(format!(
"{}api/transactions/{}",
connectors.gigadat.base_url, transfer_id
))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoSync>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn build_request(
&self,
req: &PayoutsRouterData<PoSync>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Get)
.url(&PayoutSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutSyncType::get_headers(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PayoutsRouterData<PoSync>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoSync>, errors::ConnectorError> {
let response: gigadat::GigadatPayoutSyncResponse = res
.response
.parse_struct("GigadatPayoutSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
fn get_webhook_query_params(
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<transformers::GigadatWebhookQueryParameters, errors::ConnectorError> {
let query_string = &request.query_params;
let (transaction, status) = query_string
.split('&')
.filter_map(|pair| pair.split_once('='))
.fold((None, None), |(mut txn, mut sts), (key, value)| {
match key {
"transaction" => txn = Some(value.to_string()),
"status" => {
if let Ok(status) =
transformers::GigadatTransactionStatus::try_from(value.to_string())
{
sts = Some(status);
}
}
_ => {}
}
(txn, sts)
});
Ok(transformers::GigadatWebhookQueryParameters {
transaction: transaction.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?,
status: status.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?,
})
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Gigadat {
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let query_params = get_webhook_query_params(request)?;
let body_str = std::str::from_utf8(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let details = transformers::GigadatWebhookKeyValueBody::decode_from_url(body_str)?;
let webhook_type = details.webhook_type;
let reference_id = match transformers::GigadatFlow::get_flow(&webhook_type)? {
transformers::GigadatFlow::Payment => {
api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
query_params.transaction,
),
)
}
#[cfg(feature = "payouts")]
transformers::GigadatFlow::Payout => api_models::webhooks::ObjectReferenceId::PayoutId(
api_models::webhooks::PayoutIdType::ConnectorPayoutId(query_params.transaction),
),
};
Ok(reference_id)
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let query_params = get_webhook_query_params(request)?;
let body_str = std::str::from_utf8(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let details = transformers::GigadatWebhookKeyValueBody::decode_from_url(body_str)?;
let webhook_type = details.webhook_type;
let flow_type = transformers::GigadatFlow::get_flow(&webhook_type)?;
let event_type =
transformers::get_gigadat_webhook_event_type(query_params.status, flow_type);
Ok(event_type)
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let body_str = std::str::from_utf8(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let details = transformers::GigadatWebhookKeyValueBody::decode_from_url(body_str)?;
Ok(Box::new(details))
}
async fn verify_webhook_source(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: Encryptable<masking::Secret<serde_json::Value>>,
_connector_label: &str,
) -> CustomResult<bool, errors::ConnectorError> {
Ok(false)
}
}
lazy_static! {
static ref GIGADAT_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
let supported_capture_methods = vec![enums::CaptureMethod::Automatic];
let mut gigadat_supported_payment_methods = SupportedPaymentMethods::new();
gigadat_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Interac,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
gigadat_supported_payment_methods
};
static ref GIGADAT_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Gigadat",
description: "Gigadat is a financial services product that offers a single API for payment integration. It provides Canadian businesses with a secure payment gateway and various pay-in and pay-out solutions, including Interac e-Transfer",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static ref GIGADAT_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = {
#[cfg(feature = "payouts")]
{
let mut flows = vec![enums::EventClass::Payments];
flows.push(enums::EventClass::Payouts);
flows
}
#[cfg(not(feature = "payouts"))]
{
vec![enums::EventClass::Payments]
}
};
}
impl ConnectorSpecifications for Gigadat {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*GIGADAT_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*GIGADAT_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*GIGADAT_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__gigadat__transformers.rs
|
use api_models::webhooks::IncomingWebhookEvent;
#[cfg(feature = "payouts")]
use api_models::{
self,
payouts::{BankRedirect, PayoutMethodData},
};
use common_enums::{enums, Currency};
use common_utils::{
id_type,
pii::{self, Email, IpAddress},
request::Method,
types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankRedirectData, PaymentMethodData},
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
InteracCustomerInfo, RouterData,
},
router_flow_types::refunds::Execute,
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::PoQuote, router_response_types::PayoutsResponseData,
types::PayoutsRouterData,
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
#[cfg(feature = "payouts")]
use crate::{types::PayoutsResponseRouterData, utils::PayoutsData as _};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, BrowserInformationData, PaymentsAuthorizeRequestData, RouterData as _},
};
pub struct GigadatRouterData<T> {
pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for GigadatRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
const CONNECTOR_BASE_URL: &str = "https://interac.express-connect.com/";
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct GigadatConnectorMetadataObject {
pub site: String,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for GigadatConnectorMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
Ok(metadata)
}
}
// CPI (Combined Pay-in) Request Structure for Gigadat
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GigadatCpiRequest {
pub user_id: id_type::CustomerId,
pub site: String,
pub user_ip: Secret<String, IpAddress>,
pub currency: Currency,
pub amount: FloatMajorUnit,
pub transaction_id: String,
#[serde(rename = "type")]
pub transaction_type: GidadatTransactionType,
pub sandbox: bool,
pub name: Secret<String>,
pub email: Email,
pub mobile: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum GidadatTransactionType {
Cpi,
Eto,
}
impl TryFrom<&GigadatRouterData<&PaymentsAuthorizeRouterData>> for GigadatCpiRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &GigadatRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let metadata: GigadatConnectorMetadataObject =
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankRedirect(BankRedirectData::Interac { .. }) => {
let router_data = item.router_data;
let name = router_data.get_billing_full_name()?;
let email = router_data.get_billing_email()?;
let mobile = router_data.get_billing_phone_number()?;
let currency = item.router_data.request.currency;
let sandbox = match item.router_data.test_mode {
Some(true) => true,
Some(false) | None => false,
};
let user_ip = router_data.request.get_browser_info()?.get_ip_address()?;
Ok(Self {
user_id: router_data.get_customer_id()?,
site: metadata.site,
user_ip,
currency,
amount: item.amount,
transaction_id: router_data.connector_request_reference_id.clone(),
transaction_type: GidadatTransactionType::Cpi,
name,
sandbox,
email,
mobile,
})
}
PaymentMethodData::BankRedirect(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Gigadat"),
))?,
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Gigadat"),
)
.into()),
}
}
}
#[derive(Debug, Clone)]
pub struct GigadatAuthType {
pub campaign_id: Secret<String>,
pub access_token: Secret<String>,
pub security_token: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for GigadatAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
security_token: api_secret.to_owned(),
access_token: api_key.to_owned(),
campaign_id: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigadatPaymentResponse {
pub token: Secret<String>,
pub data: GigadatPaymentData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GigadatPaymentData {
pub transaction_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GigadatTransactionStatus {
StatusInited,
StatusSuccess,
StatusRejected,
StatusRejected1,
StatusExpired,
StatusAborted1,
StatusPending,
StatusFailed,
}
impl From<GigadatTransactionStatus> for enums::AttemptStatus {
fn from(item: GigadatTransactionStatus) -> Self {
match item {
GigadatTransactionStatus::StatusSuccess => Self::Charged,
GigadatTransactionStatus::StatusInited | GigadatTransactionStatus::StatusPending => {
Self::Pending
}
GigadatTransactionStatus::StatusRejected
| GigadatTransactionStatus::StatusExpired
| GigadatTransactionStatus::StatusRejected1
| GigadatTransactionStatus::StatusAborted1
| GigadatTransactionStatus::StatusFailed => Self::Failure,
}
}
}
pub enum GigadatFlow {
Payment,
#[cfg(feature = "payouts")]
Payout,
}
impl GigadatFlow {
pub fn get_flow(webhook_type: &str) -> Result<Self, errors::ConnectorError> {
match webhook_type {
#[cfg(feature = "payouts")]
"ETO" | "RTO" | "RTX" | "ANR" | "ANX" => Ok(Self::Payout),
"ETI" | "RFM" | "CPI" | "ACK" => Ok(Self::Payment),
_ => Err(errors::ConnectorError::NotImplemented(
"Invalid transaction type ".to_string(),
)),
}
}
}
pub fn get_gigadat_webhook_event_type(
status: GigadatTransactionStatus,
flow: GigadatFlow,
) -> IncomingWebhookEvent {
match flow {
GigadatFlow::Payment => match status {
GigadatTransactionStatus::StatusSuccess => IncomingWebhookEvent::PaymentIntentSuccess,
GigadatTransactionStatus::StatusFailed
| GigadatTransactionStatus::StatusRejected
| GigadatTransactionStatus::StatusRejected1
| GigadatTransactionStatus::StatusExpired
| GigadatTransactionStatus::StatusAborted1 => {
IncomingWebhookEvent::PaymentIntentFailure
}
GigadatTransactionStatus::StatusInited | GigadatTransactionStatus::StatusPending => {
IncomingWebhookEvent::PaymentIntentProcessing
}
},
#[cfg(feature = "payouts")]
GigadatFlow::Payout => match status {
GigadatTransactionStatus::StatusSuccess => IncomingWebhookEvent::PayoutSuccess,
GigadatTransactionStatus::StatusFailed
| GigadatTransactionStatus::StatusRejected
| GigadatTransactionStatus::StatusRejected1
| GigadatTransactionStatus::StatusExpired
| GigadatTransactionStatus::StatusAborted1 => IncomingWebhookEvent::PayoutFailure,
GigadatTransactionStatus::StatusInited | GigadatTransactionStatus::StatusPending => {
IncomingWebhookEvent::PayoutProcessing
}
},
}
}
impl TryFrom<String> for GigadatTransactionStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: String) -> Result<Self, Self::Error> {
match value.as_str() {
"STATUS_INITED" => Ok(Self::StatusInited),
"STATUS_SUCCESS" => Ok(Self::StatusSuccess),
"STATUS_REJECTED" => Ok(Self::StatusRejected),
"STATUS_REJECTED1" => Ok(Self::StatusRejected1),
"STATUS_EXPIRED" => Ok(Self::StatusExpired),
"STATUS_ABORTED1" => Ok(Self::StatusAborted1),
"STATUS_PENDING" => Ok(Self::StatusPending),
"STATUS_FAILED" => Ok(Self::StatusFailed),
_ => Err(errors::ConnectorError::WebhookBodyDecodingFailed.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigadatTransactionStatusResponse {
pub status: GigadatTransactionStatus,
pub interac_bank_name: Option<Secret<String>>,
pub data: Option<GigadatSyncData>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigadatSyncData {
pub name: Option<Secret<String>>,
pub email: Option<Email>,
pub mobile: Option<Secret<String>>,
}
impl<F, T> TryFrom<ResponseRouterData<F, GigadatPaymentResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, GigadatPaymentResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
// Will be raising a sepearte PR to populate a field connect_base_url in routerData and use it here
let base_url = CONNECTOR_BASE_URL;
let redirect_url = format!(
"{}webflow?transaction={}&token={}",
base_url,
item.data.connector_request_reference_id,
item.response.token.peek()
);
let redirection_data = Some(RedirectForm::Form {
endpoint: redirect_url,
method: Method::Get,
form_fields: Default::default(),
});
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.data.transaction_id),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, GigadatTransactionStatusResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, GigadatTransactionStatusResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let connector_response = item.response.data.as_ref().map(|sync_data| {
ConnectorResponseData::with_additional_payment_method_data(
AdditionalPaymentMethodConnectorResponse::BankRedirect {
interac: Some(InteracCustomerInfo {
customer_info: Some(build_interac_customer_info_details(
sync_data,
item.response.interac_bank_name.clone(),
)),
}),
},
)
});
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
connector_response,
..item.data
})
}
}
fn build_interac_customer_info_details(
sync_data: &GigadatSyncData,
bank_name: Option<Secret<String>>,
) -> common_types::payments::InteracCustomerInfoDetails {
common_types::payments::InteracCustomerInfoDetails {
customer_name: sync_data.name.clone(),
customer_email: sync_data.email.clone(),
customer_phone_number: sync_data.mobile.clone(),
customer_bank_id: None,
customer_bank_name: bank_name,
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct GigadatRefundRequest {
pub amount: FloatMajorUnit,
pub transaction_id: String,
pub campaign_id: Secret<String>,
}
impl<F> TryFrom<&GigadatRouterData<&RefundsRouterData<F>>> for GigadatRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &GigadatRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let auth_type = GigadatAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
amount: item.amount.to_owned(),
transaction_id: item.router_data.request.connector_transaction_id.clone(),
campaign_id: auth_type.campaign_id,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
success: bool,
data: GigadatPaymentData,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = match item.http_code {
200 => enums::RefundStatus::Success,
400 | 401 | 422 => enums::RefundStatus::Failure,
_ => enums::RefundStatus::Pending,
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.data.transaction_id.to_string(),
refund_status,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GigadatPayoutQuoteRequest {
pub amount: FloatMajorUnit,
pub campaign: Secret<String>,
pub currency: Currency,
pub email: Email,
pub mobile: Secret<String>,
pub name: Secret<String>,
pub site: String,
pub transaction_id: String,
#[serde(rename = "type")]
pub transaction_type: GidadatTransactionType,
pub user_id: id_type::CustomerId,
pub user_ip: Secret<String, IpAddress>,
pub sandbox: bool,
}
// Payouts fulfill request transform
#[cfg(feature = "payouts")]
impl TryFrom<&GigadatRouterData<&PayoutsRouterData<PoQuote>>> for GigadatPayoutQuoteRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &GigadatRouterData<&PayoutsRouterData<PoQuote>>,
) -> Result<Self, Self::Error> {
match item.router_data.get_payout_method_data()? {
PayoutMethodData::BankRedirect(BankRedirect::Interac(interac_data)) => {
let metadata: GigadatConnectorMetadataObject =
utils::to_connector_meta_from_secret(
item.router_data.connector_meta_data.clone(),
)
.change_context(
errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
},
)?;
let router_data = item.router_data;
let name = router_data.get_billing_full_name()?;
let email = interac_data.email;
let mobile = router_data.get_billing_phone_number()?;
let currency = item.router_data.request.destination_currency;
let user_ip = router_data.request.get_browser_info()?.get_ip_address()?;
let auth_type = GigadatAuthType::try_from(&item.router_data.connector_auth_type)?;
let sandbox = match item.router_data.test_mode {
Some(true) => true,
Some(false) | None => false,
};
Ok(Self {
user_id: router_data.get_customer_id()?,
site: metadata.site,
user_ip,
currency,
amount: item.amount,
transaction_id: router_data.connector_request_reference_id.clone(),
transaction_type: GidadatTransactionType::Eto,
name,
email,
mobile,
campaign: auth_type.campaign_id,
sandbox,
})
}
PayoutMethodData::Card(_)
| PayoutMethodData::Bank(_)
| PayoutMethodData::Wallet(_)
| PayoutMethodData::Passthrough(_) => Err(errors::ConnectorError::NotSupported {
message: "Payment Method Not Supported".to_string(),
connector: "Gigadat",
})?,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigadatPayoutQuoteResponse {
pub token: Secret<String>,
pub data: GigadatPayoutData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GigadatPayoutData {
pub transaction_id: String,
#[serde(rename = "type")]
pub transaction_type: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct GigadatPayoutMeta {
pub token: Secret<String>,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, GigadatPayoutQuoteResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, GigadatPayoutQuoteResponse>,
) -> Result<Self, Self::Error> {
let connector_meta = serde_json::json!(GigadatPayoutMeta {
token: item.response.token,
});
Ok(Self {
response: Ok(PayoutsResponseData {
status: None,
connector_payout_id: Some(item.response.data.transaction_id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: Some(Secret::new(connector_meta)),
}),
..item.data
})
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigadatPayoutResponse {
pub id: String,
pub status: GigadatPayoutStatus,
pub data: GigadatPayoutData,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, GigadatPayoutResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, GigadatPayoutResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::from(item.response.status)),
connector_payout_id: Some(item.response.data.transaction_id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigadatPayoutSyncResponse {
pub status: GigadatPayoutStatus,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GigadatPayoutStatus {
StatusInited,
StatusSuccess,
StatusRejected,
StatusRejected1,
StatusExpired,
StatusAborted1,
StatusPending,
StatusFailed,
}
#[cfg(feature = "payouts")]
impl From<GigadatPayoutStatus> for enums::PayoutStatus {
fn from(item: GigadatPayoutStatus) -> Self {
match item {
GigadatPayoutStatus::StatusSuccess => Self::Success,
GigadatPayoutStatus::StatusPending => Self::RequiresFulfillment,
GigadatPayoutStatus::StatusInited => Self::Pending,
GigadatPayoutStatus::StatusRejected
| GigadatPayoutStatus::StatusExpired
| GigadatPayoutStatus::StatusRejected1
| GigadatPayoutStatus::StatusAborted1
| GigadatPayoutStatus::StatusFailed => Self::Failed,
}
}
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, GigadatPayoutSyncResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, GigadatPayoutSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::from(item.response.status)),
connector_payout_id: None,
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct GigadatErrorResponse {
pub err: String,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct GigadatRefundErrorResponse {
pub error: Vec<Error>,
pub message: String,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct Error {
pub code: Option<String>,
pub detail: String,
}
#[derive(Debug, Deserialize)]
pub struct GigadatWebhookQueryParameters {
pub transaction: String,
pub status: GigadatTransactionStatus,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GigadatWebhookKeyValueBody {
#[serde(rename = "type")]
pub webhook_type: String,
pub final_type: Option<String>,
pub cpi_type: Option<String>,
// donot remove the below fields
pub name: Option<Secret<String>>,
pub mobile: Option<Secret<String>>,
pub user_id: Option<Secret<String>>,
pub email: Option<Email>,
pub financial_institution: Option<Secret<String>>,
}
impl GigadatWebhookKeyValueBody {
pub fn decode_from_url(body_str: &str) -> Result<Self, errors::ConnectorError> {
serde_urlencoded::from_str(body_str)
.map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed)
}
}
|
crates__hyperswitch_connectors__src__connectors__globalpay.rs
|
mod requests;
mod response;
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::IncomingWebhookEvent;
use common_enums::{enums, CallConnectorAction, PaymentAction};
use common_utils::{
crypto,
errors::{CustomResult, ReportSwitchExt},
ext_traits::{ByteSliceExt, BytesExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
CompleteAuthorize,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData, SyncRequestType,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
RefundsRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, CaptureSyncMethod, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration,
ConnectorRedirectResponse, ConnectorSpecifications, ConnectorValidation,
PaymentsCompleteAuthorize,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{
PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType,
PaymentsSyncType, PaymentsVoidType, RefreshTokenType, RefundExecuteType, RefundSyncType,
Response, TokenizationType,
},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},
};
use masking::{Mask, PeekInterface};
use requests::{GlobalpayPaymentsRequest, GlobalpayRefreshTokenRequest};
use response::{
GlobalpayPaymentsResponse, GlobalpayRefreshTokenErrorResponse, GlobalpayRefreshTokenResponse,
};
use serde_json::Value;
use crate::{
connectors::globalpay::response::GlobalpayPaymentMethodsResponse,
constants::headers,
types::{RefreshTokenRouterData, ResponseRouterData},
utils::{
convert_amount, get_header_key_value, is_mandate_supported, ForeignTryFrom,
PaymentMethodDataType, RefundsRequestData,
},
};
#[derive(Clone)]
pub struct Globalpay {
amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Globalpay {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Globalpay
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let access_token = req
.access_token
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![
(
headers::CONTENT_TYPE.to_string(),
PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
),
("X-GP-Version".to_string(), "2021-03-22".to_string().into()),
(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", access_token.token.peek()).into_masked(),
),
])
}
}
impl ConnectorCommon for Globalpay {
fn id(&self) -> &'static str {
"globalpay"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.globalpay.base_url.as_ref()
}
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: transformers::GlobalpayErrorResponse = res
.response
.parse_struct("Globalpay ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_code,
message: response.detailed_error_description,
reason: None,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Globalpay {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::PaypalRedirect,
PaymentMethodDataType::GooglePay,
PaymentMethodDataType::Ideal,
PaymentMethodDataType::Sofort,
PaymentMethodDataType::Eps,
PaymentMethodDataType::Giropay,
]);
is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl PaymentsCompleteAuthorize for Globalpay {}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Globalpay
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}transactions/{}/confirmation",
self.base_url(connectors),
req.request
.connector_transaction_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorTransactionID)?
))
}
fn get_request_body(
&self,
_req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Ok(RequestContent::Json(Box::new(serde_json::json!({}))))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: GlobalpayPaymentsResponse = res
.response
.parse_struct("Globalpay PaymentsResponse")
.switch()?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::ConnectorAccessToken for Globalpay {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Globalpay {
fn get_headers(
&self,
_req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![
(
headers::CONTENT_TYPE.to_string(),
RefreshTokenType::get_content_type(self).to_string().into(),
),
("X-GP-Version".to_string(), "2021-03-22".to_string().into()),
])
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "accesstoken"))
}
fn build_request(
&self,
req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&RefreshTokenType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefreshTokenType::get_headers(self, req, connectors)?)
.set_body(RefreshTokenType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn get_request_body(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = GlobalpayRefreshTokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
&self,
data: &RefreshTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
let response: GlobalpayRefreshTokenResponse = res
.response
.parse_struct("Globalpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: GlobalpayRefreshTokenErrorResponse = res
.response
.parse_struct("Globalpay ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_code,
message: response.detailed_error_description,
reason: None,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl api::Payment for Globalpay {}
impl api::PaymentToken for Globalpay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Globalpay
{
fn get_headers(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/payment-methods", self.base_url(connectors),))
}
fn build_request(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(TokenizationType::get_headers(self, req, connectors)?)
.set_body(TokenizationType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn get_request_body(
&self,
req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = requests::GlobalPayPaymentMethodsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
&self,
data: &TokenizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<TokenizationRouterData, errors::ConnectorError> {
let response: GlobalpayPaymentMethodsResponse = res
.response
.parse_struct("GlobalpayPaymentMethodsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::MandateSetup for Globalpay {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Globalpay
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Globalpay".to_string())
.into(),
)
}
}
impl api::PaymentVoid for Globalpay {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Globalpay {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/transactions/{}/reversal",
self.base_url(connectors),
req.request.connector_transaction_id
))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = req
.request
.minor_amount
.and_then(|amount| {
req.request
.currency
.map(|currency| convert_amount(self.amount_converter, amount, currency))
})
.transpose()?;
let connector_router_data = requests::GlobalpayCancelRouterData::from((amount, req));
let connector_req = requests::GlobalpayCancelRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: GlobalpayPaymentsResponse = res
.response
.parse_struct("Globalpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::PaymentSync for Globalpay {}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Globalpay {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}transactions/{}",
self.base_url(connectors),
req.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: GlobalpayPaymentsResponse = res
.response
.parse_struct("Globalpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let is_multiple_capture_sync = match data.request.sync_type {
SyncRequestType::MultipleCaptureSync(_) => true,
SyncRequestType::SinglePaymentSync => false,
};
RouterData::foreign_try_from((
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
is_multiple_capture_sync,
))
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_multiple_capture_sync_method(
&self,
) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> {
Ok(CaptureSyncMethod::Individual)
}
}
impl api::PaymentCapture for Globalpay {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Globalpay {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/transactions/{}/capture",
self.base_url(connectors),
req.request.connector_transaction_id
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = requests::GlobalPayRouterData::from((amount, req));
let connector_req = requests::GlobalpayCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
.set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: GlobalpayPaymentsResponse = res
.response
.parse_struct("Globalpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::PaymentSession for Globalpay {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Globalpay {}
impl api::PaymentAuthorize for Globalpay {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Globalpay {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}transactions", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = requests::GlobalPayRouterData::from((amount, req));
let connector_req = GlobalpayPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: GlobalpayPaymentsResponse = res
.response
.parse_struct("Globalpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::Refund for Globalpay {}
impl api::RefundExecute for Globalpay {}
impl api::RefundSync for Globalpay {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Globalpay {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}transactions/{}/refund",
self.base_url(connectors),
req.request.connector_transaction_id
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = requests::GlobalPayRouterData::from((amount, req));
let connector_req = requests::GlobalpayRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: GlobalpayPaymentsResponse = res
.response
.parse_struct("globalpay RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Globalpay {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}transactions/{}",
self.base_url(connectors),
refund_id
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: GlobalpayPaymentsResponse = res
.response
.parse_struct("globalpay RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Globalpay {
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::Sha512))
}
fn get_webhook_source_verification_signature(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let signature = get_header_key_value("x-gp-signature", request.headers)?;
Ok(signature.as_bytes().to_vec())
}
fn get_webhook_source_verification_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let payload: Value = request.body.parse_struct("GlobalpayWebhookBody").switch()?;
let mut payload_str = serde_json::to_string(&payload)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let sec = std::str::from_utf8(&connector_webhook_secrets.secret)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
payload_str.push_str(sec);
Ok(payload_str.into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let details: response::GlobalpayWebhookObjectId = request
.body
.parse_struct("GlobalpayWebhookObjectId")
.switch()?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(details.id),
))
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let details: response::GlobalpayWebhookObjectEventType = request
.body
.parse_struct("GlobalpayWebhookObjectEventType")
.switch()?;
Ok(match details.status {
response::GlobalpayWebhookStatus::Declined => {
IncomingWebhookEvent::PaymentIntentFailure
}
response::GlobalpayWebhookStatus::Captured => {
IncomingWebhookEvent::PaymentIntentSuccess
}
response::GlobalpayWebhookStatus::Unknown => IncomingWebhookEvent::EventNotSupported,
})
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Ok(Box::new(
request
.body
.parse_struct::<GlobalpayPaymentsResponse>("GlobalpayPaymentsResponse")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?,
))
}
}
impl ConnectorRedirectResponse for Globalpay {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<Value>,
action: PaymentAction,
) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
match action {
PaymentAction::PSync
| PaymentAction::CompleteAuthorize
| PaymentAction::PaymentAuthenticateCompleteAuthorize => {
Ok(CallConnectorAction::Trigger)
}
}
}
}
static GLOBALPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::UnionPay,
];
let mut globalpay_supported_payment_methods = SupportedPaymentMethods::new();
globalpay_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
globalpay_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
globalpay_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Ideal,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
globalpay_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Giropay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
globalpay_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Sofort,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
globalpay_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Eps,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
globalpay_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
globalpay_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Paypal,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
globalpay_supported_payment_methods
});
static GLOBALPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Globalpay",
description: "Global Payments is an American multinational financial technology company that provides payment technology and services to merchants, issuers and consumers.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static GLOBALPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];
impl ConnectorSpecifications for Globalpay {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&GLOBALPAY_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*GLOBALPAY_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&GLOBALPAY_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__gocardless.rs
|
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use common_enums::enums;
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
CreateConnectorCustomer, PreProcessing,
},
router_request_types::{
AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData,
PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, PaymentsSyncType, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},
};
use masking::{Mask, PeekInterface};
use transformers as gocardless;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, is_mandate_supported, PaymentMethodDataType},
};
#[derive(Clone)]
pub struct Gocardless {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Gocardless {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Gocardless {}
impl api::PaymentSession for Gocardless {}
impl api::ConnectorAccessToken for Gocardless {}
impl api::MandateSetup for Gocardless {}
impl api::PaymentAuthorize for Gocardless {}
impl api::PaymentSync for Gocardless {}
impl api::PaymentCapture for Gocardless {}
impl api::PaymentVoid for Gocardless {}
impl api::Refund for Gocardless {}
impl api::RefundExecute for Gocardless {}
impl api::RefundSync for Gocardless {}
impl api::PaymentToken for Gocardless {}
impl api::ConnectorCustomer for Gocardless {}
impl api::PaymentsPreProcessing for Gocardless {}
const GOCARDLESS_VERSION: &str = "2015-07-06";
const GOCARDLESS_VERSION_HEADER: &str = "GoCardless-Version";
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Gocardless
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
GOCARDLESS_VERSION_HEADER.to_string(),
GOCARDLESS_VERSION.to_string().into(),
),
];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Gocardless {
fn id(&self) -> &'static str {
"gocardless"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.gocardless.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = gocardless::GocardlessAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", auth.access_token.peek()).into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: gocardless::GocardlessErrorResponse = res
.response
.parse_struct("GocardlessErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_iter = response.error.errors.iter();
let mut error_reason: Vec<String> = Vec::new();
for error in error_iter {
let reason = error.field.clone().map_or(error.message.clone(), |field| {
format!("{} {}", field, error.message)
});
error_reason.push(reason)
}
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.code.to_string(),
message: response.error.error_type,
reason: Some(error_reason.join("; ")),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>
for Gocardless
{
fn get_headers(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
_req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/customers", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &ConnectorCustomerRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = gocardless::GocardlessCustomerRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::ConnectorCustomerType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::ConnectorCustomerType::get_headers(
self, req, connectors,
)?)
.set_body(types::ConnectorCustomerType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &ConnectorCustomerRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>,
errors::ConnectorError,
>
where
CreateConnectorCustomer: Clone,
ConnectorCustomerData: Clone,
PaymentsResponseData: Clone,
{
let response: gocardless::GocardlessCustomerResponse = res
.response
.parse_struct("GocardlessCustomerResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Gocardless
{
fn get_headers(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
_req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/customer_bank_accounts",
self.base_url(connectors),
))
}
fn get_request_body(
&self,
req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = gocardless::GocardlessBankAccountRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::TokenizationType::get_headers(self, req, connectors)?)
.set_body(types::TokenizationType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &TokenizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<TokenizationRouterData, errors::ConnectorError>
where
PaymentMethodToken: Clone,
PaymentMethodTokenizationData: Clone,
PaymentsResponseData: Clone,
{
let response: gocardless::GocardlessBankAccountResponse = res
.response
.parse_struct("GocardlessBankAccountResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
for Gocardless
{
}
impl ConnectorValidation for Gocardless {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::SepaBankDebit,
PaymentMethodDataType::AchBankDebit,
PaymentMethodDataType::BecsBankDebit,
PaymentMethodDataType::BacsBankDebit,
]);
is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Gocardless {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Gocardless {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Gocardless
{
fn get_headers(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
_req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/mandates", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = gocardless::GocardlessMandateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
// Preprocessing flow is to create mandate, which should to be called only in case of First mandate
if req.request.setup_mandate_details.is_some() {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::SetupMandateType::get_headers(self, req, connectors)?)
.set_body(types::SetupMandateType::get_request_body(
self, req, connectors,
)?)
.build(),
))
} else {
Ok(None)
}
}
fn handle_response(
&self,
data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
let response: gocardless::GocardlessMandateResponse = res
.response
.parse_struct("GocardlessMandateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Gocardless {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = gocardless::GocardlessRouterData::from((amount, req));
let connector_req =
gocardless::GocardlessPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: gocardless::GocardlessPaymentsResponse = res
.response
.parse_struct("GocardlessPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Gocardless {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/payments/{}",
self.base_url(connectors),
req.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: gocardless::GocardlessPaymentsResponse = res
.response
.parse_struct("GocardlessPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Gocardless {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Gocardless {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Gocardless {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/refunds", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = gocardless::GocardlessRouterData::from((refund_amount, req));
let connector_req = gocardless::GocardlessRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: gocardless::RefundResponse = res
.response
.parse_struct("gocardless RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Gocardless {
fn build_request(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(None)
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Gocardless {
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let signature = request
.headers
.get("Webhook-Signature")
.map(|header_value| {
header_value
.to_str()
.map(String::from)
.map_err(|_| errors::ConnectorError::WebhookSignatureNotFound)
})
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)??;
hex::decode(signature).change_context(errors::ConnectorError::WebhookSignatureNotFound)
}
fn get_webhook_source_verification_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(format!("{}", String::from_utf8_lossy(request.body))
.as_bytes()
.to_vec())
}
fn get_webhook_object_reference_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
let details: gocardless::GocardlessWebhookEvent = request
.body
.parse_struct("GocardlessWebhookEvent")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let first_event = details
.events
.first()
.ok_or_else(|| errors::ConnectorError::WebhookReferenceIdNotFound)?;
let reference_id = match &first_event.links {
transformers::WebhooksLink::PaymentWebhooksLink(link) => {
let payment_id = api_models::payments::PaymentIdType::ConnectorTransactionId(
link.payment.to_owned(),
);
ObjectReferenceId::PaymentId(payment_id)
}
transformers::WebhooksLink::RefundWebhookLink(link) => {
let refund_id =
api_models::webhooks::RefundIdType::ConnectorRefundId(link.refund.to_owned());
ObjectReferenceId::RefundId(refund_id)
}
transformers::WebhooksLink::MandateWebhookLink(link) => {
let mandate_id = api_models::webhooks::MandateIdType::ConnectorMandateId(
link.mandate.to_owned(),
);
ObjectReferenceId::MandateId(mandate_id)
}
};
Ok(reference_id)
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let details: gocardless::GocardlessWebhookEvent = request
.body
.parse_struct("GocardlessWebhookEvent")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let first_event = details
.events
.first()
.ok_or_else(|| errors::ConnectorError::WebhookReferenceIdNotFound)?;
let event_type = match &first_event.action {
transformers::WebhookAction::PaymentsAction(action) => match action {
transformers::PaymentsAction::Created
| transformers::PaymentsAction::Submitted
| transformers::PaymentsAction::CustomerApprovalGranted => {
IncomingWebhookEvent::PaymentIntentProcessing
}
transformers::PaymentsAction::CustomerApprovalDenied
| transformers::PaymentsAction::Failed
| transformers::PaymentsAction::Cancelled
| transformers::PaymentsAction::LateFailureSettled => {
IncomingWebhookEvent::PaymentIntentFailure
}
transformers::PaymentsAction::Confirmed | transformers::PaymentsAction::PaidOut => {
IncomingWebhookEvent::PaymentIntentSuccess
}
transformers::PaymentsAction::SurchargeFeeDebited
| transformers::PaymentsAction::ResubmissionRequired => {
IncomingWebhookEvent::EventNotSupported
}
},
transformers::WebhookAction::RefundsAction(action) => match action {
transformers::RefundsAction::Failed => IncomingWebhookEvent::RefundFailure,
transformers::RefundsAction::Paid => IncomingWebhookEvent::RefundSuccess,
transformers::RefundsAction::RefundSettled
| transformers::RefundsAction::FundsReturned
| transformers::RefundsAction::Created => IncomingWebhookEvent::EventNotSupported,
},
transformers::WebhookAction::MandatesAction(action) => match action {
transformers::MandatesAction::Active | transformers::MandatesAction::Reinstated => {
IncomingWebhookEvent::MandateActive
}
transformers::MandatesAction::Expired
| transformers::MandatesAction::Cancelled
| transformers::MandatesAction::Failed
| transformers::MandatesAction::Consumed => IncomingWebhookEvent::MandateRevoked,
transformers::MandatesAction::Created
| transformers::MandatesAction::CustomerApprovalGranted
| transformers::MandatesAction::CustomerApprovalSkipped
| transformers::MandatesAction::Transferred
| transformers::MandatesAction::Submitted
| transformers::MandatesAction::ResubmissionRequested
| transformers::MandatesAction::Replaced
| transformers::MandatesAction::Blocked => IncomingWebhookEvent::EventNotSupported,
},
};
Ok(event_type)
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let details: gocardless::GocardlessWebhookEvent = request
.body
.parse_struct("GocardlessWebhookEvent")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let first_event = details
.events
.first()
.ok_or_else(|| errors::ConnectorError::WebhookReferenceIdNotFound)?
.clone();
match first_event.resource_type {
transformers::WebhookResourceType::Payments => Ok(Box::new(
gocardless::GocardlessPaymentsResponse::try_from(&first_event)?,
)),
transformers::WebhookResourceType::Refunds
| transformers::WebhookResourceType::Mandates => Ok(Box::new(first_event)),
}
}
}
static GOCARDLESS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::SequentialAutomatic,
];
let mut gocardless_supported_payment_methods = SupportedPaymentMethods::new();
gocardless_supported_payment_methods.add(
enums::PaymentMethod::BankDebit,
enums::PaymentMethodType::Ach,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
gocardless_supported_payment_methods.add(
enums::PaymentMethod::BankDebit,
enums::PaymentMethodType::Becs,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
gocardless_supported_payment_methods.add(
enums::PaymentMethod::BankDebit,
enums::PaymentMethodType::Sepa,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
gocardless_supported_payment_methods
});
static GOCARDLESS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "GoCardless",
description: "GoCardless is a fintech company that specialises in bank payments including recurring payments.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static GOCARDLESS_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [
enums::EventClass::Payments,
enums::EventClass::Refunds,
enums::EventClass::Mandates,
];
impl ConnectorSpecifications for Gocardless {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&GOCARDLESS_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*GOCARDLESS_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&GOCARDLESS_SUPPORTED_WEBHOOK_FLOWS)
}
fn should_call_connector_customer(
&self,
_payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> bool {
true
}
}
|
crates__hyperswitch_connectors__src__connectors__gocardless__transformers.rs
|
use common_enums::{enums, CountryAlpha2, UsStatesAbbreviation};
use common_utils::{
id_type,
pii::{self, IpAddress},
types::MinorUnit,
};
use hyperswitch_domain_models::{
address::AddressDetails,
payment_method_data::{BankDebitData, PaymentMethodData},
router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
router_flow_types::refunds::Execute,
router_request_types::{
ConnectorCustomerData, PaymentMethodTokenizationData, ResponseId, SetupMandateRequestData,
},
router_response_types::{
ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, RefundsResponseData,
},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
ResponseRouterData,
},
utils::{
self, AddressDetailsData, BrowserInformationData, CustomerData, ForeignTryFrom,
PaymentsAuthorizeRequestData, PaymentsSetupMandateRequestData, RouterData as _,
},
};
pub struct GocardlessRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for GocardlessRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct GocardlessCustomerRequest {
customers: GocardlessCustomer,
}
#[derive(Default, Debug, Serialize)]
pub struct GocardlessCustomer {
address_line1: Option<Secret<String>>,
address_line2: Option<Secret<String>>,
address_line3: Option<Secret<String>>,
city: Option<Secret<String>>,
region: Option<Secret<String>>,
country_code: Option<CountryAlpha2>,
email: pii::Email,
given_name: Secret<String>,
family_name: Secret<String>,
metadata: CustomerMetaData,
danish_identity_number: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
swedish_identity_number: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize)]
pub struct CustomerMetaData {
crm_id: Option<Secret<id_type::CustomerId>>,
}
impl TryFrom<&types::ConnectorCustomerRouterData> for GocardlessCustomerRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> {
let email = item.request.get_email()?;
let billing_details_name = item.get_billing_full_name()?.expose();
let (given_name, family_name) = billing_details_name
.trim()
.rsplit_once(' ')
.unwrap_or((&billing_details_name, &billing_details_name));
let billing_address = item.get_billing_address()?;
let metadata = CustomerMetaData {
crm_id: item.customer_id.clone().map(Secret::new),
};
let region = get_region(billing_address)?;
Ok(Self {
customers: GocardlessCustomer {
email,
given_name: Secret::new(given_name.to_string()),
family_name: Secret::new(family_name.to_string()),
metadata,
address_line1: billing_address.line1.to_owned(),
address_line2: billing_address.line2.to_owned(),
address_line3: billing_address.line3.to_owned(),
country_code: billing_address.country,
region,
// Should be populated based on the billing country
danish_identity_number: None,
postal_code: billing_address.zip.to_owned(),
// Should be populated based on the billing country
swedish_identity_number: None,
city: billing_address.city.clone().map(Secret::new),
},
})
}
}
fn get_region(
address_details: &AddressDetails,
) -> Result<Option<Secret<String>>, error_stack::Report<errors::ConnectorError>> {
match address_details.country {
Some(CountryAlpha2::US) => {
let state = address_details.get_state()?.to_owned();
Ok(Some(Secret::new(
UsStatesAbbreviation::foreign_try_from(state.expose())?.to_string(),
)))
}
_ => Ok(None),
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GocardlessCustomerResponse {
customers: Customers,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Customers {
id: Secret<String>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
GocardlessCustomerResponse,
ConnectorCustomerData,
PaymentsResponseData,
>,
> for RouterData<F, ConnectorCustomerData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
GocardlessCustomerResponse,
ConnectorCustomerData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(
item.response.customers.id.expose(),
),
)),
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct GocardlessBankAccountRequest {
customer_bank_accounts: CustomerBankAccounts,
}
#[derive(Debug, Serialize)]
pub struct CustomerBankAccounts {
#[serde(flatten)]
accounts: CustomerBankAccount,
links: CustomerAccountLink,
}
#[derive(Debug, Serialize)]
pub struct CustomerAccountLink {
customer: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum CustomerBankAccount {
InternationalBankAccount(InternationalBankAccount),
AUBankAccount(AUBankAccount),
USBankAccount(USBankAccount),
}
#[derive(Debug, Serialize)]
pub struct InternationalBankAccount {
iban: Secret<String>,
account_holder_name: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct AUBankAccount {
country_code: CountryAlpha2,
account_number: Secret<String>,
branch_code: Secret<String>,
account_holder_name: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub struct USBankAccount {
country_code: CountryAlpha2,
account_number: Secret<String>,
bank_code: Secret<String>,
account_type: AccountType,
account_holder_name: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AccountType {
Checking,
Savings,
}
impl TryFrom<&types::TokenizationRouterData> for GocardlessBankAccountRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
let customer = item.get_connector_customer_id()?;
let accounts = CustomerBankAccount::try_from(item)?;
let links = CustomerAccountLink {
customer: Secret::new(customer),
};
Ok(Self {
customer_bank_accounts: CustomerBankAccounts { accounts, links },
})
}
}
impl TryFrom<&types::TokenizationRouterData> for CustomerBankAccount {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
match &item.request.payment_method_data {
PaymentMethodData::BankDebit(bank_debit_data) => {
Self::try_from((bank_debit_data, item))
}
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Gocardless"),
)
.into())
}
}
}
}
impl TryFrom<(&BankDebitData, &types::TokenizationRouterData)> for CustomerBankAccount {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(bank_debit_data, item): (&BankDebitData, &types::TokenizationRouterData),
) -> Result<Self, Self::Error> {
match bank_debit_data {
BankDebitData::AchBankDebit {
account_number,
routing_number,
bank_type,
..
} => {
let bank_type = bank_type.ok_or_else(utils::missing_field_err("bank_type"))?;
let country_code = item.get_billing_country()?;
let account_holder_name = item.get_billing_full_name()?;
let us_bank_account = USBankAccount {
country_code,
account_number: account_number.clone(),
bank_code: routing_number.clone(),
account_type: AccountType::from(bank_type),
account_holder_name,
};
Ok(Self::USBankAccount(us_bank_account))
}
BankDebitData::BecsBankDebit {
account_number,
bsb_number,
..
} => {
let country_code = item.get_billing_country()?;
let account_holder_name = item.get_billing_full_name()?;
let au_bank_account = AUBankAccount {
country_code,
account_number: account_number.clone(),
branch_code: bsb_number.clone(),
account_holder_name,
};
Ok(Self::AUBankAccount(au_bank_account))
}
BankDebitData::SepaBankDebit { iban, .. } => {
let account_holder_name = item.get_billing_full_name()?;
let international_bank_account = InternationalBankAccount {
iban: iban.clone(),
account_holder_name,
};
Ok(Self::InternationalBankAccount(international_bank_account))
}
BankDebitData::BacsBankDebit { .. } | BankDebitData::SepaGuarenteedBankDebit { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Gocardless"),
)
.into())
}
}
}
}
impl From<common_enums::BankType> for AccountType {
fn from(item: common_enums::BankType) -> Self {
match item {
common_enums::BankType::Checking => Self::Checking,
common_enums::BankType::Savings => Self::Savings,
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GocardlessBankAccountResponse {
customer_bank_accounts: CustomerBankAccountResponse,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CustomerBankAccountResponse {
pub id: Secret<String>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
GocardlessBankAccountResponse,
PaymentMethodTokenizationData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentMethodTokenizationData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
GocardlessBankAccountResponse,
PaymentMethodTokenizationData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.customer_bank_accounts.id.expose(),
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct GocardlessMandateRequest {
mandates: Mandate,
}
#[derive(Debug, Serialize)]
pub struct Mandate {
scheme: GocardlessScheme,
metadata: MandateMetaData,
payer_ip_address: Option<Secret<String, IpAddress>>,
links: MandateLink,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum GocardlessScheme {
Becs,
SepaCore,
Ach,
BecsNz,
}
#[derive(Debug, Serialize)]
pub struct MandateMetaData {
payment_reference: String,
}
#[derive(Debug, Serialize)]
pub struct MandateLink {
customer_bank_account: Secret<String>,
}
impl TryFrom<&types::SetupMandateRouterData> for GocardlessMandateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> {
let (scheme, payer_ip_address) = match &item.request.payment_method_data {
PaymentMethodData::BankDebit(bank_debit_data) => {
let payer_ip_address = get_ip_if_required(bank_debit_data, item)?;
Ok((
GocardlessScheme::try_from(bank_debit_data)?,
payer_ip_address,
))
}
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
"Setup Mandate flow for selected payment method through Gocardless".to_string(),
))
}
}?;
let payment_method_token = item.get_payment_method_token()?;
let customer_bank_account = match payment_method_token {
PaymentMethodToken::Token(token) => Ok(token),
PaymentMethodToken::ApplePayDecrypt(_)
| PaymentMethodToken::PazeDecrypt(_)
| PaymentMethodToken::GooglePayDecrypt(_) => {
Err(errors::ConnectorError::NotImplemented(
"Setup Mandate flow for selected payment method through Gocardless".to_string(),
))
}
}?;
Ok(Self {
mandates: Mandate {
scheme,
metadata: MandateMetaData {
payment_reference: item.connector_request_reference_id.clone(),
},
payer_ip_address,
links: MandateLink {
customer_bank_account,
},
},
})
}
}
fn get_ip_if_required(
bank_debit_data: &BankDebitData,
item: &types::SetupMandateRouterData,
) -> Result<Option<Secret<String, IpAddress>>, error_stack::Report<errors::ConnectorError>> {
let ip_address = item.request.get_browser_info()?.get_ip_address()?;
match bank_debit_data {
BankDebitData::AchBankDebit { .. } => Ok(Some(ip_address)),
BankDebitData::SepaBankDebit { .. }
| BankDebitData::SepaGuarenteedBankDebit { .. }
| BankDebitData::BecsBankDebit { .. }
| BankDebitData::BacsBankDebit { .. } => Ok(None),
}
}
impl TryFrom<&BankDebitData> for GocardlessScheme {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &BankDebitData) -> Result<Self, Self::Error> {
match item {
BankDebitData::AchBankDebit { .. } => Ok(Self::Ach),
BankDebitData::SepaBankDebit { .. } => Ok(Self::SepaCore),
BankDebitData::BecsBankDebit { .. } => Ok(Self::Becs),
BankDebitData::BacsBankDebit { .. } | BankDebitData::SepaGuarenteedBankDebit { .. } => {
Err(errors::ConnectorError::NotImplemented(
"Setup Mandate flow for selected payment method through Gocardless".to_string(),
)
.into())
}
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GocardlessMandateResponse {
mandates: MandateResponse,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MandateResponse {
id: Secret<String>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
GocardlessMandateResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
> for RouterData<F, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
GocardlessMandateResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let mandate_reference = Some(MandateReference {
connector_mandate_id: Some(item.response.mandates.id.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
connector_metadata: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
network_txn_id: None,
authentication_data: None,
charges: None,
}),
status: enums::AttemptStatus::Charged,
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct GocardlessPaymentsRequest {
payments: GocardlessPayment,
}
#[derive(Debug, Serialize)]
pub struct GocardlessPayment {
amount: MinorUnit,
currency: enums::Currency,
description: Option<String>,
metadata: PaymentMetaData,
links: PaymentLink,
}
#[derive(Debug, Serialize)]
pub struct PaymentMetaData {
payment_reference: String,
}
#[derive(Debug, Serialize)]
pub struct PaymentLink {
mandate: Secret<String>,
}
impl TryFrom<&GocardlessRouterData<&types::PaymentsAuthorizeRouterData>>
for GocardlessPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &GocardlessRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let mandate_id = if item.router_data.request.is_mandate_payment() {
item.router_data
.request
.connector_mandate_id()
.ok_or_else(utils::missing_field_err("mandate_id"))
} else {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("gocardless"),
)
.into())
}?;
let payments = GocardlessPayment {
amount: item.router_data.request.minor_amount,
currency: item.router_data.request.currency,
description: item.router_data.description.clone(),
metadata: PaymentMetaData {
payment_reference: item.router_data.connector_request_reference_id.clone(),
},
links: PaymentLink {
mandate: Secret::new(mandate_id),
},
};
Ok(Self { payments })
}
}
// Auth Struct
pub struct GocardlessAuthType {
pub(super) access_token: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for GocardlessAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
access_token: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GocardlessPaymentStatus {
PendingCustomerApproval,
PendingSubmission,
Submitted,
Confirmed,
PaidOut,
Cancelled,
CustomerApprovalDenied,
Failed,
}
impl From<GocardlessPaymentStatus> for enums::AttemptStatus {
fn from(item: GocardlessPaymentStatus) -> Self {
match item {
GocardlessPaymentStatus::PendingCustomerApproval
| GocardlessPaymentStatus::PendingSubmission
| GocardlessPaymentStatus::Submitted => Self::Pending,
GocardlessPaymentStatus::Confirmed | GocardlessPaymentStatus::PaidOut => Self::Charged,
GocardlessPaymentStatus::Cancelled => Self::Voided,
GocardlessPaymentStatus::CustomerApprovalDenied => Self::AuthenticationFailed,
GocardlessPaymentStatus::Failed => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GocardlessPaymentsResponse {
payments: PaymentResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentResponse {
status: GocardlessPaymentStatus,
id: String,
}
impl TryFrom<PaymentsResponseRouterData<GocardlessPaymentsResponse>>
for types::PaymentsAuthorizeRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<GocardlessPaymentsResponse>,
) -> Result<Self, Self::Error> {
let mandate_reference = MandateReference {
connector_mandate_id: Some(item.data.request.get_connector_mandate_id()?),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
};
Ok(Self {
status: enums::AttemptStatus::from(item.response.payments.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.payments.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(Some(mandate_reference)),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<GocardlessPaymentsResponse>>
for types::PaymentsSyncRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<GocardlessPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.payments.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.payments.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
#[derive(Default, Debug, Serialize)]
pub struct GocardlessRefundRequest {
refunds: GocardlessRefund,
}
#[derive(Default, Debug, Serialize)]
pub struct GocardlessRefund {
amount: MinorUnit,
metadata: RefundMetaData,
links: RefundLink,
}
#[derive(Default, Debug, Serialize)]
pub struct RefundMetaData {
refund_reference: String,
}
#[derive(Default, Debug, Serialize)]
pub struct RefundLink {
payment: String,
}
impl<F> TryFrom<&GocardlessRouterData<&types::RefundsRouterData<F>>> for GocardlessRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &GocardlessRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
refunds: GocardlessRefund {
amount: item.amount.to_owned(),
metadata: RefundMetaData {
refund_reference: item.router_data.connector_request_reference_id.clone(),
},
links: RefundLink {
payment: item.router_data.request.connector_transaction_id.clone(),
},
},
})
}
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
id: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::Pending,
}),
..item.data
})
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GocardlessErrorResponse {
pub error: GocardlessError,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GocardlessError {
pub message: String,
pub code: u16,
pub errors: Vec<Error>,
#[serde(rename = "type")]
pub error_type: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Error {
pub field: Option<String>,
pub message: String,
}
#[derive(Debug, Deserialize)]
pub struct GocardlessWebhookEvent {
pub events: Vec<WebhookEvent>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WebhookEvent {
pub resource_type: WebhookResourceType,
pub action: WebhookAction,
pub links: WebhooksLink,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WebhookResourceType {
Payments,
Refunds,
Mandates,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum WebhookAction {
PaymentsAction(PaymentsAction),
RefundsAction(RefundsAction),
MandatesAction(MandatesAction),
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PaymentsAction {
Created,
CustomerApprovalGranted,
CustomerApprovalDenied,
Submitted,
Confirmed,
PaidOut,
LateFailureSettled,
SurchargeFeeDebited,
Failed,
Cancelled,
ResubmissionRequired,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RefundsAction {
Created,
Failed,
Paid,
// Payout statuses
RefundSettled,
FundsReturned,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MandatesAction {
Created,
CustomerApprovalGranted,
CustomerApprovalSkipped,
Active,
Cancelled,
Failed,
Transferred,
Expired,
Submitted,
ResubmissionRequested,
Reinstated,
Replaced,
Consumed,
Blocked,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum WebhooksLink {
PaymentWebhooksLink(PaymentWebhooksLink),
RefundWebhookLink(RefundWebhookLink),
MandateWebhookLink(MandateWebhookLink),
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RefundWebhookLink {
pub refund: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PaymentWebhooksLink {
pub payment: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct MandateWebhookLink {
pub mandate: String,
}
impl TryFrom<&WebhookEvent> for GocardlessPaymentsResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &WebhookEvent) -> Result<Self, Self::Error> {
let id = match &item.links {
WebhooksLink::PaymentWebhooksLink(link) => link.payment.to_owned(),
WebhooksLink::RefundWebhookLink(_) | WebhooksLink::MandateWebhookLink(_) => {
Err(errors::ConnectorError::WebhookEventTypeNotFound)?
}
};
Ok(Self {
payments: PaymentResponse {
status: GocardlessPaymentStatus::try_from(&item.action)?,
id,
},
})
}
}
impl TryFrom<&WebhookAction> for GocardlessPaymentStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &WebhookAction) -> Result<Self, Self::Error> {
match item {
WebhookAction::PaymentsAction(action) => match action {
PaymentsAction::CustomerApprovalGranted | PaymentsAction::Submitted => {
Ok(Self::Submitted)
}
PaymentsAction::CustomerApprovalDenied => Ok(Self::CustomerApprovalDenied),
PaymentsAction::LateFailureSettled => Ok(Self::Failed),
PaymentsAction::Failed => Ok(Self::Failed),
PaymentsAction::Cancelled => Ok(Self::Cancelled),
PaymentsAction::Confirmed => Ok(Self::Confirmed),
PaymentsAction::PaidOut => Ok(Self::PaidOut),
PaymentsAction::SurchargeFeeDebited
| PaymentsAction::ResubmissionRequired
| PaymentsAction::Created => Err(errors::ConnectorError::WebhookEventTypeNotFound)?,
},
WebhookAction::RefundsAction(_) | WebhookAction::MandatesAction(_) => {
Err(errors::ConnectorError::WebhookEventTypeNotFound)?
}
}
}
}
|
crates__hyperswitch_connectors__src__connectors__helcim.rs
|
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::IncomingWebhookEvent;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
errors::api_error_response::ApiErrorResponse,
payments::payment_attempt::PaymentAttempt,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorTransactionId, ConnectorValidation,
},
configs::Connectors,
consts::NO_ERROR_CODE,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},
};
#[cfg(feature = "v2")]
use masking::PeekInterface;
use masking::{ExposeInterface, Mask};
use transformers as helcim;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{convert_amount, to_connector_meta, PaymentsAuthorizeRequestData},
};
#[derive(Clone)]
pub struct Helcim {
amount_convertor: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Helcim {
pub fn new() -> &'static Self {
&Self {
amount_convertor: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Helcim {}
impl api::PaymentSession for Helcim {}
impl api::ConnectorAccessToken for Helcim {}
impl api::MandateSetup for Helcim {}
impl api::PaymentAuthorize for Helcim {}
impl api::PaymentSync for Helcim {}
impl api::PaymentCapture for Helcim {}
impl api::PaymentVoid for Helcim {}
impl api::Refund for Helcim {}
impl api::RefundExecute for Helcim {}
impl api::RefundSync for Helcim {}
impl api::PaymentToken for Helcim {}
impl Helcim {
pub fn connector_transaction_id(
&self,
connector_meta: Option<&serde_json::Value>,
) -> CustomResult<Option<String>, errors::ConnectorError> {
let meta: helcim::HelcimMetaData = to_connector_meta(connector_meta.cloned())?;
Ok(Some(meta.preauth_transaction_id.to_string()))
}
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Helcim
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Helcim
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError>
{
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
//Helcim requires an Idempotency Key of length 25. We prefix every ID by "HS_".
const ID_LENGTH: usize = 22;
let mut idempotency_key = vec![(
headers::IDEMPOTENCY_KEY.to_string(),
common_utils::generate_id(ID_LENGTH, "HS").into_masked(),
)];
header.append(&mut api_key);
header.append(&mut idempotency_key);
Ok(header)
}
}
impl ConnectorCommon for Helcim {
fn id(&self) -> &'static str {
"helcim"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.helcim.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError>
{
let auth = helcim::HelcimAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::API_TOKEN.to_string(),
auth.api_key.expose().into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: helcim::HelcimErrorResponse = res
.response
.parse_struct("HelcimErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_string = match response {
transformers::HelcimErrorResponse::Payment(response) => match response.errors {
transformers::HelcimErrorTypes::StringType(error) => error,
transformers::HelcimErrorTypes::JsonType(error) => error.to_string(),
},
transformers::HelcimErrorResponse::General(error_string) => error_string,
};
Ok(ErrorResponse {
status_code: res.status_code,
code: NO_ERROR_CODE.to_owned(),
message: error_string.clone(),
reason: Some(error_string),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Helcim {
fn validate_connector_against_payment_request(
&self,
capture_method: Option<enums::CaptureMethod>,
_payment_method: enums::PaymentMethod,
_pmt: Option<enums::PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
match capture_method {
enums::CaptureMethod::Automatic
| enums::CaptureMethod::Manual
| enums::CaptureMethod::SequentialAutomatic => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
crate::utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Helcim {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Helcim {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Helcim {
fn get_headers(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError>
{
self.build_headers(req, connectors)
}
fn get_url(
&self,
_req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v2/payment/verify", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = helcim::HelcimVerifyRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
_req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Helcim".to_string())
.into(),
)
// Ok(Some(
// RequestBuilder::new()
// .method(Method::Post)
// .url(&types::SetupMandateType::get_url(self, req, connectors)?)
// .attach_default_headers()
// .headers(types::SetupMandateType::get_headers(self, req, connectors)?)
// .set_body(types::SetupMandateType::get_request_body(
// self, req, connectors,
// )?)
// .build(),
// ))
}
fn handle_response(
&self,
data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
let response: helcim::HelcimPaymentsResponse = res
.response
.parse_struct("Helcim PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Helcim {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError>
{
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
if req.request.is_auto_capture()? {
return Ok(format!("{}v2/payment/purchase", self.base_url(connectors)));
}
Ok(format!("{}v2/payment/preauth", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = convert_amount(
self.amount_convertor,
req.request.minor_amount,
req.request.currency,
)?;
let router_obj = helcim::HelcimRouterData::try_from((connector_router_data, req))?;
let connector_req = helcim::HelcimPaymentsRequest::try_from(&router_obj)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: helcim::HelcimPaymentsResponse = res
.response
.parse_struct("Helcim PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Helcim {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError>
{
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
types::PaymentsSyncType::get_content_type(self)
.to_string()
.into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}v2/card-transactions/{connector_payment_id}",
self.base_url(connectors)
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: helcim::HelcimPaymentsResponse = res
.response
.parse_struct("helcim PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
// fn get_multiple_capture_sync_method(
// &self,
// ) -> CustomResult<services::CaptureSyncMethod, errors::ConnectorError> {
// Ok(services::CaptureSyncMethod::Individual)
// }
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Helcim {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError>
{
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v2/payment/capture", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = convert_amount(
self.amount_convertor,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let router_obj = helcim::HelcimRouterData::try_from((connector_router_data, req))?;
let connector_req = helcim::HelcimCaptureRequest::try_from(&router_obj)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: helcim::HelcimPaymentsResponse = res
.response
.parse_struct("Helcim PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Helcim {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError>
{
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v2/payment/reverse", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = helcim::HelcimVoidRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: helcim::HelcimPaymentsResponse = res
.response
.parse_struct("HelcimPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Helcim {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError>
{
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v2/payment/refund", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = convert_amount(
self.amount_convertor,
req.request.minor_refund_amount,
req.request.currency,
)?;
let router_obj = helcim::HelcimRouterData::try_from((connector_router_data, req))?;
let connector_req = helcim::HelcimRefundRequest::try_from(&router_obj)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: helcim::RefundResponse =
res.response
.parse_struct("helcim RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Helcim {
fn get_headers(
&self,
req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError>
{
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
types::RefundSyncType::get_content_type(self)
.to_string()
.into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_refund_id = req
.request
.connector_refund_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?;
Ok(format!(
"{}v2/card-transactions/{connector_refund_id}",
self.base_url(connectors)
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: helcim::RefundResponse = res
.response
.parse_struct("helcim RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Helcim {
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_context: Option<&WebhookContext>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static HELCIM_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::UnionPay,
];
let mut helcim_supported_payment_methods = SupportedPaymentMethods::new();
helcim_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
helcim_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
helcim_supported_payment_methods
});
static HELCIM_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Helcim",
description:
"Helcim is a payment processing company that offers transparent, affordable merchant services for businesses of all sizes",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static HELCIM_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Helcim {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&HELCIM_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*HELCIM_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&HELCIM_SUPPORTED_WEBHOOK_FLOWS)
}
}
impl ConnectorTransactionId for Helcim {
#[cfg(feature = "v1")]
fn connector_transaction_id(
&self,
payment_attempt: &PaymentAttempt,
) -> Result<Option<String>, ApiErrorResponse> {
if payment_attempt.get_connector_payment_id().is_none() {
let metadata =
Self::connector_transaction_id(self, payment_attempt.connector_metadata.as_ref());
metadata.map_err(|_| ApiErrorResponse::ResourceIdNotFound)
} else {
Ok(payment_attempt
.get_connector_payment_id()
.map(ToString::to_string))
}
}
#[cfg(feature = "v2")]
fn connector_transaction_id(
&self,
payment_attempt: &PaymentAttempt,
) -> Result<Option<String>, ApiErrorResponse> {
use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
if payment_attempt.get_connector_payment_id().is_none() {
let metadata = Self::connector_transaction_id(
self,
payment_attempt
.connector_metadata
.as_ref()
.map(|connector_metadata| connector_metadata.peek()),
);
metadata.map_err(|_| ApiErrorResponse::ResourceIdNotFound)
} else {
Ok(payment_attempt
.get_connector_payment_id()
.map(ToString::to_string))
}
}
}
|
crates__hyperswitch_connectors__src__connectors__helcim__transformers.rs
|
use common_enums::enums;
use common_utils::{
pii::{Email, IpAddress},
types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{Card, PaymentMethodData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{ResponseId, SetupMandateRequestData},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
ResponseRouterData,
},
utils::{
self, AddressDetailsData, BrowserInformationData, CardData, PaymentsAuthorizeRequestData,
PaymentsCancelRequestData, PaymentsCaptureRequestData, PaymentsSetupMandateRequestData,
RefundsRequestData, RouterData as RouterDataUtils,
},
};
#[derive(Debug, Serialize)]
pub struct HelcimRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(FloatMajorUnit, T)> for HelcimRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (FloatMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
pub fn check_currency(
currency: enums::Currency,
) -> Result<enums::Currency, errors::ConnectorError> {
if currency == enums::Currency::USD {
Ok(currency)
} else {
Err(errors::ConnectorError::NotSupported {
message: format!("currency {currency} is not supported for this merchant account"),
connector: "Helcim",
})?
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimVerifyRequest {
currency: enums::Currency,
ip_address: Secret<String, IpAddress>,
card_data: HelcimCard,
billing_address: HelcimBillingAddress,
#[serde(skip_serializing_if = "Option::is_none")]
ecommerce: Option<bool>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimPaymentsRequest {
amount: FloatMajorUnit,
currency: enums::Currency,
ip_address: Secret<String, IpAddress>,
card_data: HelcimCard,
invoice: HelcimInvoice,
billing_address: HelcimBillingAddress,
//The ecommerce field is an optional field in Connector Helcim.
//Setting the ecommerce field to true activates the Helcim Fraud Defender.
#[serde(skip_serializing_if = "Option::is_none")]
ecommerce: Option<bool>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimBillingAddress {
name: Secret<String>,
street1: Secret<String>,
postal_code: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
street2: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
city: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
email: Option<Email>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimInvoice {
invoice_number: String,
line_items: Vec<HelcimLineItems>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimLineItems {
description: String,
quantity: u8,
price: FloatMajorUnit,
total: FloatMajorUnit,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimCard {
card_number: cards::CardNumber,
card_expiry: Secret<String>,
card_c_v_v: Secret<String>,
}
impl TryFrom<(&SetupMandateRouterData, &Card)> for HelcimVerifyRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: (&SetupMandateRouterData, &Card)) -> Result<Self, Self::Error> {
let (item, req_card) = value;
let card_data = HelcimCard {
card_expiry: req_card
.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?,
card_number: req_card.card_number.clone(),
card_c_v_v: req_card.card_cvc.clone(),
};
let req_address = item.get_billing_address()?.to_owned();
let billing_address = HelcimBillingAddress {
name: req_address.get_full_name()?,
street1: req_address.get_line1()?.to_owned(),
postal_code: req_address.get_zip()?.to_owned(),
street2: req_address.line2,
city: req_address.city,
email: item.request.email.clone(),
};
let ip_address = item.request.get_browser_info()?.get_ip_address()?;
let currency = check_currency(item.request.currency)?;
Ok(Self {
currency,
ip_address,
card_data,
billing_address,
ecommerce: None,
})
}
}
impl TryFrom<&SetupMandateRouterData> for HelcimVerifyRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => Self::try_from((item, &req_card)),
PaymentMethodData::BankTransfer(_) => {
Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into())
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Helcim"),
))?
}
}
}
}
impl TryFrom<(&HelcimRouterData<&PaymentsAuthorizeRouterData>, &Card)> for HelcimPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (&HelcimRouterData<&PaymentsAuthorizeRouterData>, &Card),
) -> Result<Self, Self::Error> {
let (item, req_card) = value;
if item.router_data.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Cards 3DS".to_string(),
connector: "Helcim",
})?
}
let card_data = HelcimCard {
card_expiry: req_card
.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?,
card_number: req_card.card_number.clone(),
card_c_v_v: req_card.card_cvc.clone(),
};
let req_address = item
.router_data
.get_billing()?
.to_owned()
.address
.ok_or_else(utils::missing_field_err("billing.address"))?;
let billing_address = HelcimBillingAddress {
name: req_address.get_full_name()?,
street1: req_address.get_line1()?.to_owned(),
postal_code: req_address.get_zip()?.to_owned(),
street2: req_address.line2,
city: req_address.city,
email: item.router_data.request.email.clone(),
};
let ip_address = item
.router_data
.request
.get_browser_info()?
.get_ip_address()?;
let line_items = vec![
(HelcimLineItems {
description: item
.router_data
.description
.clone()
.unwrap_or("No Description".to_string()),
// By default quantity is set to 1 and price and total is set to amount because these three fields are required to generate an invoice.
quantity: 1,
price: item.amount,
total: item.amount,
}),
];
let invoice = HelcimInvoice {
invoice_number: item.router_data.connector_request_reference_id.clone(),
line_items,
};
let currency = check_currency(item.router_data.request.currency)?;
Ok(Self {
amount: item.amount,
currency,
ip_address,
card_data,
invoice,
billing_address,
ecommerce: None,
})
}
}
impl TryFrom<&HelcimRouterData<&PaymentsAuthorizeRouterData>> for HelcimPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &HelcimRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => Self::try_from((item, &req_card)),
PaymentMethodData::BankTransfer(_) => {
Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into())
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardWithLimitedDetails(_)
| PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Helcim"),
))?
}
}
}
}
// Auth Struct
pub struct HelcimAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for HelcimAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum HelcimPaymentStatus {
Approved,
Declined,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum HelcimTransactionType {
Purchase,
PreAuth,
Capture,
Verify,
Reverse,
}
impl From<HelcimPaymentsResponse> for enums::AttemptStatus {
fn from(item: HelcimPaymentsResponse) -> Self {
match item.transaction_type {
HelcimTransactionType::Purchase | HelcimTransactionType::Verify => match item.status {
HelcimPaymentStatus::Approved => Self::Charged,
HelcimPaymentStatus::Declined => Self::Failure,
},
HelcimTransactionType::PreAuth => match item.status {
HelcimPaymentStatus::Approved => Self::Authorized,
HelcimPaymentStatus::Declined => Self::AuthorizationFailed,
},
HelcimTransactionType::Capture => match item.status {
HelcimPaymentStatus::Approved => Self::Charged,
HelcimPaymentStatus::Declined => Self::CaptureFailed,
},
HelcimTransactionType::Reverse => match item.status {
HelcimPaymentStatus::Approved => Self::Voided,
HelcimPaymentStatus::Declined => Self::VoidFailed,
},
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimPaymentsResponse {
status: HelcimPaymentStatus,
transaction_id: u64,
invoice_number: Option<String>,
#[serde(rename = "type")]
transaction_type: HelcimTransactionType,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
HelcimPaymentsResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
> for RouterData<F, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
HelcimPaymentsResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
status: enums::AttemptStatus::from(item.response),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct HelcimMetaData {
pub preauth_transaction_id: u64,
}
impl TryFrom<PaymentsResponseRouterData<HelcimPaymentsResponse>> for PaymentsAuthorizeRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<HelcimPaymentsResponse>,
) -> Result<Self, Self::Error> {
//PreAuth Transaction ID is stored in connector metadata
//Initially resource_id is stored as NoResponseID for manual capture
//After Capture Transaction is completed it is updated to store the Capture ID
let resource_id = if item.data.request.is_auto_capture()? {
ResponseId::ConnectorTransactionId(item.response.transaction_id.to_string())
} else {
ResponseId::NoResponseId
};
let connector_metadata = if !item.data.request.is_auto_capture()? {
Some(serde_json::json!(HelcimMetaData {
preauth_transaction_id: item.response.transaction_id,
}))
} else {
None
};
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
status: enums::AttemptStatus::from(item.response),
..item.data
})
}
}
// impl utils::MultipleCaptureSyncResponse for HelcimPaymentsResponse {
// fn get_connector_capture_id(&self) -> String {
// self.transaction_id.to_string()
// }
// fn get_capture_attempt_status(&self) -> diesel_models::enums::AttemptStatus {
// enums::AttemptStatus::from(self.to_owned())
// }
// fn is_capture_response(&self) -> bool {
// true
// }
// fn get_amount_captured(&self) -> Option<i64> {
// Some(self.amount)
// }
// fn get_connector_reference_id(&self) -> Option<String> {
// None
// }
// }
impl TryFrom<PaymentsSyncResponseRouterData<HelcimPaymentsResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<HelcimPaymentsResponse>,
) -> Result<Self, Self::Error> {
match item.data.request.sync_type {
hyperswitch_domain_models::router_request_types::SyncRequestType::SinglePaymentSync => Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
status: enums::AttemptStatus::from(item.response),
..item.data
}),
hyperswitch_domain_models::router_request_types::SyncRequestType::MultipleCaptureSync(_) => {
Err(errors::ConnectorError::NotImplemented(
"manual multiple capture sync".to_string(),
)
.into())
// let capture_sync_response_list =
// utils::construct_captures_response_hashmap(vec![item.response]);
// Ok(Self {
// response: Ok(PaymentsResponseData::MultipleCaptureResponse {
// capture_sync_response_list,
// }),
// ..item.data
// })
}
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimCaptureRequest {
pre_auth_transaction_id: u64,
amount: FloatMajorUnit,
ip_address: Secret<String, IpAddress>,
#[serde(skip_serializing_if = "Option::is_none")]
ecommerce: Option<bool>,
}
impl TryFrom<&HelcimRouterData<&PaymentsCaptureRouterData>> for HelcimCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &HelcimRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let ip_address = item
.router_data
.request
.get_browser_info()?
.get_ip_address()?;
Ok(Self {
pre_auth_transaction_id: item
.router_data
.request
.connector_transaction_id
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
amount: item.amount,
ip_address,
ecommerce: None,
})
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<HelcimPaymentsResponse>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<HelcimPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
status: enums::AttemptStatus::from(item.response),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimVoidRequest {
card_transaction_id: u64,
ip_address: Secret<String, IpAddress>,
#[serde(skip_serializing_if = "Option::is_none")]
ecommerce: Option<bool>,
}
impl TryFrom<&PaymentsCancelRouterData> for HelcimVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let ip_address = item.request.get_browser_info()?.get_ip_address()?;
Ok(Self {
card_transaction_id: item
.request
.connector_transaction_id
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
ip_address,
ecommerce: None,
})
}
}
impl TryFrom<PaymentsCancelResponseRouterData<HelcimPaymentsResponse>>
for PaymentsCancelRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<HelcimPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
status: enums::AttemptStatus::from(item.response),
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimRefundRequest {
amount: FloatMajorUnit,
original_transaction_id: u64,
ip_address: Secret<String, IpAddress>,
#[serde(skip_serializing_if = "Option::is_none")]
ecommerce: Option<bool>,
}
impl<F> TryFrom<&HelcimRouterData<&RefundsRouterData<F>>> for HelcimRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &HelcimRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let original_transaction_id = item
.router_data
.request
.connector_transaction_id
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let ip_address = item
.router_data
.request
.get_browser_info()?
.get_ip_address()?;
Ok(Self {
amount: item.amount,
original_transaction_id,
ip_address,
ecommerce: None,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum HelcimRefundTransactionType {
Refund,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
status: HelcimPaymentStatus,
transaction_id: u64,
#[serde(rename = "type")]
transaction_type: HelcimRefundTransactionType,
}
impl From<RefundResponse> for enums::RefundStatus {
fn from(item: RefundResponse) -> Self {
match item.transaction_type {
HelcimRefundTransactionType::Refund => match item.status {
HelcimPaymentStatus::Approved => Self::Success,
HelcimPaymentStatus::Declined => Self::Failure,
},
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id.to_string(),
refund_status: enums::RefundStatus::from(item.response),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id.to_string(),
refund_status: enums::RefundStatus::from(item.response),
}),
..item.data
})
}
}
#[derive(Debug, strum::Display, Deserialize, Serialize)]
#[serde(untagged)]
pub enum HelcimErrorTypes {
StringType(String),
JsonType(serde_json::Value),
}
#[derive(Debug, Deserialize, Serialize)]
pub struct HelcimPaymentsErrorResponse {
pub errors: HelcimErrorTypes,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum HelcimErrorResponse {
Payment(HelcimPaymentsErrorResponse),
General(String),
}
|
crates__hyperswitch_connectors__src__connectors__hipay.rs
|
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::{enums, CaptureMethod, PaymentMethod, PaymentMethodType};
use common_utils::{
consts::BASE64_ENGINE,
errors::{self as common_errors, CustomResult},
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response, TokenizationType},
webhooks,
};
use masking::{Mask, PeekInterface};
use reqwest::multipart::Form;
use serde::Serialize;
use serde_json::Value;
use transformers as hipay;
use crate::{constants::headers, types::ResponseRouterData, utils};
pub fn build_form_from_struct<T: Serialize + Send + 'static>(
data: T,
) -> Result<RequestContent, common_errors::ParsingError> {
let mut form = Form::new();
let serialized = serde_json::to_value(&data).map_err(|e| {
router_env::logger::error!("Error serializing data to JSON value: {:?}", e);
common_errors::ParsingError::EncodeError("json-value")
})?;
let serialized_object = serialized.as_object().ok_or_else(|| {
router_env::logger::error!("Error: Expected JSON object but got something else");
common_errors::ParsingError::EncodeError("Expected object")
})?;
for (key, values) in serialized_object {
let value = match values {
Value::String(s) => s.clone(),
Value::Number(n) => n.to_string(),
Value::Bool(b) => b.to_string(),
Value::Null => "".to_string(),
Value::Array(_) | Value::Object(_) => {
router_env::logger::error!(serialization_error =? "Form Construction Failed.");
"".to_string()
}
};
form = form.text(key.clone(), value.clone());
}
Ok(RequestContent::FormData((form, Box::new(data))))
}
#[derive(Clone)]
pub struct Hipay {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Hipay {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl api::Payment for Hipay {}
impl api::PaymentSession for Hipay {}
impl api::ConnectorAccessToken for Hipay {}
impl api::MandateSetup for Hipay {}
impl api::PaymentAuthorize for Hipay {}
impl api::PaymentSync for Hipay {}
impl api::PaymentCapture for Hipay {}
impl api::PaymentVoid for Hipay {}
impl api::Refund for Hipay {}
impl api::RefundExecute for Hipay {}
impl api::RefundSync for Hipay {}
impl api::PaymentToken for Hipay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Hipay
{
fn get_headers(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
_req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}v2/token/create",
connectors.hipay.secondary_base_url.clone()
))
}
fn get_request_body(
&self,
req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = transformers::HiPayTokenRequest::try_from(req)?;
router_env::logger::info!(raw_connector_request=?connector_req);
build_form_from_struct(connector_req).change_context(errors::ConnectorError::ParsingFailed)
}
fn build_request(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&TokenizationType::get_url(self, req, connectors)?)
.headers(TokenizationType::get_headers(self, req, connectors)?)
.set_body(TokenizationType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &TokenizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<TokenizationRouterData, errors::ConnectorError>
where
PaymentsResponseData: Clone,
{
let response: transformers::HipayTokenResponse = res
.response
.parse_struct("HipayTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
Ok(ErrorResponse::get_not_implemented())
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Hipay
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::ACCEPT.to_string(),
"application/json".to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Hipay {
fn id(&self) -> &'static str {
"hipay"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.hipay.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = hipay::HipayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_key = format!("{}:{}", auth.api_key.peek(), auth.key1.peek());
let auth_header = format!("Basic {}", BASE64_ENGINE.encode(auth_key));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth_header.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: hipay::HipayErrorResponse =
res.response
.parse_struct("HipayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code.to_string(),
message: response.message,
reason: response.description,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Hipay {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Hipay {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Hipay {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Hipay {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Hipay {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v1/order", connectors.hipay.base_url.clone()))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = hipay::HipayRouterData::from((amount, req));
let connector_req = hipay::HipayPaymentsRequest::try_from(&connector_router_data)?;
router_env::logger::info!(raw_connector_request=?connector_req);
build_form_from_struct(connector_req).change_context(errors::ConnectorError::ParsingFailed)
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: hipay::HipayPaymentsResponse = res
.response
.parse_struct("Hipay PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Hipay {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}v3/transaction/{}",
connectors.hipay.third_base_url.clone(),
connector_payment_id
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: hipay::HipaySyncResponse = res
.response
.parse_struct("hipay HipaySyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Hipay {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}v1/maintenance/transaction/{}",
connectors.hipay.base_url.clone(),
req.request.connector_transaction_id
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let capture_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = hipay::HipayRouterData::from((capture_amount, req));
let connector_req = hipay::HipayMaintenanceRequest::try_from(&connector_router_data)?;
router_env::logger::info!(raw_connector_request=?connector_req);
build_form_from_struct(connector_req).change_context(errors::ConnectorError::ParsingFailed)
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: hipay::HipayMaintenanceResponse<hipay::HipayPaymentStatus> = res
.response
.parse_struct("Hipay HipayMaintenanceResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Hipay {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}v1/maintenance/transaction/{}",
self.base_url(connectors),
req.request.connector_transaction_id
))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = hipay::HipayMaintenanceRequest::try_from(req)?;
router_env::logger::info!(raw_connector_request=?connector_req);
build_form_from_struct(connector_req).change_context(errors::ConnectorError::ParsingFailed)
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: hipay::HipayMaintenanceResponse<hipay::HipayPaymentStatus> = res
.response
.parse_struct("Hipay HipayMaintenanceResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Hipay {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}v1/maintenance/transaction/{}",
connectors.hipay.base_url.clone(),
req.request.connector_transaction_id
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = hipay::HipayRouterData::from((refund_amount, req));
let connector_req = hipay::HipayMaintenanceRequest::try_from(&connector_router_data)?;
router_env::logger::info!(raw_connector_request=?connector_req);
build_form_from_struct(connector_req).change_context(errors::ConnectorError::ParsingFailed)
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: hipay::HipayMaintenanceResponse<hipay::RefundStatus> = res
.response
.parse_struct("hipay RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Hipay {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}v3/transaction/{}",
connectors.hipay.third_base_url.clone(),
connector_payment_id
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: hipay::RefundResponse = res
.response
.parse_struct("hipay RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Hipay {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static HIPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
CaptureMethod::Automatic,
CaptureMethod::Manual,
CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::UnionPay,
];
let mut hipay_supported_payment_methods = SupportedPaymentMethods::new();
hipay_supported_payment_methods.add(
PaymentMethod::Card,
PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
hipay_supported_payment_methods.add(
PaymentMethod::Card,
PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
hipay_supported_payment_methods
});
static HIPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Hipay",
description: "HiPay is an independent global payment service provider that is based in France.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static HIPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Hipay {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&HIPAY_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*HIPAY_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&HIPAY_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates__hyperswitch_connectors__src__connectors__hipay__transformers.rs
|
use std::collections::HashMap;
use common_enums::{enums, CardNetwork};
use common_utils::{
pii::{self},
request::Method,
types::StringMajorUnit,
};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ErrorResponse, PaymentMethodToken, RouterData,
},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{BrowserInformation, ResponseId},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundsRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
ResponseRouterData,
},
unimplemented_payment_method,
utils::{self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, RouterData as _},
};
pub struct HipayRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for HipayRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Operation {
Authorization,
Sale,
Capture,
Refund,
Cancel,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct HipayBrowserInfo {
java_enabled: Option<bool>,
javascript_enabled: Option<bool>,
ipaddr: Option<std::net::IpAddr>,
http_accept: String,
http_user_agent: Option<String>,
language: Option<String>,
color_depth: Option<u8>,
screen_height: Option<u32>,
screen_width: Option<u32>,
timezone: Option<i32>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct HipayPaymentsRequest {
operation: Operation,
authentication_indicator: u8,
cardtoken: Secret<String>,
orderid: String,
currency: enums::Currency,
payment_product: String,
amount: StringMajorUnit,
description: String,
decline_url: Option<String>,
pending_url: Option<String>,
cancel_url: Option<String>,
accept_url: Option<String>,
notify_url: Option<String>,
#[serde(flatten)]
#[serde(skip_serializing_if = "Option::is_none")]
three_ds_data: Option<ThreeDSPaymentData>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ThreeDSPaymentData {
#[serde(skip_serializing_if = "Option::is_none")]
pub firstname: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub lastname: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<pii::Email>,
#[serde(skip_serializing_if = "Option::is_none")]
pub streetaddress: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub city: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub zipcode: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub country: Option<enums::CountryAlpha2>,
#[serde(skip_serializing_if = "Option::is_none")]
pub browser_info: Option<HipayBrowserInfo>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct HipayMaintenanceRequest {
operation: Operation,
currency: Option<enums::Currency>,
amount: Option<StringMajorUnit>,
}
impl From<BrowserInformation> for HipayBrowserInfo {
fn from(browser_info: BrowserInformation) -> Self {
Self {
java_enabled: browser_info.java_enabled,
javascript_enabled: browser_info.java_script_enabled,
ipaddr: browser_info.ip_address,
http_accept: "*/*".to_string(),
http_user_agent: browser_info.user_agent,
language: browser_info.language,
color_depth: browser_info.color_depth,
screen_height: browser_info.screen_height,
screen_width: browser_info.screen_width,
timezone: browser_info.time_zone,
}
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct HiPayTokenRequest {
pub card_number: cards::CardNumber,
pub card_expiry_month: Secret<String>,
pub card_expiry_year: Secret<String>,
pub card_holder: Secret<String>,
pub cvc: Secret<String>,
}
impl TryFrom<&HipayRouterData<&PaymentsAuthorizeRouterData>> for HipayPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &HipayRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
let (domestic_card_network, domestic_network) = item
.router_data
.connector_response
.clone()
.and_then(|response| match response.additional_payment_method_data {
Some(AdditionalPaymentMethodConnectorResponse::Card {
card_network,
domestic_network,
..
}) => Some((card_network, domestic_network)),
_ => None,
})
.unwrap_or_default();
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => Ok(Self {
operation: if item.router_data.request.is_auto_capture()? {
Operation::Sale
} else {
Operation::Authorization
},
authentication_indicator: if item.router_data.is_three_ds() { 2 } else { 0 },
cardtoken: match item.router_data.get_payment_method_token()? {
PaymentMethodToken::Token(token) => token,
PaymentMethodToken::ApplePayDecrypt(_) => {
return Err(unimplemented_payment_method!("Apple Pay", "Hipay").into());
}
PaymentMethodToken::PazeDecrypt(_) => {
return Err(unimplemented_payment_method!("Paze", "Hipay").into());
}
PaymentMethodToken::GooglePayDecrypt(_) => {
return Err(unimplemented_payment_method!("Google Pay", "Hipay").into());
}
},
orderid: item.router_data.connector_request_reference_id.clone(),
currency: item.router_data.request.currency,
payment_product: match (domestic_network, domestic_card_network.as_deref()) {
(Some(domestic), _) => domestic,
(None, Some("VISA")) => "visa".to_string(),
(None, Some("MASTERCARD")) => "mastercard".to_string(),
(None, Some("MAESTRO")) => "maestro".to_string(),
(None, Some("AMERICAN EXPRESS")) => "american-express".to_string(),
(None, Some("CB")) => "cb".to_string(),
(None, Some("BCMC")) => "bcmc".to_string(),
(None, _) => match req_card.card_network {
Some(CardNetwork::Visa) => "visa".to_string(),
Some(CardNetwork::Mastercard) => "mastercard".to_string(),
Some(CardNetwork::AmericanExpress) => "american-express".to_string(),
Some(CardNetwork::JCB) => "jcb".to_string(),
Some(CardNetwork::DinersClub) => "diners".to_string(),
Some(CardNetwork::Discover) => "discover".to_string(),
Some(CardNetwork::CartesBancaires) => "cb".to_string(),
Some(CardNetwork::UnionPay) => "unionpay".to_string(),
Some(CardNetwork::Interac) => "interac".to_string(),
Some(CardNetwork::RuPay) => "rupay".to_string(),
Some(CardNetwork::Maestro) => "maestro".to_string(),
Some(CardNetwork::Star)
| Some(CardNetwork::Accel)
| Some(CardNetwork::Pulse)
| Some(CardNetwork::Nyce)
| None => "".to_string(),
},
},
amount: item.amount.clone(),
description: item
.router_data
.get_description()
.map(|s| s.to_string())
.unwrap_or("Short Description".to_string()),
decline_url: item.router_data.request.router_return_url.clone(),
pending_url: item.router_data.request.router_return_url.clone(),
cancel_url: item.router_data.request.router_return_url.clone(),
accept_url: item.router_data.request.router_return_url.clone(),
notify_url: item.router_data.request.router_return_url.clone(),
three_ds_data: if item.router_data.is_three_ds() {
let billing_address = item.router_data.get_billing_address()?;
Some(ThreeDSPaymentData {
firstname: billing_address.get_optional_first_name(),
lastname: billing_address.get_optional_last_name(),
email: Some(
item.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?,
),
city: billing_address.get_optional_city(),
streetaddress: billing_address.get_optional_line1(),
zipcode: billing_address.get_optional_zip(),
state: billing_address.get_optional_state(),
country: billing_address.get_optional_country(),
browser_info: Some(HipayBrowserInfo::from(
item.router_data.request.get_browser_info()?,
)),
})
} else {
None
},
}),
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
impl TryFrom<&TokenizationRouterData> for HiPayTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(card_data) => Ok(Self {
card_number: card_data.card_number.clone(),
card_expiry_month: card_data.card_exp_month.clone(),
card_expiry_year: card_data.get_expiry_year_4_digit(),
card_holder: item.get_billing_full_name()?,
cvc: card_data.card_cvc,
}),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Hipay"),
)
.into()),
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct HipayTokenResponse {
token: Secret<String>,
brand: String,
domestic_network: Option<String>,
}
impl From<&HipayTokenResponse> for AdditionalPaymentMethodConnectorResponse {
fn from(hipay_token_response: &HipayTokenResponse) -> Self {
Self::Card {
authentication_data: None,
payment_checks: None,
card_network: Some(hipay_token_response.brand.clone()),
domestic_network: hipay_token_response.domestic_network.clone(),
auth_code: None,
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct HipayErrorResponse {
pub code: u8,
pub message: String,
pub description: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, HipayTokenResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, HipayTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.token.clone().expose(),
}),
connector_response: Some(ConnectorResponseData::with_additional_payment_method_data(
AdditionalPaymentMethodConnectorResponse::from(&item.response),
)),
..item.data
})
}
}
pub struct HipayAuthType {
pub(super) api_key: Secret<String>,
pub(super) key1: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for HipayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.clone(),
key1: key1.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HipayPaymentsResponse {
status: HipayPaymentStatus,
message: String,
order: PaymentOrder,
forward_url: String,
transaction_reference: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentOrder {
id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HipayMaintenanceResponse<S> {
status: S,
message: String,
transaction_reference: String,
}
impl TryFrom<PaymentsResponseRouterData<HipayPaymentsResponse>> for PaymentsAuthorizeRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<HipayPaymentsResponse>,
) -> Result<Self, Self::Error> {
let status = common_enums::AttemptStatus::from(item.response.status);
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: item.response.message.clone(),
reason: Some(item.response.message.clone()),
attempt_status: None,
connector_transaction_id: Some(item.response.transaction_reference),
connector_response_reference_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_reference,
),
redirection_data: match item.data.is_three_ds() {
true => Box::new(Some(RedirectForm::Form {
endpoint: item.response.forward_url,
method: Method::Get,
form_fields: HashMap::new(),
})),
false => Box::new(None),
},
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl<F> TryFrom<&HipayRouterData<&RefundsRouterData<F>>> for HipayMaintenanceRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &HipayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: Some(item.amount.to_owned()),
operation: Operation::Refund,
currency: Some(item.router_data.request.currency),
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for HipayMaintenanceRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Ok(Self {
operation: Operation::Cancel,
currency: item.request.currency,
amount: None,
})
}
}
impl TryFrom<&HipayRouterData<&PaymentsCaptureRouterData>> for HipayMaintenanceRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &HipayRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
Ok(Self {
amount: Some(item.amount.to_owned()),
operation: Operation::Capture,
currency: Some(item.router_data.request.currency),
})
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum RefundStatus {
#[serde(rename = "124")]
RefundRequested,
#[serde(rename = "125")]
Refunded,
#[serde(rename = "126")]
PartiallyRefunded,
#[serde(rename = "165")]
RefundRefused,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::RefundRequested => Self::Pending,
RefundStatus::Refunded | RefundStatus::PartiallyRefunded => Self::Success,
RefundStatus::RefundRefused => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum HipayPaymentStatus {
#[serde(rename = "109")]
AuthenticationFailed,
#[serde(rename = "110")]
Blocked,
#[serde(rename = "111")]
Denied,
#[serde(rename = "112")]
AuthorizedAndPending,
#[serde(rename = "113")]
Refused,
#[serde(rename = "114")]
Expired,
#[serde(rename = "115")]
Cancelled,
#[serde(rename = "116")]
Authorized,
#[serde(rename = "117")]
CaptureRequested,
#[serde(rename = "118")]
Captured,
#[serde(rename = "119")]
PartiallyCaptured,
#[serde(rename = "129")]
ChargedBack,
#[serde(rename = "173")]
CaptureRefused,
#[serde(rename = "174")]
AwaitingTerminal,
#[serde(rename = "175")]
AuthorizationCancellationRequested,
#[serde(rename = "177")]
ChallengeRequested,
#[serde(rename = "178")]
SoftDeclined,
#[serde(rename = "200")]
PendingPayment,
#[serde(rename = "101")]
Created,
#[serde(rename = "105")]
UnableToAuthenticate,
#[serde(rename = "106")]
CardholderAuthenticated,
#[serde(rename = "107")]
AuthenticationAttempted,
#[serde(rename = "108")]
CouldNotAuthenticate,
#[serde(rename = "120")]
Collected,
#[serde(rename = "121")]
PartiallyCollected,
#[serde(rename = "122")]
Settled,
#[serde(rename = "123")]
PartiallySettled,
#[serde(rename = "140")]
AuthenticationRequested,
#[serde(rename = "141")]
Authenticated,
#[serde(rename = "151")]
AcquirerNotFound,
#[serde(rename = "161")]
RiskAccepted,
#[serde(rename = "163")]
AuthorizationRefused,
}
impl From<HipayPaymentStatus> for common_enums::AttemptStatus {
fn from(status: HipayPaymentStatus) -> Self {
match status {
HipayPaymentStatus::AuthenticationFailed => Self::AuthenticationFailed,
HipayPaymentStatus::Blocked
| HipayPaymentStatus::Refused
| HipayPaymentStatus::Expired
| HipayPaymentStatus::Denied => Self::Failure,
HipayPaymentStatus::AuthorizedAndPending => Self::Pending,
HipayPaymentStatus::Cancelled => Self::Voided,
HipayPaymentStatus::Authorized => Self::Authorized,
HipayPaymentStatus::CaptureRequested => Self::CaptureInitiated,
HipayPaymentStatus::Captured => Self::Charged,
HipayPaymentStatus::PartiallyCaptured => Self::PartialCharged,
HipayPaymentStatus::CaptureRefused => Self::CaptureFailed,
HipayPaymentStatus::AwaitingTerminal => Self::Pending,
HipayPaymentStatus::AuthorizationCancellationRequested => Self::VoidInitiated,
HipayPaymentStatus::ChallengeRequested => Self::AuthenticationPending,
HipayPaymentStatus::SoftDeclined => Self::Failure,
HipayPaymentStatus::PendingPayment => Self::Pending,
HipayPaymentStatus::ChargedBack => Self::Failure,
HipayPaymentStatus::Created => Self::Started,
HipayPaymentStatus::UnableToAuthenticate | HipayPaymentStatus::CouldNotAuthenticate => {
Self::AuthenticationFailed
}
HipayPaymentStatus::CardholderAuthenticated => Self::Pending,
HipayPaymentStatus::AuthenticationAttempted => Self::AuthenticationPending,
HipayPaymentStatus::Collected
| HipayPaymentStatus::PartiallySettled
| HipayPaymentStatus::PartiallyCollected
| HipayPaymentStatus::Settled => Self::Charged,
HipayPaymentStatus::AuthenticationRequested => Self::AuthenticationPending,
HipayPaymentStatus::Authenticated => Self::AuthenticationSuccessful,
HipayPaymentStatus::AcquirerNotFound => Self::Failure,
HipayPaymentStatus::RiskAccepted => Self::Pending,
HipayPaymentStatus::AuthorizationRefused => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: u64,
status: u16,
}
impl TryFrom<RefundsResponseRouterData<Execute, HipayMaintenanceResponse<RefundStatus>>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, HipayMaintenanceResponse<RefundStatus>>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_reference,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: match item.response.status {
25 | 26 => enums::RefundStatus::Success,
65 => enums::RefundStatus::Failure,
24 => enums::RefundStatus::Pending,
_ => enums::RefundStatus::Pending,
},
}),
..item.data
})
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<HipayMaintenanceResponse<HipayPaymentStatus>>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<HipayMaintenanceResponse<HipayPaymentStatus>>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_reference.clone().to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<PaymentsCancelResponseRouterData<HipayMaintenanceResponse<HipayPaymentStatus>>>
for PaymentsCancelRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<HipayMaintenanceResponse<HipayPaymentStatus>>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_reference.clone().to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Reason {
reason: Option<String>,
code: Option<u64>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum HipaySyncResponse {
Response { status: i32, reason: Reason },
Error { message: String, code: u32 },
}
fn get_sync_status(state: i32) -> enums::AttemptStatus {
match state {
9 => enums::AttemptStatus::AuthenticationFailed,
10 => enums::AttemptStatus::Failure,
11 => enums::AttemptStatus::Failure,
12 => enums::AttemptStatus::Pending,
13 => enums::AttemptStatus::Failure,
14 => enums::AttemptStatus::Failure,
15 => enums::AttemptStatus::Voided,
16 => enums::AttemptStatus::Authorized,
17 => enums::AttemptStatus::CaptureInitiated,
18 => enums::AttemptStatus::Charged,
19 => enums::AttemptStatus::PartialCharged,
29 => enums::AttemptStatus::Failure,
73 => enums::AttemptStatus::CaptureFailed,
74 => enums::AttemptStatus::Pending,
75 => enums::AttemptStatus::VoidInitiated,
77 => enums::AttemptStatus::AuthenticationPending,
78 => enums::AttemptStatus::Failure,
200 => enums::AttemptStatus::Pending,
1 => enums::AttemptStatus::Started,
5 => enums::AttemptStatus::AuthenticationFailed,
6 => enums::AttemptStatus::Pending,
7 => enums::AttemptStatus::AuthenticationPending,
8 => enums::AttemptStatus::AuthenticationFailed,
20 => enums::AttemptStatus::Charged,
21 => enums::AttemptStatus::Charged,
22 => enums::AttemptStatus::Charged,
23 => enums::AttemptStatus::Charged,
40 => enums::AttemptStatus::AuthenticationPending,
41 => enums::AttemptStatus::AuthenticationSuccessful,
51 => enums::AttemptStatus::Failure,
61 => enums::AttemptStatus::Pending,
63 => enums::AttemptStatus::Failure,
_ => enums::AttemptStatus::Failure,
}
}
impl TryFrom<PaymentsSyncResponseRouterData<HipaySyncResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<HipaySyncResponse>,
) -> Result<Self, Self::Error> {
match item.response {
HipaySyncResponse::Error { message, code } => {
let response = Err(ErrorResponse {
code: code.to_string(),
message: message.clone(),
reason: Some(message.clone()),
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
status: enums::AttemptStatus::Failure,
response,
..item.data
})
}
HipaySyncResponse::Response { status, reason } => {
let status = get_sync_status(status);
let response = if status == enums::AttemptStatus::Failure {
let error_code = reason
.code
.map_or(NO_ERROR_CODE.to_string(), |c| c.to_string());
let error_message = reason
.reason
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_owned());
Err(ErrorResponse {
code: error_code,
message: error_message.clone(),
reason: Some(error_message),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
connector_response_reference_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
authentication_data: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.