repo stringclasses 4 values | file_path stringlengths 6 193 | extension stringclasses 23 values | content stringlengths 0 1.73M | token_count int64 0 724k | __index_level_0__ int64 0 10.8k |
|---|---|---|---|---|---|
hyperswitch | crates/api_models/src/analytics/disputes.rs | .rs | use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use super::{ForexMetric, NameDescription, TimeRange};
use crate::enums::{Currency, DisputeStage};
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum DisputeMetrics {
DisputeStatusMetric,
TotalAmountDisputed,
TotalDisputeLostAmount,
SessionizedDisputeStatusMetric,
SessionizedTotalAmountDisputed,
SessionizedTotalDisputeLostAmount,
}
impl ForexMetric for DisputeMetrics {
fn is_forex_metric(&self) -> bool {
matches!(
self,
Self::TotalAmountDisputed | Self::TotalDisputeLostAmount
)
}
}
#[derive(
Debug,
serde::Serialize,
serde::Deserialize,
strum::AsRefStr,
PartialEq,
PartialOrd,
Eq,
Ord,
strum::Display,
strum::EnumIter,
Clone,
Copy,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum DisputeDimensions {
// Do not change the order of these enums
// Consult the Dashboard FE folks since these also affects the order of metrics on FE
Connector,
DisputeStage,
Currency,
}
impl From<DisputeDimensions> for NameDescription {
fn from(value: DisputeDimensions) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
impl From<DisputeMetrics> for NameDescription {
fn from(value: DisputeMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct DisputeFilters {
#[serde(default)]
pub dispute_stage: Vec<DisputeStage>,
#[serde(default)]
pub connector: Vec<String>,
#[serde(default)]
pub currency: Vec<Currency>,
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct DisputeMetricsBucketIdentifier {
pub dispute_stage: Option<DisputeStage>,
pub connector: Option<String>,
pub currency: Option<Currency>,
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
#[serde(rename = "time_bucket")]
#[serde(with = "common_utils::custom_serde::iso8601custom")]
pub start_time: time::PrimitiveDateTime,
}
impl Hash for DisputeMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.dispute_stage.hash(state);
self.connector.hash(state);
self.currency.hash(state);
self.time_bucket.hash(state);
}
}
impl PartialEq for DisputeMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
impl DisputeMetricsBucketIdentifier {
pub fn new(
dispute_stage: Option<DisputeStage>,
connector: Option<String>,
currency: Option<Currency>,
normalized_time_range: TimeRange,
) -> Self {
Self {
dispute_stage,
connector,
currency,
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
}
}
#[derive(Debug, serde::Serialize)]
pub struct DisputeMetricsBucketValue {
pub disputes_challenged: Option<u64>,
pub disputes_won: Option<u64>,
pub disputes_lost: Option<u64>,
pub disputed_amount: Option<u64>,
pub dispute_lost_amount: Option<u64>,
pub total_dispute: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct DisputeMetricsBucketResponse {
#[serde(flatten)]
pub values: DisputeMetricsBucketValue,
#[serde(flatten)]
pub dimensions: DisputeMetricsBucketIdentifier,
}
| 934 | 2,006 |
hyperswitch | crates/api_models/src/analytics/search.rs | .rs | use common_utils::{hashing::HashedString, types::TimeRange};
use masking::WithType;
use serde_json::Value;
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct SearchFilters {
pub payment_method: Option<Vec<String>>,
pub currency: Option<Vec<String>>,
pub status: Option<Vec<String>>,
pub customer_email: Option<Vec<HashedString<common_utils::pii::EmailStrategy>>>,
pub search_tags: Option<Vec<HashedString<WithType>>>,
pub connector: Option<Vec<String>>,
pub payment_method_type: Option<Vec<String>>,
pub card_network: Option<Vec<String>>,
pub card_last_4: Option<Vec<String>>,
pub payment_id: Option<Vec<String>>,
pub amount: Option<Vec<u64>>,
pub customer_id: Option<Vec<String>>,
}
impl SearchFilters {
pub fn is_all_none(&self) -> bool {
self.payment_method.is_none()
&& self.currency.is_none()
&& self.status.is_none()
&& self.customer_email.is_none()
&& self.search_tags.is_none()
&& self.connector.is_none()
&& self.payment_method_type.is_none()
&& self.card_network.is_none()
&& self.card_last_4.is_none()
&& self.payment_id.is_none()
&& self.amount.is_none()
&& self.customer_id.is_none()
}
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetGlobalSearchRequest {
pub query: String,
#[serde(default)]
pub filters: Option<SearchFilters>,
#[serde(default)]
pub time_range: Option<TimeRange>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSearchRequest {
pub offset: i64,
pub count: i64,
pub query: String,
#[serde(default)]
pub filters: Option<SearchFilters>,
#[serde(default)]
pub time_range: Option<TimeRange>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSearchRequestWithIndex {
pub index: SearchIndex,
pub search_req: GetSearchRequest,
}
#[derive(
Debug, strum::EnumIter, Clone, serde::Deserialize, serde::Serialize, Copy, Eq, PartialEq,
)]
#[serde(rename_all = "snake_case")]
pub enum SearchIndex {
PaymentAttempts,
PaymentIntents,
Refunds,
Disputes,
SessionizerPaymentAttempts,
SessionizerPaymentIntents,
SessionizerRefunds,
SessionizerDisputes,
}
#[derive(Debug, strum::EnumIter, Clone, serde::Deserialize, serde::Serialize, Copy)]
pub enum SearchStatus {
Success,
Failure,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSearchResponse {
pub count: u64,
pub index: SearchIndex,
pub hits: Vec<Value>,
pub status: SearchStatus,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpenMsearchOutput {
#[serde(default)]
pub responses: Vec<OpensearchOutput>,
pub error: Option<OpensearchErrorDetails>,
}
#[derive(Debug, serde::Deserialize)]
#[serde(untagged)]
pub enum OpensearchOutput {
Success(OpensearchSuccess),
Error(OpensearchError),
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchError {
pub error: OpensearchErrorDetails,
pub status: u16,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchErrorDetails {
#[serde(rename = "type")]
pub error_type: String,
pub reason: String,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchSuccess {
pub hits: OpensearchHits,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchHits {
pub total: OpensearchResultsTotal,
pub hits: Vec<OpensearchHit>,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchResultsTotal {
pub value: u64,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchHit {
#[serde(rename = "_source")]
pub source: Value,
}
| 934 | 2,007 |
hyperswitch | crates/api_models/src/analytics/payments.rs | .rs | use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use common_utils::id_type;
use super::{ForexMetric, NameDescription, TimeRange};
use crate::enums::{
AttemptStatus, AuthenticationType, CardNetwork, Connector, Currency, PaymentMethod,
PaymentMethodType,
};
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct PaymentFilters {
#[serde(default)]
pub currency: Vec<Currency>,
#[serde(default)]
pub status: Vec<AttemptStatus>,
#[serde(default)]
pub connector: Vec<Connector>,
#[serde(default)]
pub auth_type: Vec<AuthenticationType>,
#[serde(default)]
pub payment_method: Vec<PaymentMethod>,
#[serde(default)]
pub payment_method_type: Vec<PaymentMethodType>,
#[serde(default)]
pub client_source: Vec<String>,
#[serde(default)]
pub client_version: Vec<String>,
#[serde(default)]
pub card_network: Vec<CardNetwork>,
#[serde(default)]
pub profile_id: Vec<id_type::ProfileId>,
#[serde(default)]
pub merchant_id: Vec<id_type::MerchantId>,
#[serde(default)]
pub card_last_4: Vec<String>,
#[serde(default)]
pub card_issuer: Vec<String>,
#[serde(default)]
pub error_reason: Vec<String>,
#[serde(default)]
pub first_attempt: Vec<bool>,
}
#[derive(
Debug,
serde::Serialize,
serde::Deserialize,
strum::AsRefStr,
PartialEq,
PartialOrd,
Eq,
Ord,
strum::Display,
strum::EnumIter,
Clone,
Copy,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PaymentDimensions {
// Do not change the order of these enums
// Consult the Dashboard FE folks since these also affects the order of metrics on FE
Connector,
PaymentMethod,
PaymentMethodType,
Currency,
#[strum(serialize = "authentication_type")]
#[serde(rename = "authentication_type")]
AuthType,
#[strum(serialize = "status")]
#[serde(rename = "status")]
PaymentStatus,
ClientSource,
ClientVersion,
ProfileId,
CardNetwork,
MerchantId,
#[strum(serialize = "card_last_4")]
#[serde(rename = "card_last_4")]
CardLast4,
CardIssuer,
ErrorReason,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum PaymentMetrics {
PaymentSuccessRate,
PaymentCount,
PaymentSuccessCount,
PaymentProcessedAmount,
AvgTicketSize,
RetriesCount,
ConnectorSuccessRate,
SessionizedPaymentSuccessRate,
SessionizedPaymentCount,
SessionizedPaymentSuccessCount,
SessionizedPaymentProcessedAmount,
SessionizedAvgTicketSize,
SessionizedRetriesCount,
SessionizedConnectorSuccessRate,
PaymentsDistribution,
FailureReasons,
}
impl ForexMetric for PaymentMetrics {
fn is_forex_metric(&self) -> bool {
matches!(
self,
Self::PaymentProcessedAmount
| Self::AvgTicketSize
| Self::SessionizedPaymentProcessedAmount
| Self::SessionizedAvgTicketSize
)
}
}
#[derive(Debug, Default, serde::Serialize)]
pub struct ErrorResult {
pub reason: String,
pub count: i64,
pub percentage: f64,
}
#[derive(
Clone,
Copy,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum PaymentDistributions {
#[strum(serialize = "error_message")]
PaymentErrorMessage,
}
pub mod metric_behaviour {
pub struct PaymentSuccessRate;
pub struct PaymentCount;
pub struct PaymentSuccessCount;
pub struct PaymentProcessedAmount;
pub struct AvgTicketSize;
}
impl From<PaymentMetrics> for NameDescription {
fn from(value: PaymentMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
impl From<PaymentDimensions> for NameDescription {
fn from(value: PaymentDimensions) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct PaymentMetricsBucketIdentifier {
pub currency: Option<Currency>,
pub status: Option<AttemptStatus>,
pub connector: Option<String>,
#[serde(rename = "authentication_type")]
pub auth_type: Option<AuthenticationType>,
pub payment_method: Option<String>,
pub payment_method_type: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
pub profile_id: Option<String>,
pub card_network: Option<String>,
pub merchant_id: Option<String>,
pub card_last_4: Option<String>,
pub card_issuer: Option<String>,
pub error_reason: Option<String>,
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
// Coz FE sucks
#[serde(rename = "time_bucket")]
#[serde(with = "common_utils::custom_serde::iso8601custom")]
pub start_time: time::PrimitiveDateTime,
}
impl PaymentMetricsBucketIdentifier {
#[allow(clippy::too_many_arguments)]
pub fn new(
currency: Option<Currency>,
status: Option<AttemptStatus>,
connector: Option<String>,
auth_type: Option<AuthenticationType>,
payment_method: Option<String>,
payment_method_type: Option<String>,
client_source: Option<String>,
client_version: Option<String>,
profile_id: Option<String>,
card_network: Option<String>,
merchant_id: Option<String>,
card_last_4: Option<String>,
card_issuer: Option<String>,
error_reason: Option<String>,
normalized_time_range: TimeRange,
) -> Self {
Self {
currency,
status,
connector,
auth_type,
payment_method,
payment_method_type,
client_source,
client_version,
profile_id,
card_network,
merchant_id,
card_last_4,
card_issuer,
error_reason,
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
}
}
impl Hash for PaymentMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.currency.hash(state);
self.status.map(|i| i.to_string()).hash(state);
self.connector.hash(state);
self.auth_type.map(|i| i.to_string()).hash(state);
self.payment_method.hash(state);
self.payment_method_type.hash(state);
self.client_source.hash(state);
self.client_version.hash(state);
self.profile_id.hash(state);
self.card_network.hash(state);
self.merchant_id.hash(state);
self.card_last_4.hash(state);
self.card_issuer.hash(state);
self.error_reason.hash(state);
self.time_bucket.hash(state);
}
}
impl PartialEq for PaymentMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
#[derive(Debug, serde::Serialize)]
pub struct PaymentMetricsBucketValue {
pub payment_success_rate: Option<f64>,
pub payment_count: Option<u64>,
pub payment_success_count: Option<u64>,
pub payment_processed_amount: Option<u64>,
pub payment_processed_amount_in_usd: Option<u64>,
pub payment_processed_count: Option<u64>,
pub payment_processed_amount_without_smart_retries: Option<u64>,
pub payment_processed_amount_without_smart_retries_usd: Option<u64>,
pub payment_processed_count_without_smart_retries: Option<u64>,
pub avg_ticket_size: Option<f64>,
pub payment_error_message: Option<Vec<ErrorResult>>,
pub retries_count: Option<u64>,
pub retries_amount_processed: Option<u64>,
pub connector_success_rate: Option<f64>,
pub payments_success_rate_distribution: Option<f64>,
pub payments_success_rate_distribution_without_smart_retries: Option<f64>,
pub payments_success_rate_distribution_with_only_retries: Option<f64>,
pub payments_failure_rate_distribution: Option<f64>,
pub payments_failure_rate_distribution_without_smart_retries: Option<f64>,
pub payments_failure_rate_distribution_with_only_retries: Option<f64>,
pub failure_reason_count: Option<u64>,
pub failure_reason_count_without_smart_retries: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct MetricsBucketResponse {
#[serde(flatten)]
pub values: PaymentMetricsBucketValue,
#[serde(flatten)]
pub dimensions: PaymentMetricsBucketIdentifier,
}
| 2,026 | 2,008 |
hyperswitch | crates/api_models/src/analytics/connector_events.rs | .rs | #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ConnectorEventsRequest {
pub payment_id: common_utils::id_type::PaymentId,
pub refund_id: Option<String>,
pub dispute_id: Option<String>,
}
| 51 | 2,009 |
hyperswitch | crates/api_models/src/analytics/auth_events.rs | .rs | use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use common_enums::{
AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus,
};
use super::{NameDescription, TimeRange};
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct AuthEventFilters {
#[serde(default)]
pub authentication_status: Vec<AuthenticationStatus>,
#[serde(default)]
pub trans_status: Vec<TransactionStatus>,
#[serde(default)]
pub authentication_type: Vec<DecoupledAuthenticationType>,
#[serde(default)]
pub error_message: Vec<String>,
#[serde(default)]
pub authentication_connector: Vec<AuthenticationConnectors>,
#[serde(default)]
pub message_version: Vec<String>,
#[serde(default)]
pub acs_reference_number: Vec<String>,
}
#[derive(
Debug,
serde::Serialize,
serde::Deserialize,
strum::AsRefStr,
PartialEq,
PartialOrd,
Eq,
Ord,
strum::Display,
strum::EnumIter,
Clone,
Copy,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum AuthEventDimensions {
AuthenticationStatus,
#[strum(serialize = "trans_status")]
#[serde(rename = "trans_status")]
TransactionStatus,
AuthenticationType,
ErrorMessage,
AuthenticationConnector,
MessageVersion,
AcsReferenceNumber,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum AuthEventMetrics {
AuthenticationCount,
AuthenticationAttemptCount,
AuthenticationSuccessCount,
ChallengeFlowCount,
FrictionlessFlowCount,
FrictionlessSuccessCount,
ChallengeAttemptCount,
ChallengeSuccessCount,
AuthenticationErrorMessage,
AuthenticationFunnel,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
pub enum AuthEventFlows {
IncomingWebhookReceive,
PaymentsExternalAuthentication,
}
pub mod metric_behaviour {
pub struct AuthenticationCount;
pub struct AuthenticationAttemptCount;
pub struct AuthenticationSuccessCount;
pub struct ChallengeFlowCount;
pub struct FrictionlessFlowCount;
pub struct FrictionlessSuccessCount;
pub struct ChallengeAttemptCount;
pub struct ChallengeSuccessCount;
pub struct AuthenticationErrorMessage;
pub struct AuthenticationFunnel;
}
impl From<AuthEventMetrics> for NameDescription {
fn from(value: AuthEventMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
impl From<AuthEventDimensions> for NameDescription {
fn from(value: AuthEventDimensions) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct AuthEventMetricsBucketIdentifier {
pub authentication_status: Option<AuthenticationStatus>,
pub trans_status: Option<TransactionStatus>,
pub authentication_type: Option<DecoupledAuthenticationType>,
pub error_message: Option<String>,
pub authentication_connector: Option<AuthenticationConnectors>,
pub message_version: Option<String>,
pub acs_reference_number: Option<String>,
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
#[serde(rename = "time_bucket")]
#[serde(with = "common_utils::custom_serde::iso8601custom")]
pub start_time: time::PrimitiveDateTime,
}
impl AuthEventMetricsBucketIdentifier {
#[allow(clippy::too_many_arguments)]
pub fn new(
authentication_status: Option<AuthenticationStatus>,
trans_status: Option<TransactionStatus>,
authentication_type: Option<DecoupledAuthenticationType>,
error_message: Option<String>,
authentication_connector: Option<AuthenticationConnectors>,
message_version: Option<String>,
acs_reference_number: Option<String>,
normalized_time_range: TimeRange,
) -> Self {
Self {
authentication_status,
trans_status,
authentication_type,
error_message,
authentication_connector,
message_version,
acs_reference_number,
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
}
}
impl Hash for AuthEventMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.authentication_status.hash(state);
self.trans_status.hash(state);
self.authentication_type.hash(state);
self.authentication_connector.hash(state);
self.message_version.hash(state);
self.acs_reference_number.hash(state);
self.error_message.hash(state);
self.time_bucket.hash(state);
}
}
impl PartialEq for AuthEventMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
#[derive(Debug, serde::Serialize)]
pub struct AuthEventMetricsBucketValue {
pub authentication_count: Option<u64>,
pub authentication_attempt_count: Option<u64>,
pub authentication_success_count: Option<u64>,
pub challenge_flow_count: Option<u64>,
pub challenge_attempt_count: Option<u64>,
pub challenge_success_count: Option<u64>,
pub frictionless_flow_count: Option<u64>,
pub frictionless_success_count: Option<u64>,
pub error_message_count: Option<u64>,
pub authentication_funnel: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct MetricsBucketResponse {
#[serde(flatten)]
pub values: AuthEventMetricsBucketValue,
#[serde(flatten)]
pub dimensions: AuthEventMetricsBucketIdentifier,
}
| 1,310 | 2,010 |
hyperswitch | crates/api_models/src/analytics/payment_intents.rs | .rs | use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use common_utils::id_type;
use super::{ForexMetric, NameDescription, TimeRange};
use crate::enums::{
AuthenticationType, Connector, Currency, IntentStatus, PaymentMethod, PaymentMethodType,
};
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct PaymentIntentFilters {
#[serde(default)]
pub status: Vec<IntentStatus>,
#[serde(default)]
pub currency: Vec<Currency>,
#[serde(default)]
pub profile_id: Vec<id_type::ProfileId>,
#[serde(default)]
pub connector: Vec<Connector>,
#[serde(default)]
pub auth_type: Vec<AuthenticationType>,
#[serde(default)]
pub payment_method: Vec<PaymentMethod>,
#[serde(default)]
pub payment_method_type: Vec<PaymentMethodType>,
#[serde(default)]
pub card_network: Vec<String>,
#[serde(default)]
pub merchant_id: Vec<id_type::MerchantId>,
#[serde(default)]
pub card_last_4: Vec<String>,
#[serde(default)]
pub card_issuer: Vec<String>,
#[serde(default)]
pub error_reason: Vec<String>,
#[serde(default)]
pub customer_id: Vec<id_type::CustomerId>,
}
#[derive(
Debug,
serde::Serialize,
serde::Deserialize,
strum::AsRefStr,
PartialEq,
PartialOrd,
Eq,
Ord,
strum::Display,
strum::EnumIter,
Clone,
Copy,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PaymentIntentDimensions {
#[strum(serialize = "status")]
#[serde(rename = "status")]
PaymentIntentStatus,
Currency,
ProfileId,
Connector,
#[strum(serialize = "authentication_type")]
#[serde(rename = "authentication_type")]
AuthType,
PaymentMethod,
PaymentMethodType,
CardNetwork,
MerchantId,
#[strum(serialize = "card_last_4")]
#[serde(rename = "card_last_4")]
CardLast4,
CardIssuer,
ErrorReason,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum PaymentIntentMetrics {
SuccessfulSmartRetries,
TotalSmartRetries,
SmartRetriedAmount,
PaymentIntentCount,
PaymentsSuccessRate,
PaymentProcessedAmount,
SessionizedSuccessfulSmartRetries,
SessionizedTotalSmartRetries,
SessionizedSmartRetriedAmount,
SessionizedPaymentIntentCount,
SessionizedPaymentsSuccessRate,
SessionizedPaymentProcessedAmount,
SessionizedPaymentsDistribution,
}
impl ForexMetric for PaymentIntentMetrics {
fn is_forex_metric(&self) -> bool {
matches!(
self,
Self::PaymentProcessedAmount
| Self::SmartRetriedAmount
| Self::SessionizedPaymentProcessedAmount
| Self::SessionizedSmartRetriedAmount
)
}
}
#[derive(Debug, Default, serde::Serialize)]
pub struct ErrorResult {
pub reason: String,
pub count: i64,
pub percentage: f64,
}
pub mod metric_behaviour {
pub struct SuccessfulSmartRetries;
pub struct TotalSmartRetries;
pub struct SmartRetriedAmount;
pub struct PaymentIntentCount;
pub struct PaymentsSuccessRate;
}
impl From<PaymentIntentMetrics> for NameDescription {
fn from(value: PaymentIntentMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
impl From<PaymentIntentDimensions> for NameDescription {
fn from(value: PaymentIntentDimensions) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct PaymentIntentMetricsBucketIdentifier {
pub status: Option<IntentStatus>,
pub currency: Option<Currency>,
pub profile_id: Option<String>,
pub connector: Option<String>,
pub auth_type: Option<AuthenticationType>,
pub payment_method: Option<String>,
pub payment_method_type: Option<String>,
pub card_network: Option<String>,
pub merchant_id: Option<String>,
pub card_last_4: Option<String>,
pub card_issuer: Option<String>,
pub error_reason: Option<String>,
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
#[serde(rename = "time_bucket")]
#[serde(with = "common_utils::custom_serde::iso8601custom")]
pub start_time: time::PrimitiveDateTime,
}
impl PaymentIntentMetricsBucketIdentifier {
#[allow(clippy::too_many_arguments)]
pub fn new(
status: Option<IntentStatus>,
currency: Option<Currency>,
profile_id: Option<String>,
connector: Option<String>,
auth_type: Option<AuthenticationType>,
payment_method: Option<String>,
payment_method_type: Option<String>,
card_network: Option<String>,
merchant_id: Option<String>,
card_last_4: Option<String>,
card_issuer: Option<String>,
error_reason: Option<String>,
normalized_time_range: TimeRange,
) -> Self {
Self {
status,
currency,
profile_id,
connector,
auth_type,
payment_method,
payment_method_type,
card_network,
merchant_id,
card_last_4,
card_issuer,
error_reason,
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
}
}
impl Hash for PaymentIntentMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.status.map(|i| i.to_string()).hash(state);
self.currency.hash(state);
self.profile_id.hash(state);
self.connector.hash(state);
self.auth_type.map(|i| i.to_string()).hash(state);
self.payment_method.hash(state);
self.payment_method_type.hash(state);
self.card_network.hash(state);
self.merchant_id.hash(state);
self.card_last_4.hash(state);
self.card_issuer.hash(state);
self.error_reason.hash(state);
self.time_bucket.hash(state);
}
}
impl PartialEq for PaymentIntentMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
#[derive(Debug, serde::Serialize)]
pub struct PaymentIntentMetricsBucketValue {
pub successful_smart_retries: Option<u64>,
pub total_smart_retries: Option<u64>,
pub smart_retried_amount: Option<u64>,
pub smart_retried_amount_in_usd: Option<u64>,
pub smart_retried_amount_without_smart_retries: Option<u64>,
pub smart_retried_amount_without_smart_retries_in_usd: Option<u64>,
pub payment_intent_count: Option<u64>,
pub successful_payments: Option<u32>,
pub successful_payments_without_smart_retries: Option<u32>,
pub total_payments: Option<u32>,
pub payments_success_rate: Option<f64>,
pub payments_success_rate_without_smart_retries: Option<f64>,
pub payment_processed_amount: Option<u64>,
pub payment_processed_amount_in_usd: Option<u64>,
pub payment_processed_count: Option<u64>,
pub payment_processed_amount_without_smart_retries: Option<u64>,
pub payment_processed_amount_without_smart_retries_in_usd: Option<u64>,
pub payment_processed_count_without_smart_retries: Option<u64>,
pub payments_success_rate_distribution_without_smart_retries: Option<f64>,
pub payments_failure_rate_distribution_without_smart_retries: Option<f64>,
}
#[derive(Debug, serde::Serialize)]
pub struct MetricsBucketResponse {
#[serde(flatten)]
pub values: PaymentIntentMetricsBucketValue,
#[serde(flatten)]
pub dimensions: PaymentIntentMetricsBucketIdentifier,
}
| 1,807 | 2,011 |
hyperswitch | crates/api_models/src/analytics/outgoing_webhook_event.rs | .rs | #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct OutgoingWebhookLogsRequest {
pub payment_id: common_utils::id_type::PaymentId,
pub event_id: Option<String>,
pub refund_id: Option<String>,
pub dispute_id: Option<String>,
pub mandate_id: Option<String>,
pub payment_method_id: Option<String>,
pub attempt_id: Option<String>,
}
| 87 | 2,012 |
hyperswitch | crates/api_models/src/analytics/refunds.rs | .rs | use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use common_utils::id_type;
use crate::enums::{Currency, RefundStatus};
#[derive(
Clone,
Copy,
Debug,
Default,
Hash,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
// TODO RefundType api_models_oss need to mapped to storage_model
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RefundType {
InstantRefund,
#[default]
RegularRefund,
RetryRefund,
}
use super::{ForexMetric, NameDescription, TimeRange};
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct RefundFilters {
#[serde(default)]
pub currency: Vec<Currency>,
#[serde(default)]
pub refund_status: Vec<RefundStatus>,
#[serde(default)]
pub connector: Vec<String>,
#[serde(default)]
pub refund_type: Vec<RefundType>,
#[serde(default)]
pub profile_id: Vec<id_type::ProfileId>,
#[serde(default)]
pub refund_reason: Vec<String>,
#[serde(default)]
pub refund_error_message: Vec<String>,
}
#[derive(
Debug,
serde::Serialize,
serde::Deserialize,
strum::AsRefStr,
PartialEq,
PartialOrd,
Eq,
Ord,
strum::Display,
strum::EnumIter,
Clone,
Copy,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RefundDimensions {
Currency,
RefundStatus,
Connector,
RefundType,
ProfileId,
RefundReason,
RefundErrorMessage,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum RefundMetrics {
RefundSuccessRate,
RefundCount,
RefundSuccessCount,
RefundProcessedAmount,
SessionizedRefundSuccessRate,
SessionizedRefundCount,
SessionizedRefundSuccessCount,
SessionizedRefundProcessedAmount,
SessionizedRefundReason,
SessionizedRefundErrorMessage,
}
#[derive(Debug, Default, serde::Serialize)]
pub struct ReasonsResult {
pub reason: String,
pub count: i64,
pub percentage: f64,
}
#[derive(Debug, Default, serde::Serialize)]
pub struct ErrorMessagesResult {
pub error_message: String,
pub count: i64,
pub percentage: f64,
}
#[derive(
Clone,
Copy,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum RefundDistributions {
#[strum(serialize = "refund_reason")]
SessionizedRefundReason,
#[strum(serialize = "refund_error_message")]
SessionizedRefundErrorMessage,
}
impl ForexMetric for RefundMetrics {
fn is_forex_metric(&self) -> bool {
matches!(
self,
Self::RefundProcessedAmount | Self::SessionizedRefundProcessedAmount
)
}
}
pub mod metric_behaviour {
pub struct RefundSuccessRate;
pub struct RefundCount;
pub struct RefundSuccessCount;
pub struct RefundProcessedAmount;
}
impl From<RefundMetrics> for NameDescription {
fn from(value: RefundMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
impl From<RefundDimensions> for NameDescription {
fn from(value: RefundDimensions) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct RefundMetricsBucketIdentifier {
pub currency: Option<Currency>,
pub refund_status: Option<String>,
pub connector: Option<String>,
pub refund_type: Option<String>,
pub profile_id: Option<String>,
pub refund_reason: Option<String>,
pub refund_error_message: Option<String>,
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
#[serde(rename = "time_bucket")]
#[serde(with = "common_utils::custom_serde::iso8601custom")]
pub start_time: time::PrimitiveDateTime,
}
impl Hash for RefundMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.currency.hash(state);
self.refund_status.hash(state);
self.connector.hash(state);
self.refund_type.hash(state);
self.profile_id.hash(state);
self.refund_reason.hash(state);
self.refund_error_message.hash(state);
self.time_bucket.hash(state);
}
}
impl PartialEq for RefundMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
impl RefundMetricsBucketIdentifier {
#[allow(clippy::too_many_arguments)]
pub fn new(
currency: Option<Currency>,
refund_status: Option<String>,
connector: Option<String>,
refund_type: Option<String>,
profile_id: Option<String>,
refund_reason: Option<String>,
refund_error_message: Option<String>,
normalized_time_range: TimeRange,
) -> Self {
Self {
currency,
refund_status,
connector,
refund_type,
profile_id,
refund_reason,
refund_error_message,
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
}
}
#[derive(Debug, serde::Serialize)]
pub struct RefundMetricsBucketValue {
pub successful_refunds: Option<u32>,
pub total_refunds: Option<u32>,
pub refund_success_rate: Option<f64>,
pub refund_count: Option<u64>,
pub refund_success_count: Option<u64>,
pub refund_processed_amount: Option<u64>,
pub refund_processed_amount_in_usd: Option<u64>,
pub refund_processed_count: Option<u64>,
pub refund_reason_distribution: Option<Vec<ReasonsResult>>,
pub refund_error_message_distribution: Option<Vec<ErrorMessagesResult>>,
pub refund_reason_count: Option<u64>,
pub refund_error_message_count: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct RefundMetricsBucketResponse {
#[serde(flatten)]
pub values: RefundMetricsBucketValue,
#[serde(flatten)]
pub dimensions: RefundMetricsBucketIdentifier,
}
| 1,551 | 2,013 |
hyperswitch | crates/api_models/src/analytics/api_event.rs | .rs | use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use super::{NameDescription, TimeRange};
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ApiLogsRequest {
#[serde(flatten)]
pub query_param: QueryType,
}
pub enum FilterType {
ApiCountFilter,
LatencyFilter,
StatusCodeFilter,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(tag = "type")]
pub enum QueryType {
Payment {
payment_id: common_utils::id_type::PaymentId,
},
Refund {
payment_id: common_utils::id_type::PaymentId,
refund_id: String,
},
Dispute {
payment_id: common_utils::id_type::PaymentId,
dispute_id: String,
},
}
#[derive(
Debug,
serde::Serialize,
serde::Deserialize,
strum::AsRefStr,
PartialEq,
PartialOrd,
Eq,
Ord,
strum::Display,
strum::EnumIter,
Clone,
Copy,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ApiEventDimensions {
// Do not change the order of these enums
// Consult the Dashboard FE folks since these also affects the order of metrics on FE
StatusCode,
FlowType,
ApiFlow,
}
impl From<ApiEventDimensions> for NameDescription {
fn from(value: ApiEventDimensions) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct ApiEventFilters {
pub status_code: Vec<u64>,
pub flow_type: Vec<String>,
pub api_flow: Vec<String>,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum ApiEventMetrics {
Latency,
ApiCount,
StatusCodeCount,
}
impl From<ApiEventMetrics> for NameDescription {
fn from(value: ApiEventMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct ApiEventMetricsBucketIdentifier {
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
// Coz FE sucks
#[serde(rename = "time_bucket")]
#[serde(with = "common_utils::custom_serde::iso8601custom")]
pub start_time: time::PrimitiveDateTime,
}
impl ApiEventMetricsBucketIdentifier {
pub fn new(normalized_time_range: TimeRange) -> Self {
Self {
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
}
}
impl Hash for ApiEventMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.time_bucket.hash(state);
}
}
impl PartialEq for ApiEventMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
#[derive(Debug, serde::Serialize)]
pub struct ApiEventMetricsBucketValue {
pub latency: Option<u64>,
pub api_count: Option<u64>,
pub status_code_count: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct ApiMetricsBucketResponse {
#[serde(flatten)]
pub values: ApiEventMetricsBucketValue,
#[serde(flatten)]
pub dimensions: ApiEventMetricsBucketIdentifier,
}
| 864 | 2,014 |
hyperswitch | crates/api_models/src/analytics/sdk_events.rs | .rs | use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use super::{NameDescription, TimeRange};
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SdkEventsRequest {
pub payment_id: common_utils::id_type::PaymentId,
pub time_range: TimeRange,
}
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct SdkEventFilters {
#[serde(default)]
pub payment_method: Vec<String>,
#[serde(default)]
pub platform: Vec<String>,
#[serde(default)]
pub browser_name: Vec<String>,
#[serde(default)]
pub source: Vec<String>,
#[serde(default)]
pub component: Vec<String>,
#[serde(default)]
pub payment_experience: Vec<String>,
}
#[derive(
Debug,
serde::Serialize,
serde::Deserialize,
strum::AsRefStr,
PartialEq,
PartialOrd,
Eq,
Ord,
strum::Display,
strum::EnumIter,
Clone,
Copy,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum SdkEventDimensions {
// Do not change the order of these enums
// Consult the Dashboard FE folks since these also affects the order of metrics on FE
PaymentMethod,
Platform,
BrowserName,
Source,
Component,
PaymentExperience,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum SdkEventMetrics {
PaymentAttempts,
PaymentMethodsCallCount,
SdkRenderedCount,
SdkInitiatedCount,
PaymentMethodSelectedCount,
PaymentDataFilledCount,
AveragePaymentTime,
LoadTime,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SdkEventNames {
OrcaElementsCalled,
AppRendered,
PaymentMethodChanged,
PaymentDataFilled,
PaymentAttempt,
PaymentMethodsCall,
ConfirmCall,
SessionsCall,
CustomerPaymentMethodsCall,
RedirectingUser,
DisplayBankTransferInfoPage,
DisplayQrCodeInfoPage,
AuthenticationCall,
AuthenticationCallInit,
ThreeDsMethodCall,
ThreeDsMethodResult,
ThreeDsMethod,
LoaderChanged,
DisplayThreeDsSdk,
ThreeDsSdkInit,
AreqParamsGeneration,
ChallengePresented,
ChallengeComplete,
}
pub mod metric_behaviour {
pub struct PaymentAttempts;
pub struct PaymentMethodsCallCount;
pub struct SdkRenderedCount;
pub struct SdkInitiatedCount;
pub struct PaymentMethodSelectedCount;
pub struct PaymentDataFilledCount;
pub struct AveragePaymentTime;
pub struct LoadTime;
}
impl From<SdkEventMetrics> for NameDescription {
fn from(value: SdkEventMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
impl From<SdkEventDimensions> for NameDescription {
fn from(value: SdkEventDimensions) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct SdkEventMetricsBucketIdentifier {
pub payment_method: Option<String>,
pub platform: Option<String>,
pub browser_name: Option<String>,
pub source: Option<String>,
pub component: Option<String>,
pub payment_experience: Option<String>,
pub time_bucket: Option<String>,
}
impl SdkEventMetricsBucketIdentifier {
pub fn new(
payment_method: Option<String>,
platform: Option<String>,
browser_name: Option<String>,
source: Option<String>,
component: Option<String>,
payment_experience: Option<String>,
time_bucket: Option<String>,
) -> Self {
Self {
payment_method,
platform,
browser_name,
source,
component,
payment_experience,
time_bucket,
}
}
}
impl Hash for SdkEventMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.payment_method.hash(state);
self.platform.hash(state);
self.browser_name.hash(state);
self.source.hash(state);
self.component.hash(state);
self.payment_experience.hash(state);
self.time_bucket.hash(state);
}
}
impl PartialEq for SdkEventMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
#[derive(Debug, serde::Serialize)]
pub struct SdkEventMetricsBucketValue {
pub payment_attempts: Option<u64>,
pub payment_methods_call_count: Option<u64>,
pub average_payment_time: Option<u64>,
pub load_time: Option<u64>,
pub sdk_rendered_count: Option<u64>,
pub sdk_initiated_count: Option<u64>,
pub payment_method_selected_count: Option<u64>,
pub payment_data_filled_count: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct MetricsBucketResponse {
#[serde(flatten)]
pub values: SdkEventMetricsBucketValue,
#[serde(flatten)]
pub dimensions: SdkEventMetricsBucketIdentifier,
}
| 1,285 | 2,015 |
hyperswitch | crates/api_models/src/analytics/active_payments.rs | .rs | use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use super::NameDescription;
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum ActivePaymentsMetrics {
ActivePayments,
}
pub mod metric_behaviour {
pub struct ActivePayments;
}
impl From<ActivePaymentsMetrics> for NameDescription {
fn from(value: ActivePaymentsMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct ActivePaymentsMetricsBucketIdentifier {
pub time_bucket: Option<String>,
}
impl ActivePaymentsMetricsBucketIdentifier {
pub fn new(time_bucket: Option<String>) -> Self {
Self { time_bucket }
}
}
impl Hash for ActivePaymentsMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.time_bucket.hash(state);
}
}
impl PartialEq for ActivePaymentsMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
#[derive(Debug, serde::Serialize)]
pub struct ActivePaymentsMetricsBucketValue {
pub active_payments: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct MetricsBucketResponse {
#[serde(flatten)]
pub values: ActivePaymentsMetricsBucketValue,
#[serde(flatten)]
pub dimensions: ActivePaymentsMetricsBucketIdentifier,
}
| 403 | 2,016 |
hyperswitch | crates/api_models/src/user/sample_data.rs | .rs | use common_enums::{AuthenticationType, CountryAlpha2};
use time::PrimitiveDateTime;
use crate::enums::Connector;
#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct SampleDataRequest {
pub record: Option<usize>,
pub connector: Option<Vec<Connector>>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub start_time: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub end_time: Option<PrimitiveDateTime>,
// The amount for each sample will be between min_amount and max_amount (in dollars)
pub min_amount: Option<i64>,
pub max_amount: Option<i64>,
pub currency: Option<Vec<common_enums::Currency>>,
pub auth_type: Option<Vec<AuthenticationType>>,
pub business_country: Option<CountryAlpha2>,
pub business_label: Option<String>,
pub profile_id: Option<common_utils::id_type::ProfileId>,
}
| 225 | 2,017 |
hyperswitch | crates/api_models/src/user/dashboard_metadata.rs | .rs | use common_enums::{CountryAlpha2, MerchantProductType};
use common_utils::{id_type, pii};
use masking::Secret;
use strum::EnumString;
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub enum SetMetaDataRequest {
ProductionAgreement(ProductionAgreementRequest),
SetupProcessor(SetupProcessor),
ConfigureEndpoint,
SetupComplete,
FirstProcessorConnected(ProcessorConnected),
SecondProcessorConnected(ProcessorConnected),
ConfiguredRouting(ConfiguredRouting),
TestPayment(TestPayment),
IntegrationMethod(IntegrationMethod),
ConfigurationType(ConfigurationType),
IntegrationCompleted,
SPRoutingConfigured(ConfiguredRouting),
Feedback(Feedback),
ProdIntent(ProdIntent),
SPTestPayment,
DownloadWoocom,
ConfigureWoocom,
SetupWoocomWebhook,
IsMultipleConfiguration,
#[serde(skip)]
IsChangePasswordRequired,
OnboardingSurvey(OnboardingSurvey),
ReconStatus(ReconStatus),
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ProductionAgreementRequest {
pub version: String,
#[serde(skip_deserializing)]
pub ip_address: Option<Secret<String, pii::IpAddress>>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct SetupProcessor {
pub connector_id: String,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ProcessorConnected {
pub processor_id: id_type::MerchantConnectorAccountId,
pub processor_name: String,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct OnboardingSurvey {
pub designation: Option<String>,
pub about_business: Option<String>,
pub business_website: Option<String>,
pub hyperswitch_req: Option<String>,
pub major_markets: Option<Vec<String>>,
pub business_size: Option<String>,
pub required_features: Option<Vec<String>>,
pub required_processors: Option<Vec<String>>,
pub planned_live_date: Option<String>,
pub miscellaneous: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ConfiguredRouting {
pub routing_id: String,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct TestPayment {
pub payment_id: id_type::PaymentId,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct IntegrationMethod {
pub integration_type: String,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub enum ConfigurationType {
Single,
Multiple,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct Feedback {
pub email: pii::Email,
pub description: Option<String>,
pub rating: Option<i32>,
pub category: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct ProdIntent {
pub legal_business_name: Option<String>,
pub business_label: Option<String>,
pub business_location: Option<CountryAlpha2>,
pub display_name: Option<String>,
pub poc_email: Option<Secret<String>>,
pub business_type: Option<String>,
pub business_identifier: Option<String>,
pub business_website: Option<String>,
pub poc_name: Option<String>,
pub poc_contact: Option<String>,
pub comments: Option<String>,
pub is_completed: bool,
#[serde(default)]
pub product_type: MerchantProductType,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct ReconStatus {
pub is_order_data_set: bool,
pub is_processor_data_set: bool,
}
#[derive(Debug, serde::Deserialize, EnumString, serde::Serialize)]
pub enum GetMetaDataRequest {
ProductionAgreement,
SetupProcessor,
ConfigureEndpoint,
SetupComplete,
FirstProcessorConnected,
SecondProcessorConnected,
ConfiguredRouting,
TestPayment,
IntegrationMethod,
ConfigurationType,
IntegrationCompleted,
StripeConnected,
PaypalConnected,
SPRoutingConfigured,
Feedback,
ProdIntent,
SPTestPayment,
DownloadWoocom,
ConfigureWoocom,
SetupWoocomWebhook,
IsMultipleConfiguration,
IsChangePasswordRequired,
OnboardingSurvey,
ReconStatus,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(transparent)]
pub struct GetMultipleMetaDataPayload {
pub results: Vec<GetMetaDataRequest>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct GetMultipleMetaDataRequest {
pub keys: String,
}
#[derive(Debug, serde::Serialize)]
pub enum GetMetaDataResponse {
ProductionAgreement(bool),
SetupProcessor(Option<SetupProcessor>),
ConfigureEndpoint(bool),
SetupComplete(bool),
FirstProcessorConnected(Option<ProcessorConnected>),
SecondProcessorConnected(Option<ProcessorConnected>),
ConfiguredRouting(Option<ConfiguredRouting>),
TestPayment(Option<TestPayment>),
IntegrationMethod(Option<IntegrationMethod>),
ConfigurationType(Option<ConfigurationType>),
IntegrationCompleted(bool),
StripeConnected(Option<ProcessorConnected>),
PaypalConnected(Option<ProcessorConnected>),
SPRoutingConfigured(Option<ConfiguredRouting>),
Feedback(Option<Feedback>),
ProdIntent(Option<ProdIntent>),
SPTestPayment(bool),
DownloadWoocom(bool),
ConfigureWoocom(bool),
SetupWoocomWebhook(bool),
IsMultipleConfiguration(bool),
IsChangePasswordRequired(bool),
OnboardingSurvey(Option<OnboardingSurvey>),
ReconStatus(Option<ReconStatus>),
}
| 1,160 | 2,018 |
hyperswitch | crates/api_models/src/user/theme.rs | .rs | use actix_multipart::form::{bytes::Bytes, text::Text, MultipartForm};
use common_enums::EntityType;
use common_utils::{
id_type,
types::theme::{EmailThemeConfig, ThemeLineage},
};
use masking::Secret;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize)]
pub struct GetThemeResponse {
pub theme_id: String,
pub theme_name: String,
pub entity_type: EntityType,
pub tenant_id: id_type::TenantId,
pub org_id: Option<id_type::OrganizationId>,
pub merchant_id: Option<id_type::MerchantId>,
pub profile_id: Option<id_type::ProfileId>,
pub email_config: EmailThemeConfig,
pub theme_data: ThemeData,
}
#[derive(Debug, MultipartForm)]
pub struct UploadFileAssetData {
pub asset_name: Text<String>,
#[multipart(limit = "10MB")]
pub asset_data: Bytes,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct UploadFileRequest {
pub lineage: ThemeLineage,
pub asset_name: String,
pub asset_data: Secret<Vec<u8>>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CreateThemeRequest {
pub lineage: ThemeLineage,
pub theme_name: String,
pub theme_data: ThemeData,
pub email_config: Option<EmailThemeConfig>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct UpdateThemeRequest {
pub lineage: ThemeLineage,
pub theme_data: ThemeData,
// TODO: Add support to update email config
}
// All the below structs are for the theme.json file,
// which will be used by frontend to style the dashboard.
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ThemeData {
settings: Settings,
urls: Option<Urls>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Settings {
colors: Colors,
sidebar: Option<Sidebar>,
typography: Option<Typography>,
buttons: Buttons,
borders: Option<Borders>,
spacing: Option<Spacing>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Colors {
primary: String,
secondary: Option<String>,
background: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Sidebar {
primary: String,
text_color: Option<String>,
text_color_primary: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Typography {
font_family: Option<String>,
font_size: Option<String>,
heading_font_size: Option<String>,
text_color: Option<String>,
link_color: Option<String>,
link_hover_color: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Buttons {
primary: PrimaryButton,
secondary: Option<SecondaryButton>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct PrimaryButton {
background_color: Option<String>,
text_color: Option<String>,
hover_background_color: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct SecondaryButton {
background_color: Option<String>,
text_color: Option<String>,
hover_background_color: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Borders {
default_radius: Option<String>,
border_color: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Spacing {
padding: Option<String>,
margin: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Urls {
favicon_url: Option<String>,
logo_url: Option<String>,
}
| 834 | 2,019 |
hyperswitch | crates/common_utils/Cargo.toml | .toml | [package]
name = "common_utils"
description = "Utilities shared across `router` and other crates"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
readme = "README.md"
license.workspace = true
[features]
default = []
keymanager = ["dep:router_env"]
keymanager_mtls = ["reqwest/rustls-tls"]
encryption_service = ["dep:router_env"]
km_forward_x_request_id = ["dep:router_env", "router_env/actix_web"]
signals = ["dep:signal-hook-tokio", "dep:signal-hook", "dep:tokio", "dep:router_env", "dep:futures"]
async_ext = ["dep:async-trait", "dep:futures"]
logs = ["dep:router_env"]
metrics = ["dep:router_env", "dep:futures"]
payouts = ["common_enums/payouts"]
v1 = []
v2 = []
customer_v2 = []
payment_methods_v2 = []
crypto_openssl = ["dep:openssl"]
[dependencies]
async-trait = { version = "0.1.79", optional = true }
base64 = "0.22.0"
base64-serde = "0.8.0"
blake3 = { version = "1.5.1", features = ["serde"] }
bytes = "1.6.0"
diesel = "2.2.3"
error-stack = "0.4.1"
futures = { version = "0.3.30", optional = true }
globset = "0.4.14"
hex = "0.4.3"
http = "0.2.12"
md5 = "0.7.0"
nanoid = "0.4.0"
nutype = { version = "0.4.2", features = ["serde"] }
once_cell = "1.19.0"
phonenumber = "0.3.3"
quick-xml = { version = "0.31.0", features = ["serialize"] }
rand = "0.8.5"
regex = "1.10.4"
reqwest = { version = "0.11.27", features = ["json", "native-tls", "gzip", "multipart"] }
ring = { version = "0.17.8", features = ["std", "wasm32_unknown_unknown_js"] }
rust_decimal = "1.35"
rustc-hash = "1.1.0"
semver = { version = "1.0.22", features = ["serde"] }
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
serde_urlencoded = "0.7.1"
signal-hook = { version = "0.3.17", optional = true }
strum = { version = "0.26.2", features = ["derive"] }
thiserror = "1.0.58"
time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] }
tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"], optional = true }
url = { version = "2.5.0", features = ["serde"] }
utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] }
uuid = { version = "1.8.0", features = ["v7"] }
openssl = {version = "0.10.70", optional = true}
# First party crates
common_enums = { version = "0.1.0", path = "../common_enums" }
masking = { version = "0.1.0", path = "../masking" }
router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"], optional = true, default-features = false }
[target.'cfg(not(target_os = "windows"))'.dependencies]
signal-hook-tokio = { version = "0.3.1", features = ["futures-v0_3"], optional = true }
[dev-dependencies]
fake = "2.9.2"
proptest = "1.4.0"
test-case = "3.3.1"
[lints]
workspace = true
| 971 | 2,020 |
hyperswitch | crates/common_utils/README.md | .md | # Common Utils
Utilities shared across `router` and other crates.
| 14 | 2,021 |
hyperswitch | crates/common_utils/tests/percentage.rs | .rs | #![allow(clippy::panic_in_result_fn)]
use common_utils::{errors::PercentageError, types::Percentage};
const PRECISION_2: u8 = 2;
const PRECISION_0: u8 = 0;
#[test]
fn invalid_range_more_than_100() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let percentage = Percentage::<PRECISION_2>::from_string("100.01".to_string());
assert!(percentage.is_err());
if let Err(err) = percentage {
assert_eq!(
*err.current_context(),
PercentageError::InvalidPercentageValue
)
}
Ok(())
}
#[test]
fn invalid_range_less_than_0() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let percentage = Percentage::<PRECISION_2>::from_string("-0.01".to_string());
assert!(percentage.is_err());
if let Err(err) = percentage {
assert_eq!(
*err.current_context(),
PercentageError::InvalidPercentageValue
)
}
Ok(())
}
#[test]
fn invalid_string() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let percentage = Percentage::<PRECISION_2>::from_string("-0.01ed".to_string());
assert!(percentage.is_err());
if let Err(err) = percentage {
assert_eq!(
*err.current_context(),
PercentageError::InvalidPercentageValue
)
}
Ok(())
}
#[test]
fn valid_range() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let percentage = Percentage::<PRECISION_2>::from_string("2.22".to_string());
assert!(percentage.is_ok());
if let Ok(percentage) = percentage {
assert_eq!(percentage.get_percentage(), 2.22)
}
let percentage = Percentage::<PRECISION_2>::from_string("0.05".to_string());
assert!(percentage.is_ok());
if let Ok(percentage) = percentage {
assert_eq!(percentage.get_percentage(), 0.05)
}
let percentage = Percentage::<PRECISION_2>::from_string("100.0".to_string());
assert!(percentage.is_ok());
if let Ok(percentage) = percentage {
assert_eq!(percentage.get_percentage(), 100.0)
}
Ok(())
}
#[test]
fn valid_precision() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let percentage = Percentage::<PRECISION_2>::from_string("2.2".to_string());
assert!(percentage.is_ok());
if let Ok(percentage) = percentage {
assert_eq!(percentage.get_percentage(), 2.2)
}
let percentage = Percentage::<PRECISION_2>::from_string("2.20000".to_string());
assert!(percentage.is_ok());
if let Ok(percentage) = percentage {
assert_eq!(percentage.get_percentage(), 2.2)
}
let percentage = Percentage::<PRECISION_0>::from_string("2.0".to_string());
assert!(percentage.is_ok());
if let Ok(percentage) = percentage {
assert_eq!(percentage.get_percentage(), 2.0)
}
Ok(())
}
#[test]
fn invalid_precision() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let percentage = Percentage::<PRECISION_2>::from_string("2.221".to_string());
assert!(percentage.is_err());
if let Err(err) = percentage {
assert_eq!(
*err.current_context(),
PercentageError::InvalidPercentageValue
)
}
Ok(())
}
#[test]
fn deserialization_test_ok() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let mut decimal = 0;
let mut integer = 0;
// check for all percentage values from 0 to 100
while integer <= 100 {
let json_string = format!(
r#"
{{
"percentage" : {}.{}
}}
"#,
integer, decimal
);
let percentage = serde_json::from_str::<Percentage<PRECISION_2>>(&json_string);
assert!(percentage.is_ok());
if let Ok(percentage) = percentage {
assert_eq!(
percentage.get_percentage(),
format!("{}.{}", integer, decimal)
.parse::<f32>()
.unwrap_or_default()
)
}
if integer == 100 {
break;
}
decimal += 1;
if decimal == 100 {
decimal = 0;
integer += 1;
}
}
let json_string = r#"
{
"percentage" : 18.7
}
"#;
let percentage = serde_json::from_str::<Percentage<PRECISION_2>>(json_string);
assert!(percentage.is_ok());
if let Ok(percentage) = percentage {
assert_eq!(percentage.get_percentage(), 18.7)
}
let json_string = r#"
{
"percentage" : 12.0
}
"#;
let percentage = serde_json::from_str::<Percentage<PRECISION_0>>(json_string);
assert!(percentage.is_ok());
if let Ok(percentage) = percentage {
assert_eq!(percentage.get_percentage(), 12.0)
}
Ok(())
}
#[test]
fn deserialization_test_err() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// invalid percentage precision
let json_string = r#"
{
"percentage" : 12.4
}
"#;
let percentage = serde_json::from_str::<Percentage<PRECISION_0>>(json_string);
assert!(percentage.is_err());
if let Err(err) = percentage {
assert_eq!(err.to_string(), "invalid value: percentage value 12.4, expected value should be a float between 0 to 100 and precise to only upto 0 decimal digits at line 4 column 9".to_string())
}
// invalid percentage value
let json_string = r#"
{
"percentage" : 123.42
}
"#;
let percentage = serde_json::from_str::<Percentage<PRECISION_2>>(json_string);
assert!(percentage.is_err());
if let Err(err) = percentage {
assert_eq!(err.to_string(), "invalid value: percentage value 123.42, expected value should be a float between 0 to 100 and precise to only upto 2 decimal digits at line 4 column 9".to_string())
}
// missing percentage field
let json_string = r#"
{
"percent": 22.0
}
"#;
let percentage = serde_json::from_str::<Percentage<PRECISION_2>>(json_string);
assert!(percentage.is_err());
if let Err(err) = percentage {
assert_eq!(
err.to_string(),
"missing field `percentage` at line 4 column 9".to_string()
)
}
Ok(())
}
| 1,551 | 2,022 |
hyperswitch | crates/common_utils/src/hashing.rs | .rs | use masking::{PeekInterface, Secret, Strategy};
use serde::{Deserialize, Serialize, Serializer};
#[derive(Clone, PartialEq, Debug, Deserialize)]
/// Represents a hashed string using blake3's hashing strategy.
pub struct HashedString<T: Strategy<String>>(Secret<String, T>);
impl<T: Strategy<String>> Serialize for HashedString<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let hashed_value = blake3::hash(self.0.peek().as_bytes()).to_hex();
hashed_value.serialize(serializer)
}
}
impl<T: Strategy<String>> From<Secret<String, T>> for HashedString<T> {
fn from(value: Secret<String, T>) -> Self {
Self(value)
}
}
| 174 | 2,023 |
hyperswitch | crates/common_utils/src/custom_serde.rs | .rs | //! Custom serialization/deserialization implementations.
/// Use the well-known ISO 8601 format when serializing and deserializing an
/// [`PrimitiveDateTime`][PrimitiveDateTime].
///
/// [PrimitiveDateTime]: ::time::PrimitiveDateTime
pub mod iso8601 {
use std::num::NonZeroU8;
use serde::{ser::Error as _, Deserializer, Serialize, Serializer};
use time::{
format_description::well_known::{
iso8601::{Config, EncodedConfig, TimePrecision},
Iso8601,
},
serde::iso8601,
PrimitiveDateTime, UtcOffset,
};
const FORMAT_CONFIG: EncodedConfig = Config::DEFAULT
.set_time_precision(TimePrecision::Second {
decimal_digits: NonZeroU8::new(3),
})
.encode();
/// Serialize a [`PrimitiveDateTime`] using the well-known ISO 8601 format.
pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date_time
.assume_utc()
.format(&Iso8601::<FORMAT_CONFIG>)
.map_err(S::Error::custom)?
.serialize(serializer)
}
/// Deserialize an [`PrimitiveDateTime`] from its ISO 8601 representation.
pub fn deserialize<'a, D>(deserializer: D) -> Result<PrimitiveDateTime, D::Error>
where
D: Deserializer<'a>,
{
iso8601::deserialize(deserializer).map(|offset_date_time| {
let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC);
PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())
})
}
/// Use the well-known ISO 8601 format when serializing and deserializing an
/// [`Option<PrimitiveDateTime>`][PrimitiveDateTime].
///
/// [PrimitiveDateTime]: ::time::PrimitiveDateTime
pub mod option {
use serde::Serialize;
use time::format_description::well_known::Iso8601;
use super::*;
/// Serialize an [`Option<PrimitiveDateTime>`] using the well-known ISO 8601 format.
pub fn serialize<S>(
date_time: &Option<PrimitiveDateTime>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date_time
.map(|date_time| date_time.assume_utc().format(&Iso8601::<FORMAT_CONFIG>))
.transpose()
.map_err(S::Error::custom)?
.serialize(serializer)
}
/// Deserialize an [`Option<PrimitiveDateTime>`] from its ISO 8601 representation.
pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error>
where
D: Deserializer<'a>,
{
iso8601::option::deserialize(deserializer).map(|option_offset_date_time| {
option_offset_date_time.map(|offset_date_time| {
let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC);
PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())
})
})
}
}
/// Use the well-known ISO 8601 format which is without timezone when serializing and deserializing an
/// [`Option<PrimitiveDateTime>`][PrimitiveDateTime].
///
/// [PrimitiveDateTime]: ::time::PrimitiveDateTime
pub mod option_without_timezone {
use serde::{de, Deserialize, Serialize};
use time::macros::format_description;
use super::*;
/// Serialize an [`Option<PrimitiveDateTime>`] using the well-known ISO 8601 format which is without timezone.
pub fn serialize<S>(
date_time: &Option<PrimitiveDateTime>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date_time
.map(|date_time| {
let format =
format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]");
date_time.assume_utc().format(format)
})
.transpose()
.map_err(S::Error::custom)?
.serialize(serializer)
}
/// Deserialize an [`Option<PrimitiveDateTime>`] from its ISO 8601 representation.
pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error>
where
D: Deserializer<'a>,
{
Option::deserialize(deserializer)?
.map(|time_string| {
let format =
format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]");
PrimitiveDateTime::parse(time_string, format).map_err(|_| {
de::Error::custom(format!(
"Failed to parse PrimitiveDateTime from {time_string}"
))
})
})
.transpose()
}
}
}
/// Use the UNIX timestamp when serializing and deserializing an
/// [`PrimitiveDateTime`][PrimitiveDateTime].
///
/// [PrimitiveDateTime]: ::time::PrimitiveDateTime
pub mod timestamp {
use serde::{Deserializer, Serialize, Serializer};
use time::{serde::timestamp, PrimitiveDateTime, UtcOffset};
/// Serialize a [`PrimitiveDateTime`] using UNIX timestamp.
pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date_time
.assume_utc()
.unix_timestamp()
.serialize(serializer)
}
/// Deserialize an [`PrimitiveDateTime`] from UNIX timestamp.
pub fn deserialize<'a, D>(deserializer: D) -> Result<PrimitiveDateTime, D::Error>
where
D: Deserializer<'a>,
{
timestamp::deserialize(deserializer).map(|offset_date_time| {
let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC);
PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())
})
}
/// Use the UNIX timestamp when serializing and deserializing an
/// [`Option<PrimitiveDateTime>`][PrimitiveDateTime].
///
/// [PrimitiveDateTime]: ::time::PrimitiveDateTime
pub mod option {
use serde::Serialize;
use super::*;
/// Serialize an [`Option<PrimitiveDateTime>`] from UNIX timestamp.
pub fn serialize<S>(
date_time: &Option<PrimitiveDateTime>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date_time
.map(|date_time| date_time.assume_utc().unix_timestamp())
.serialize(serializer)
}
/// Deserialize an [`Option<PrimitiveDateTime>`] from UNIX timestamp.
pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error>
where
D: Deserializer<'a>,
{
timestamp::option::deserialize(deserializer).map(|option_offset_date_time| {
option_offset_date_time.map(|offset_date_time| {
let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC);
PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())
})
})
}
}
}
/// <https://github.com/serde-rs/serde/issues/994#issuecomment-316895860>
pub mod json_string {
use serde::{
de::{self, Deserialize, DeserializeOwned, Deserializer},
ser::{self, Serialize, Serializer},
};
/// Serialize a type to json_string format
pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
T: Serialize,
S: Serializer,
{
let j = serde_json::to_string(value).map_err(ser::Error::custom)?;
j.serialize(serializer)
}
/// Deserialize a string which is in json format
pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
T: DeserializeOwned,
D: Deserializer<'de>,
{
let j = String::deserialize(deserializer)?;
serde_json::from_str(&j).map_err(de::Error::custom)
}
}
/// Use a custom ISO 8601 format when serializing and deserializing
/// [`PrimitiveDateTime`][PrimitiveDateTime].
///
/// [PrimitiveDateTime]: ::time::PrimitiveDateTime
pub mod iso8601custom {
use serde::{ser::Error as _, Deserializer, Serialize, Serializer};
use time::{
format_description::well_known::{
iso8601::{Config, EncodedConfig, TimePrecision},
Iso8601,
},
serde::iso8601,
PrimitiveDateTime, UtcOffset,
};
const FORMAT_CONFIG: EncodedConfig = Config::DEFAULT
.set_time_precision(TimePrecision::Second {
decimal_digits: None,
})
.encode();
/// Serialize a [`PrimitiveDateTime`] using the well-known ISO 8601 format.
pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date_time
.assume_utc()
.format(&Iso8601::<FORMAT_CONFIG>)
.map_err(S::Error::custom)?
.replace('T', " ")
.replace('Z', "")
.serialize(serializer)
}
/// Deserialize an [`PrimitiveDateTime`] from its ISO 8601 representation.
pub fn deserialize<'a, D>(deserializer: D) -> Result<PrimitiveDateTime, D::Error>
where
D: Deserializer<'a>,
{
iso8601::deserialize(deserializer).map(|offset_date_time| {
let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC);
PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())
})
}
}
#[cfg(test)]
mod tests {
use serde::{Deserialize, Serialize};
use serde_json::json;
#[test]
fn test_leap_second_parse() {
#[derive(Serialize, Deserialize)]
struct Try {
#[serde(with = "crate::custom_serde::iso8601")]
f: time::PrimitiveDateTime,
}
let leap_second_date_time = json!({"f": "2023-12-31T23:59:60.000Z"});
let deser = serde_json::from_value::<Try>(leap_second_date_time);
assert!(deser.is_ok())
}
}
| 2,336 | 2,024 |
hyperswitch | crates/common_utils/src/metrics.rs | .rs | //! Utilities for metrics
pub mod utils;
| 9 | 2,025 |
hyperswitch | crates/common_utils/src/signals.rs | .rs | //! Provide Interface for worker services to handle signals
#[cfg(not(target_os = "windows"))]
use futures::StreamExt;
#[cfg(not(target_os = "windows"))]
use router_env::logger;
use tokio::sync::mpsc;
/// This functions is meant to run in parallel to the application.
/// It will send a signal to the receiver when a SIGTERM or SIGINT is received
#[cfg(not(target_os = "windows"))]
pub async fn signal_handler(mut sig: signal_hook_tokio::Signals, sender: mpsc::Sender<()>) {
if let Some(signal) = sig.next().await {
logger::info!(
"Received signal: {:?}",
signal_hook::low_level::signal_name(signal)
);
match signal {
signal_hook::consts::SIGTERM | signal_hook::consts::SIGINT => match sender.try_send(())
{
Ok(_) => {
logger::info!("Request for force shutdown received")
}
Err(_) => {
logger::error!(
"The receiver is closed, a termination call might already be sent"
)
}
},
_ => {}
}
}
}
/// This functions is meant to run in parallel to the application.
/// It will send a signal to the receiver when a SIGTERM or SIGINT is received
#[cfg(target_os = "windows")]
pub async fn signal_handler(_sig: DummySignal, _sender: mpsc::Sender<()>) {}
/// This function is used to generate a list of signals that the signal_handler should listen for
#[cfg(not(target_os = "windows"))]
pub fn get_allowed_signals() -> Result<signal_hook_tokio::SignalsInfo, std::io::Error> {
signal_hook_tokio::Signals::new([signal_hook::consts::SIGTERM, signal_hook::consts::SIGINT])
}
/// This function is used to generate a list of signals that the signal_handler should listen for
#[cfg(target_os = "windows")]
pub fn get_allowed_signals() -> Result<DummySignal, std::io::Error> {
Ok(DummySignal)
}
/// Dummy Signal Handler for windows
#[cfg(target_os = "windows")]
#[derive(Debug, Clone)]
pub struct DummySignal;
#[cfg(target_os = "windows")]
impl DummySignal {
/// Dummy handler for signals in windows (empty)
pub fn handle(&self) -> Self {
self.clone()
}
/// Hollow implementation, for windows compatibility
pub fn close(self) {}
}
| 519 | 2,026 |
hyperswitch | crates/common_utils/src/access_token.rs | .rs | //! Commonly used utilities for access token
use std::fmt::Display;
use crate::id_type;
/// Create a key for fetching the access token from redis
pub fn create_access_token_key(
merchant_id: &id_type::MerchantId,
merchant_connector_id_or_connector_name: impl Display,
) -> String {
merchant_id.get_access_token_key(merchant_connector_id_or_connector_name)
}
| 83 | 2,027 |
hyperswitch | crates/common_utils/src/encryption.rs | .rs | use diesel::{
backend::Backend,
deserialize::{self, FromSql, Queryable},
expression::AsExpression,
serialize::ToSql,
sql_types,
};
use masking::Secret;
use crate::{crypto::Encryptable, pii::EncryptionStrategy};
impl<DB> FromSql<sql_types::Binary, DB> for Encryption
where
DB: Backend,
Secret<Vec<u8>, EncryptionStrategy>: FromSql<sql_types::Binary, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
<Secret<Vec<u8>, EncryptionStrategy>>::from_sql(bytes).map(Self::new)
}
}
impl<DB> ToSql<sql_types::Binary, DB> for Encryption
where
DB: Backend,
Secret<Vec<u8>, EncryptionStrategy>: ToSql<sql_types::Binary, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.get_inner().to_sql(out)
}
}
impl<DB> Queryable<sql_types::Binary, DB> for Encryption
where
DB: Backend,
Secret<Vec<u8>, EncryptionStrategy>: FromSql<sql_types::Binary, DB>,
{
type Row = Secret<Vec<u8>, EncryptionStrategy>;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(Self { inner: row })
}
}
#[derive(Debug, AsExpression, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
#[diesel(sql_type = sql_types::Binary)]
#[repr(transparent)]
pub struct Encryption {
inner: Secret<Vec<u8>, EncryptionStrategy>,
}
impl<T: Clone> From<Encryptable<T>> for Encryption {
fn from(value: Encryptable<T>) -> Self {
Self::new(value.into_encrypted())
}
}
impl Encryption {
pub fn new(item: Secret<Vec<u8>, EncryptionStrategy>) -> Self {
Self { inner: item }
}
#[inline]
pub fn into_inner(self) -> Secret<Vec<u8>, EncryptionStrategy> {
self.inner
}
#[inline]
pub fn get_inner(&self) -> &Secret<Vec<u8>, EncryptionStrategy> {
&self.inner
}
}
| 495 | 2,028 |
hyperswitch | crates/common_utils/src/fp_utils.rs | .rs | //! Functional programming utilities
/// The Applicative trait provides a pure behavior,
/// which can be used to create values of type f a from values of type a.
pub trait Applicative<R> {
/// The Associative type acts as a (f a) wrapper for Self.
type WrappedSelf<T>;
/// Applicative::pure(_) is abstraction with lifts any arbitrary type to underlying higher
/// order type
fn pure(v: R) -> Self::WrappedSelf<R>;
}
impl<R> Applicative<R> for Option<R> {
type WrappedSelf<T> = Option<T>;
fn pure(v: R) -> Self::WrappedSelf<R> {
Some(v)
}
}
impl<R, E> Applicative<R> for Result<R, E> {
type WrappedSelf<T> = Result<T, E>;
fn pure(v: R) -> Self::WrappedSelf<R> {
Ok(v)
}
}
/// This function wraps the evaluated result of `f` into current context,
/// based on the condition provided into the `predicate`
pub fn when<W: Applicative<(), WrappedSelf<()> = W>, F>(predicate: bool, f: F) -> W
where
F: FnOnce() -> W,
{
if predicate {
f()
} else {
W::pure(())
}
}
| 279 | 2,029 |
hyperswitch | crates/common_utils/src/keymanager.rs | .rs | //! Consists of all the common functions to use the Keymanager.
use core::fmt::Debug;
use std::str::FromStr;
use base64::Engine;
use error_stack::ResultExt;
use http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode};
use masking::{PeekInterface, StrongSecret};
use once_cell::sync::OnceCell;
use router_env::{instrument, logger, tracing};
use crate::{
consts::{BASE64_ENGINE, TENANT_HEADER},
errors,
types::keymanager::{
BatchDecryptDataRequest, DataKeyCreateResponse, DecryptDataRequest,
EncryptionCreateRequest, EncryptionTransferRequest, GetKeymanagerTenant, KeyManagerState,
TransientBatchDecryptDataRequest, TransientDecryptDataRequest,
},
};
const CONTENT_TYPE: &str = "Content-Type";
static ENCRYPTION_API_CLIENT: OnceCell<reqwest::Client> = OnceCell::new();
static DEFAULT_ENCRYPTION_VERSION: &str = "v1";
#[cfg(feature = "km_forward_x_request_id")]
const X_REQUEST_ID: &str = "X-Request-Id";
/// Get keymanager client constructed from the url and state
#[instrument(skip_all)]
#[allow(unused_mut)]
fn get_api_encryption_client(
state: &KeyManagerState,
) -> errors::CustomResult<reqwest::Client, errors::KeyManagerClientError> {
let get_client = || {
let mut client = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.pool_idle_timeout(std::time::Duration::from_secs(
state.client_idle_timeout.unwrap_or_default(),
));
#[cfg(feature = "keymanager_mtls")]
{
let cert = state.cert.clone();
let ca = state.ca.clone();
let identity = reqwest::Identity::from_pem(cert.peek().as_ref())
.change_context(errors::KeyManagerClientError::ClientConstructionFailed)?;
let ca_cert = reqwest::Certificate::from_pem(ca.peek().as_ref())
.change_context(errors::KeyManagerClientError::ClientConstructionFailed)?;
client = client
.use_rustls_tls()
.identity(identity)
.add_root_certificate(ca_cert)
.https_only(true);
}
client
.build()
.change_context(errors::KeyManagerClientError::ClientConstructionFailed)
};
Ok(ENCRYPTION_API_CLIENT.get_or_try_init(get_client)?.clone())
}
/// Generic function to send the request to keymanager
#[instrument(skip_all)]
pub async fn send_encryption_request<T>(
state: &KeyManagerState,
headers: HeaderMap,
url: String,
method: Method,
request_body: T,
) -> errors::CustomResult<reqwest::Response, errors::KeyManagerClientError>
where
T: ConvertRaw,
{
let client = get_api_encryption_client(state)?;
let url = reqwest::Url::parse(&url)
.change_context(errors::KeyManagerClientError::UrlEncodingFailed)?;
client
.request(method, url)
.json(&ConvertRaw::convert_raw(request_body)?)
.headers(headers)
.send()
.await
.change_context(errors::KeyManagerClientError::RequestNotSent(
"Unable to send request to encryption service".to_string(),
))
}
/// Generic function to call the Keymanager and parse the response back
#[instrument(skip_all)]
pub async fn call_encryption_service<T, R>(
state: &KeyManagerState,
method: Method,
endpoint: &str,
request_body: T,
) -> errors::CustomResult<R, errors::KeyManagerClientError>
where
T: GetKeymanagerTenant + ConvertRaw + Send + Sync + 'static + Debug,
R: serde::de::DeserializeOwned,
{
let url = format!("{}/{endpoint}", &state.url);
logger::info!(key_manager_request=?request_body);
let mut header = vec![];
header.push((
HeaderName::from_str(CONTENT_TYPE)
.change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?,
HeaderValue::from_str("application/json")
.change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?,
));
#[cfg(feature = "km_forward_x_request_id")]
if let Some(request_id) = state.request_id {
header.push((
HeaderName::from_str(X_REQUEST_ID)
.change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?,
HeaderValue::from_str(request_id.as_hyphenated().to_string().as_str())
.change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?,
))
}
//Add Tenant ID
header.push((
HeaderName::from_str(TENANT_HEADER)
.change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?,
HeaderValue::from_str(request_body.get_tenant_id(state).get_string_repr())
.change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?,
));
let response = send_encryption_request(
state,
HeaderMap::from_iter(header.into_iter()),
url,
method,
request_body,
)
.await
.map_err(|err| err.change_context(errors::KeyManagerClientError::RequestSendFailed))?;
logger::info!(key_manager_response=?response);
match response.status() {
StatusCode::OK => response
.json::<R>()
.await
.change_context(errors::KeyManagerClientError::ResponseDecodingFailed),
StatusCode::INTERNAL_SERVER_ERROR => {
Err(errors::KeyManagerClientError::InternalServerError(
response
.bytes()
.await
.change_context(errors::KeyManagerClientError::ResponseDecodingFailed)?,
)
.into())
}
StatusCode::BAD_REQUEST => Err(errors::KeyManagerClientError::BadRequest(
response
.bytes()
.await
.change_context(errors::KeyManagerClientError::ResponseDecodingFailed)?,
)
.into()),
_ => Err(errors::KeyManagerClientError::Unexpected(
response
.bytes()
.await
.change_context(errors::KeyManagerClientError::ResponseDecodingFailed)?,
)
.into()),
}
}
/// Trait to convert the raw data to the required format for encryption service request
pub trait ConvertRaw {
/// Return type of the convert_raw function
type Output: serde::Serialize;
/// Function to convert the raw data to the required format for encryption service request
fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError>;
}
impl<T: serde::Serialize> ConvertRaw for T {
type Output = T;
fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> {
Ok(self)
}
}
impl ConvertRaw for TransientDecryptDataRequest {
type Output = DecryptDataRequest;
fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> {
let data = match String::from_utf8(self.data.peek().clone()) {
Ok(data) => data,
Err(_) => {
let data = BASE64_ENGINE.encode(self.data.peek().clone());
format!("{DEFAULT_ENCRYPTION_VERSION}:{data}")
}
};
Ok(DecryptDataRequest {
identifier: self.identifier,
data: StrongSecret::new(data),
})
}
}
impl ConvertRaw for TransientBatchDecryptDataRequest {
type Output = BatchDecryptDataRequest;
fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> {
let data = self
.data
.iter()
.map(|(k, v)| {
let value = match String::from_utf8(v.peek().clone()) {
Ok(data) => data,
Err(_) => {
let data = BASE64_ENGINE.encode(v.peek().clone());
format!("{DEFAULT_ENCRYPTION_VERSION}:{data}")
}
};
(k.to_owned(), StrongSecret::new(value))
})
.collect();
Ok(BatchDecryptDataRequest {
data,
identifier: self.identifier,
})
}
}
/// A function to create the key in keymanager
#[instrument(skip_all)]
pub async fn create_key_in_key_manager(
state: &KeyManagerState,
request_body: EncryptionCreateRequest,
) -> errors::CustomResult<DataKeyCreateResponse, errors::KeyManagerError> {
call_encryption_service(state, Method::POST, "key/create", request_body)
.await
.change_context(errors::KeyManagerError::KeyAddFailed)
}
/// A function to transfer the key in keymanager
#[instrument(skip_all)]
pub async fn transfer_key_to_key_manager(
state: &KeyManagerState,
request_body: EncryptionTransferRequest,
) -> errors::CustomResult<DataKeyCreateResponse, errors::KeyManagerError> {
call_encryption_service(state, Method::POST, "key/transfer", request_body)
.await
.change_context(errors::KeyManagerError::KeyTransferFailed)
}
| 1,940 | 2,030 |
hyperswitch | crates/common_utils/src/crypto.rs | .rs | //! Utilities for cryptographic algorithms
use std::ops::Deref;
use error_stack::ResultExt;
use masking::{ExposeInterface, Secret};
use md5;
use ring::{
aead::{self, BoundKey, OpeningKey, SealingKey, UnboundKey},
hmac,
};
use crate::{
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())
}
}
/// 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)
}
}
/// 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>>;
#[cfg(test)]
mod crypto_tests {
#![allow(clippy::expect_used)]
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);
}
}
| 7,189 | 2,031 |
hyperswitch | crates/common_utils/src/id_type.rs | .rs | //! Common ID types
//! The id type can be used to create specific id types with custom behaviour
mod api_key;
mod client_secret;
mod customer;
#[cfg(feature = "v2")]
mod global_id;
mod merchant;
mod merchant_connector_account;
mod organization;
mod payment;
mod profile;
mod refunds;
mod relay;
mod routing;
mod tenant;
use std::{borrow::Cow, fmt::Debug};
use diesel::{
backend::Backend,
deserialize::FromSql,
expression::AsExpression,
serialize::{Output, ToSql},
sql_types,
};
use serde::{Deserialize, Serialize};
use thiserror::Error;
#[cfg(feature = "v2")]
pub use self::global_id::{
customer::GlobalCustomerId,
payment::{GlobalAttemptId, GlobalPaymentId},
payment_methods::{GlobalPaymentMethodId, GlobalPaymentMethodSessionId},
refunds::GlobalRefundId,
CellId,
};
pub use self::{
api_key::ApiKeyId,
client_secret::ClientSecretId,
customer::CustomerId,
merchant::MerchantId,
merchant_connector_account::MerchantConnectorAccountId,
organization::OrganizationId,
payment::{PaymentId, PaymentReferenceId},
profile::ProfileId,
refunds::RefundReferenceId,
relay::RelayId,
routing::RoutingId,
tenant::TenantId,
};
use crate::{fp_utils::when, generate_id_with_default_len};
#[inline]
fn is_valid_id_character(input_char: char) -> bool {
input_char.is_ascii_alphanumeric() || matches!(input_char, '_' | '-')
}
/// This functions checks for the input string to contain valid characters
/// Returns Some(char) if there are any invalid characters, else None
fn get_invalid_input_character(input_string: Cow<'static, str>) -> Option<char> {
input_string
.trim()
.chars()
.find(|&char| !is_valid_id_character(char))
}
#[derive(Debug, PartialEq, Hash, Serialize, Clone, Eq)]
/// A type for alphanumeric ids
pub(crate) struct AlphaNumericId(String);
#[derive(Debug, Deserialize, Hash, Serialize, Error, Eq, PartialEq)]
#[error("value `{0}` contains invalid character `{1}`")]
/// The error type for alphanumeric id
pub(crate) struct AlphaNumericIdError(String, char);
impl<'de> Deserialize<'de> for AlphaNumericId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let deserialized_string = String::deserialize(deserializer)?;
Self::from(deserialized_string.into()).map_err(serde::de::Error::custom)
}
}
impl AlphaNumericId {
/// Creates a new alphanumeric id from string by applying validation checks
pub fn from(input_string: Cow<'static, str>) -> Result<Self, AlphaNumericIdError> {
let invalid_character = get_invalid_input_character(input_string.clone());
if let Some(invalid_character) = invalid_character {
Err(AlphaNumericIdError(
input_string.to_string(),
invalid_character,
))?
}
Ok(Self(input_string.to_string()))
}
/// Create a new alphanumeric id without any validations
pub(crate) fn new_unchecked(input_string: String) -> Self {
Self(input_string)
}
/// Generate a new alphanumeric id of default length
pub(crate) fn new(prefix: &str) -> Self {
Self(generate_id_with_default_len(prefix))
}
}
/// A common type of id that can be used for reference ids with length constraint
#[derive(Debug, Clone, Serialize, Hash, PartialEq, Eq, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub(crate) struct LengthId<const MAX_LENGTH: u8, const MIN_LENGTH: u8>(AlphaNumericId);
/// Error generated from violation of constraints for MerchantReferenceId
#[derive(Debug, Error, PartialEq, Eq)]
pub(crate) enum LengthIdError {
#[error("the maximum allowed length for this field is {0}")]
/// Maximum length of string violated
MaxLengthViolated(u8),
#[error("the minimum required length for this field is {0}")]
/// Minimum length of string violated
MinLengthViolated(u8),
#[error("{0}")]
/// Input contains invalid characters
AlphanumericIdError(AlphaNumericIdError),
}
impl From<AlphaNumericIdError> for LengthIdError {
fn from(alphanumeric_id_error: AlphaNumericIdError) -> Self {
Self::AlphanumericIdError(alphanumeric_id_error)
}
}
impl<const MAX_LENGTH: u8, const MIN_LENGTH: u8> LengthId<MAX_LENGTH, MIN_LENGTH> {
/// Generates new [MerchantReferenceId] from the given input string
pub fn from(input_string: Cow<'static, str>) -> Result<Self, LengthIdError> {
let trimmed_input_string = input_string.trim().to_string();
let length_of_input_string = u8::try_from(trimmed_input_string.len())
.map_err(|_| LengthIdError::MaxLengthViolated(MAX_LENGTH))?;
when(length_of_input_string > MAX_LENGTH, || {
Err(LengthIdError::MaxLengthViolated(MAX_LENGTH))
})?;
when(length_of_input_string < MIN_LENGTH, || {
Err(LengthIdError::MinLengthViolated(MIN_LENGTH))
})?;
let alphanumeric_id = match AlphaNumericId::from(trimmed_input_string.into()) {
Ok(valid_alphanumeric_id) => valid_alphanumeric_id,
Err(error) => Err(LengthIdError::AlphanumericIdError(error))?,
};
Ok(Self(alphanumeric_id))
}
/// Generate a new MerchantRefId of default length with the given prefix
pub fn new(prefix: &str) -> Self {
Self(AlphaNumericId::new(prefix))
}
/// Use this function only if you are sure that the length is within the range
pub(crate) fn new_unchecked(alphanumeric_id: AlphaNumericId) -> Self {
Self(alphanumeric_id)
}
#[cfg(feature = "v2")]
/// Create a new LengthId from aplhanumeric id
pub(crate) fn from_alphanumeric_id(
alphanumeric_id: AlphaNumericId,
) -> Result<Self, LengthIdError> {
let length_of_input_string = alphanumeric_id.0.len();
let length_of_input_string = u8::try_from(length_of_input_string)
.map_err(|_| LengthIdError::MaxLengthViolated(MAX_LENGTH))?;
when(length_of_input_string > MAX_LENGTH, || {
Err(LengthIdError::MaxLengthViolated(MAX_LENGTH))
})?;
when(length_of_input_string < MIN_LENGTH, || {
Err(LengthIdError::MinLengthViolated(MIN_LENGTH))
})?;
Ok(Self(alphanumeric_id))
}
}
impl<'de, const MAX_LENGTH: u8, const MIN_LENGTH: u8> Deserialize<'de>
for LengthId<MAX_LENGTH, MIN_LENGTH>
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let deserialized_string = String::deserialize(deserializer)?;
Self::from(deserialized_string.into()).map_err(serde::de::Error::custom)
}
}
impl<DB, const MAX_LENGTH: u8, const MIN_LENGTH: u8> ToSql<sql_types::Text, DB>
for LengthId<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 .0.to_sql(out)
}
}
impl<DB, const MAX_LENGTH: u8, const MIN_LENGTH: u8> FromSql<sql_types::Text, DB>
for LengthId<MAX_LENGTH, MIN_LENGTH>
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
let string_val = String::from_sql(value)?;
Ok(Self(AlphaNumericId::new_unchecked(string_val)))
}
}
/// An interface to generate object identifiers.
pub trait GenerateId {
/// Generates a random object identifier.
fn generate() -> Self;
}
#[cfg(test)]
mod alphanumeric_id_tests {
#![allow(clippy::unwrap_used)]
use super::*;
const VALID_UNDERSCORE_ID_JSON: &str = r#""cus_abcdefghijklmnopqrstuv""#;
const EXPECTED_VALID_UNDERSCORE_ID: &str = "cus_abcdefghijklmnopqrstuv";
const VALID_HYPHEN_ID_JSON: &str = r#""cus-abcdefghijklmnopqrstuv""#;
const VALID_HYPHEN_ID_STRING: &str = "cus-abcdefghijklmnopqrstuv";
const INVALID_ID_WITH_SPACES: &str = r#""cus abcdefghijklmnopqrstuv""#;
const INVALID_ID_WITH_EMOJIS: &str = r#""cus_abc🦀""#;
#[test]
fn test_id_deserialize_underscore() {
let parsed_alphanumeric_id =
serde_json::from_str::<AlphaNumericId>(VALID_UNDERSCORE_ID_JSON);
let alphanumeric_id = AlphaNumericId::from(EXPECTED_VALID_UNDERSCORE_ID.into()).unwrap();
assert_eq!(parsed_alphanumeric_id.unwrap(), alphanumeric_id);
}
#[test]
fn test_id_deserialize_hyphen() {
let parsed_alphanumeric_id = serde_json::from_str::<AlphaNumericId>(VALID_HYPHEN_ID_JSON);
let alphanumeric_id = AlphaNumericId::from(VALID_HYPHEN_ID_STRING.into()).unwrap();
assert_eq!(parsed_alphanumeric_id.unwrap(), alphanumeric_id);
}
#[test]
fn test_id_deserialize_with_spaces() {
let parsed_alphanumeric_id = serde_json::from_str::<AlphaNumericId>(INVALID_ID_WITH_SPACES);
assert!(parsed_alphanumeric_id.is_err());
}
#[test]
fn test_id_deserialize_with_emojis() {
let parsed_alphanumeric_id = serde_json::from_str::<AlphaNumericId>(INVALID_ID_WITH_EMOJIS);
assert!(parsed_alphanumeric_id.is_err());
}
}
#[cfg(test)]
mod merchant_reference_id_tests {
use super::*;
const VALID_REF_ID_JSON: &str = r#""cus_abcdefghijklmnopqrstuv""#;
const MAX_LENGTH: u8 = 36;
const MIN_LENGTH: u8 = 6;
const INVALID_REF_ID_JSON: &str = r#""cus abcdefghijklmnopqrstuv""#;
const INVALID_REF_ID_LENGTH: &str = r#""cus_abcdefghijklmnopqrstuvwxyzabcdefghij""#;
#[test]
fn test_valid_reference_id() {
let parsed_merchant_reference_id =
serde_json::from_str::<LengthId<MAX_LENGTH, MIN_LENGTH>>(VALID_REF_ID_JSON);
dbg!(&parsed_merchant_reference_id);
assert!(parsed_merchant_reference_id.is_ok());
}
#[test]
fn test_invalid_ref_id() {
let parsed_merchant_reference_id =
serde_json::from_str::<LengthId<MAX_LENGTH, MIN_LENGTH>>(INVALID_REF_ID_JSON);
assert!(parsed_merchant_reference_id.is_err());
}
#[test]
fn test_invalid_ref_id_error_message() {
let parsed_merchant_reference_id =
serde_json::from_str::<LengthId<MAX_LENGTH, MIN_LENGTH>>(INVALID_REF_ID_JSON);
let expected_error_message =
r#"value `cus abcdefghijklmnopqrstuv` contains invalid character ` `"#.to_string();
let error_message = parsed_merchant_reference_id
.err()
.map(|error| error.to_string());
assert_eq!(error_message, Some(expected_error_message));
}
#[test]
fn test_invalid_ref_id_length() {
let parsed_merchant_reference_id =
serde_json::from_str::<LengthId<MAX_LENGTH, MIN_LENGTH>>(INVALID_REF_ID_LENGTH);
dbg!(&parsed_merchant_reference_id);
let expected_error_message =
format!("the maximum allowed length for this field is {MAX_LENGTH}");
assert!(parsed_merchant_reference_id
.is_err_and(|error_string| error_string.to_string().eq(&expected_error_message)));
}
#[test]
fn test_invalid_ref_id_length_error_type() {
let parsed_merchant_reference_id =
LengthId::<MAX_LENGTH, MIN_LENGTH>::from(INVALID_REF_ID_LENGTH.into());
dbg!(&parsed_merchant_reference_id);
assert!(
parsed_merchant_reference_id.is_err_and(|error_type| matches!(
error_type,
LengthIdError::MaxLengthViolated(MAX_LENGTH)
))
);
}
}
| 2,718 | 2,032 |
hyperswitch | crates/common_utils/src/request.rs | .rs | use masking::{Maskable, Secret};
use serde::{Deserialize, Serialize};
pub type Headers = std::collections::HashSet<(String, Maskable<String>)>;
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize, strum::Display, strum::EnumString,
)]
#[serde(rename_all = "UPPERCASE")]
#[strum(serialize_all = "UPPERCASE")]
pub enum Method {
Get,
Post,
Put,
Delete,
Patch,
}
#[derive(Deserialize, Serialize, Debug)]
pub enum ContentType {
Json,
FormUrlEncoded,
FormData,
Xml,
}
fn default_request_headers() -> [(String, Maskable<String>); 1] {
use http::header;
[(header::VIA.to_string(), "HyperSwitch".to_string().into())]
}
#[derive(Debug)]
pub struct Request {
pub url: String,
pub headers: Headers,
pub method: Method,
pub certificate: Option<Secret<String>>,
pub certificate_key: Option<Secret<String>>,
pub body: Option<RequestContent>,
}
impl std::fmt::Debug for RequestContent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Json(_) => "JsonRequestBody",
Self::FormUrlEncoded(_) => "FormUrlEncodedRequestBody",
Self::FormData(_) => "FormDataRequestBody",
Self::Xml(_) => "XmlRequestBody",
Self::RawBytes(_) => "RawBytesRequestBody",
})
}
}
pub enum RequestContent {
Json(Box<dyn masking::ErasedMaskSerialize + Send>),
FormUrlEncoded(Box<dyn masking::ErasedMaskSerialize + Send>),
FormData(reqwest::multipart::Form),
Xml(Box<dyn masking::ErasedMaskSerialize + Send>),
RawBytes(Vec<u8>),
}
impl RequestContent {
pub fn get_inner_value(&self) -> Secret<String> {
match self {
Self::Json(i) => serde_json::to_string(&i).unwrap_or_default().into(),
Self::FormUrlEncoded(i) => serde_urlencoded::to_string(i).unwrap_or_default().into(),
Self::Xml(i) => quick_xml::se::to_string(&i).unwrap_or_default().into(),
Self::FormData(_) => String::new().into(),
Self::RawBytes(_) => String::new().into(),
}
}
}
impl Request {
pub fn new(method: Method, url: &str) -> Self {
Self {
method,
url: String::from(url),
headers: std::collections::HashSet::new(),
certificate: None,
certificate_key: None,
body: None,
}
}
pub fn set_body<T: Into<RequestContent>>(&mut self, body: T) {
self.body.replace(body.into());
}
pub fn add_default_headers(&mut self) {
self.headers.extend(default_request_headers());
}
pub fn add_header(&mut self, header: &str, value: Maskable<String>) {
self.headers.insert((String::from(header), value));
}
pub fn add_certificate(&mut self, certificate: Option<Secret<String>>) {
self.certificate = certificate;
}
pub fn add_certificate_key(&mut self, certificate_key: Option<Secret<String>>) {
self.certificate = certificate_key;
}
}
#[derive(Debug)]
pub struct RequestBuilder {
pub url: String,
pub headers: Headers,
pub method: Method,
pub certificate: Option<Secret<String>>,
pub certificate_key: Option<Secret<String>>,
pub body: Option<RequestContent>,
}
impl RequestBuilder {
pub fn new() -> Self {
Self {
method: Method::Get,
url: String::with_capacity(1024),
headers: std::collections::HashSet::new(),
certificate: None,
certificate_key: None,
body: None,
}
}
pub fn url(mut self, url: &str) -> Self {
self.url = url.into();
self
}
pub fn method(mut self, method: Method) -> Self {
self.method = method;
self
}
pub fn attach_default_headers(mut self) -> Self {
self.headers.extend(default_request_headers());
self
}
pub fn header(mut self, header: &str, value: &str) -> Self {
self.headers.insert((header.into(), value.into()));
self
}
pub fn headers(mut self, headers: Vec<(String, Maskable<String>)>) -> Self {
self.headers.extend(headers);
self
}
pub fn set_optional_body<T: Into<RequestContent>>(mut self, body: Option<T>) -> Self {
body.map(|body| self.body.replace(body.into()));
self
}
pub fn set_body<T: Into<RequestContent>>(mut self, body: T) -> Self {
self.body.replace(body.into());
self
}
pub fn add_certificate(mut self, certificate: Option<Secret<String>>) -> Self {
self.certificate = certificate;
self
}
pub fn add_certificate_key(mut self, certificate_key: Option<Secret<String>>) -> Self {
self.certificate_key = certificate_key;
self
}
pub fn build(self) -> Request {
Request {
method: self.method,
url: self.url,
headers: self.headers,
certificate: self.certificate,
certificate_key: self.certificate_key,
body: self.body,
}
}
}
impl Default for RequestBuilder {
fn default() -> Self {
Self::new()
}
}
| 1,210 | 2,033 |
hyperswitch | crates/common_utils/src/ext_traits.rs | .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>();
format!("Unable to parse {variable_type} from bytes {self:?}")
})
}
}
/// 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(|| format!("Unable to parse {type_name} from &[u8] {:?}", &self))
}
}
/// 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,
{
let debug = format!(
"Unable to parse {type_name} from serde_json::Value: {:?}",
&self
);
serde_json::from_value::<T>(self)
.change_context(errors::ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| debug)
}
}
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 {:?}", &self)
})
}
}
/// 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;
}
#[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
}
}
}
}
#[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,
}
}
}
/// 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)
}
}
}
| 4,735 | 2,034 |
hyperswitch | crates/common_utils/src/transformers.rs | .rs | //! Utilities for converting between foreign types
/// Trait for converting from one foreign type to another
pub trait ForeignFrom<F> {
/// Convert from a foreign type to the current type
fn foreign_from(from: F) -> Self;
}
/// Trait for converting from one foreign type to another
pub trait ForeignTryFrom<F>: Sized {
/// Custom error for conversion failure
type Error;
/// Convert from a foreign type to the current type and return an error if the conversion fails
fn foreign_try_from(from: F) -> Result<Self, Self::Error>;
}
| 120 | 2,035 |
hyperswitch | crates/common_utils/src/link_utils.rs | .rs | //! This module has common utilities for links in HyperSwitch
use std::{collections::HashSet, primitive::i64};
use common_enums::{enums, UIWidgetFormLayout};
use diesel::{
backend::Backend,
deserialize,
deserialize::FromSql,
serialize::{Output, ToSql},
sql_types::Jsonb,
AsExpression, FromSqlRow,
};
use error_stack::{report, ResultExt};
use masking::Secret;
use regex::Regex;
#[cfg(feature = "logs")]
use router_env::logger;
use serde::Serialize;
use utoipa::ToSchema;
use crate::{consts, errors::ParsingError, id_type, types::MinorUnit};
#[derive(
Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq, FromSqlRow, AsExpression, ToSchema,
)]
#[serde(rename_all = "snake_case", tag = "type", content = "value")]
#[diesel(sql_type = Jsonb)]
/// Link status enum
pub enum GenericLinkStatus {
/// Status variants for payment method collect link
PaymentMethodCollect(PaymentMethodCollectStatus),
/// Status variants for payout link
PayoutLink(PayoutLinkStatus),
}
impl Default for GenericLinkStatus {
fn default() -> Self {
Self::PaymentMethodCollect(PaymentMethodCollectStatus::Initiated)
}
}
crate::impl_to_sql_from_sql_json!(GenericLinkStatus);
#[derive(
Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq, FromSqlRow, AsExpression, ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[diesel(sql_type = Jsonb)]
/// Status variants for payment method collect links
pub enum PaymentMethodCollectStatus {
/// Link was initialized
Initiated,
/// Link was expired or invalidated
Invalidated,
/// Payment method details were submitted
Submitted,
}
impl<DB: Backend> FromSql<Jsonb, DB> for PaymentMethodCollectStatus
where
serde_json::Value: FromSql<Jsonb, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let value = <serde_json::Value as FromSql<Jsonb, DB>>::from_sql(bytes)?;
let generic_status: GenericLinkStatus = serde_json::from_value(value)?;
match generic_status {
GenericLinkStatus::PaymentMethodCollect(status) => Ok(status),
GenericLinkStatus::PayoutLink(_) => Err(report!(ParsingError::EnumParseFailure(
"PaymentMethodCollectStatus"
)))
.attach_printable("Invalid status for PaymentMethodCollect")?,
}
}
}
impl ToSql<Jsonb, diesel::pg::Pg> for PaymentMethodCollectStatus
where
serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>,
{
// This wraps PaymentMethodCollectStatus with GenericLinkStatus
// Required for storing the status in required format in DB (GenericLinkStatus)
// This type is used in PaymentMethodCollectLink (a variant of GenericLink, used in the application for avoiding conversion of data and status)
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, diesel::pg::Pg>) -> diesel::serialize::Result {
let value = serde_json::to_value(GenericLinkStatus::PaymentMethodCollect(self.clone()))?;
// 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 ToSql<Jsonb, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow())
}
}
#[derive(
Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq, FromSqlRow, AsExpression, ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[diesel(sql_type = Jsonb)]
/// Status variants for payout links
pub enum PayoutLinkStatus {
/// Link was initialized
Initiated,
/// Link was expired or invalidated
Invalidated,
/// Payout details were submitted
Submitted,
}
impl<DB: Backend> FromSql<Jsonb, DB> for PayoutLinkStatus
where
serde_json::Value: FromSql<Jsonb, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let value = <serde_json::Value as FromSql<Jsonb, DB>>::from_sql(bytes)?;
let generic_status: GenericLinkStatus = serde_json::from_value(value)?;
match generic_status {
GenericLinkStatus::PayoutLink(status) => Ok(status),
GenericLinkStatus::PaymentMethodCollect(_) => {
Err(report!(ParsingError::EnumParseFailure("PayoutLinkStatus")))
.attach_printable("Invalid status for PayoutLink")?
}
}
}
}
impl ToSql<Jsonb, diesel::pg::Pg> for PayoutLinkStatus
where
serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>,
{
// This wraps PayoutLinkStatus with GenericLinkStatus
// Required for storing the status in required format in DB (GenericLinkStatus)
// This type is used in PayoutLink (a variant of GenericLink, used in the application for avoiding conversion of data and status)
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, diesel::pg::Pg>) -> diesel::serialize::Result {
let value = serde_json::to_value(GenericLinkStatus::PayoutLink(self.clone()))?;
// 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 ToSql<Jsonb, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow())
}
}
#[derive(Serialize, serde::Deserialize, Debug, Clone, FromSqlRow, AsExpression, ToSchema)]
#[diesel(sql_type = Jsonb)]
/// Payout link object
pub struct PayoutLinkData {
/// Identifier for the payout link
pub payout_link_id: String,
/// Identifier for the customer
pub customer_id: id_type::CustomerId,
/// Identifier for the payouts resource
pub payout_id: String,
/// Link to render the payout link
pub link: url::Url,
/// Client secret generated for authenticating frontend APIs
pub client_secret: Secret<String>,
/// Expiry in seconds from the time it was created
pub session_expiry: u32,
#[serde(flatten)]
/// Payout link's UI configurations
pub ui_config: GenericLinkUiConfig,
/// List of enabled payment methods
pub enabled_payment_methods: Option<Vec<EnabledPaymentMethod>>,
/// Payout amount
pub amount: MinorUnit,
/// Payout currency
pub currency: enums::Currency,
/// A list of allowed domains (glob patterns) where this link can be embedded / opened from
pub allowed_domains: HashSet<String>,
/// Form layout of the payout link
pub form_layout: Option<UIWidgetFormLayout>,
/// `test_mode` can be used for testing payout links without any restrictions
pub test_mode: Option<bool>,
}
crate::impl_to_sql_from_sql_json!(PayoutLinkData);
/// Object for GenericLinkUiConfig
#[derive(Clone, Debug, serde::Deserialize, Serialize, ToSchema)]
pub struct GenericLinkUiConfig {
/// Merchant's display logo
#[schema(value_type = Option<String>, max_length = 255, example = "https://hyperswitch.io/favicon.ico")]
pub logo: Option<url::Url>,
/// Custom merchant name for the link
#[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch")]
pub merchant_name: Option<Secret<String>>,
/// Primary color to be used in the form represented in hex format
#[schema(value_type = Option<String>, max_length = 255, example = "#4285F4")]
pub theme: Option<String>,
}
/// Object for GenericLinkUiConfigFormData
#[derive(Clone, Debug, serde::Deserialize, Serialize, ToSchema)]
pub struct GenericLinkUiConfigFormData {
/// Merchant's display logo
#[schema(value_type = String, max_length = 255, example = "https://hyperswitch.io/favicon.ico")]
pub logo: url::Url,
/// Custom merchant name for the link
#[schema(value_type = String, max_length = 255, example = "Hyperswitch")]
pub merchant_name: Secret<String>,
/// Primary color to be used in the form represented in hex format
#[schema(value_type = String, max_length = 255, example = "#4285F4")]
pub theme: String,
}
/// Object for EnabledPaymentMethod
#[derive(Clone, Debug, Serialize, serde::Deserialize, ToSchema)]
pub struct EnabledPaymentMethod {
/// Payment method (banks, cards, wallets) enabled for the operation
#[schema(value_type = PaymentMethod)]
pub payment_method: enums::PaymentMethod,
/// An array of associated payment method types
#[schema(value_type = HashSet<PaymentMethodType>)]
pub payment_method_types: HashSet<enums::PaymentMethodType>,
}
/// Util function for validating a domain without any wildcard characters.
pub fn validate_strict_domain(domain: &str) -> bool {
Regex::new(consts::STRICT_DOMAIN_REGEX)
.map(|regex| regex.is_match(domain))
.map_err(|err| {
let err_msg = format!("Invalid strict domain regex: {err:?}");
#[cfg(feature = "logs")]
logger::error!(err_msg);
err_msg
})
.unwrap_or(false)
}
/// Util function for validating a domain with "*" wildcard characters.
pub fn validate_wildcard_domain(domain: &str) -> bool {
Regex::new(consts::WILDCARD_DOMAIN_REGEX)
.map(|regex| regex.is_match(domain))
.map_err(|err| {
let err_msg = format!("Invalid strict domain regex: {err:?}");
#[cfg(feature = "logs")]
logger::error!(err_msg);
err_msg
})
.unwrap_or(false)
}
#[cfg(test)]
mod domain_tests {
use regex::Regex;
use super::*;
#[test]
fn test_validate_strict_domain_regex() {
assert!(
Regex::new(consts::STRICT_DOMAIN_REGEX).is_ok(),
"Strict domain regex is invalid"
);
}
#[test]
fn test_validate_wildcard_domain_regex() {
assert!(
Regex::new(consts::WILDCARD_DOMAIN_REGEX).is_ok(),
"Wildcard domain regex is invalid"
);
}
#[test]
fn test_validate_strict_domain() {
let valid_domains = vec![
"example.com",
"example.subdomain.com",
"https://example.com:8080",
"http://example.com",
"example.com:8080",
"example.com:443",
"localhost:443",
"127.0.0.1:443",
];
for domain in valid_domains {
assert!(
validate_strict_domain(domain),
"Could not validate strict domain: {}",
domain
);
}
let invalid_domains = vec![
"",
"invalid.domain.",
"not_a_domain",
"http://example.com/path?query=1#fragment",
"127.0.0.1.2:443",
];
for domain in invalid_domains {
assert!(
!validate_strict_domain(domain),
"Could not validate invalid strict domain: {}",
domain
);
}
}
#[test]
fn test_validate_wildcard_domain() {
let valid_domains = vec![
"example.com",
"example.subdomain.com",
"https://example.com:8080",
"http://example.com",
"example.com:8080",
"example.com:443",
"localhost:443",
"127.0.0.1:443",
"*.com",
"example.*.com",
"example.com:*",
"*:443",
"localhost:*",
"127.0.0.*:*",
"*:*",
];
for domain in valid_domains {
assert!(
validate_wildcard_domain(domain),
"Could not validate wildcard domain: {}",
domain
);
}
let invalid_domains = vec![
"",
"invalid.domain.",
"not_a_domain",
"http://example.com/path?query=1#fragment",
"*.",
".*",
"example.com:*:",
"*:443:",
":localhost:*",
"127.00.*:*",
];
for domain in invalid_domains {
assert!(
!validate_wildcard_domain(domain),
"Could not validate invalid wildcard domain: {}",
domain
);
}
}
}
| 2,899 | 2,036 |
hyperswitch | crates/common_utils/src/pii.rs | .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:?}"));
}
}
| 3,611 | 2,037 |
hyperswitch | crates/common_utils/src/new_type.rs | .rs | //! Contains new types with restrictions
use masking::{ExposeInterface, PeekInterface, Secret};
use crate::{
consts::MAX_ALLOWED_MERCHANT_NAME_LENGTH,
pii::{Email, UpiVpaMaskingStrategy},
transformers::ForeignFrom,
};
#[nutype::nutype(
derive(Clone, Serialize, Deserialize, Debug),
validate(len_char_min = 1, len_char_max = MAX_ALLOWED_MERCHANT_NAME_LENGTH)
)]
pub struct MerchantName(String);
impl masking::SerializableSecret for MerchantName {}
/// Function for masking alphanumeric characters in a string.
///
/// # Arguments
/// `val`
/// - holds reference to the string to be masked.
/// `unmasked_char_count`
/// - minimum character count to remain unmasked for identification
/// - this number is for keeping the characters unmasked from
/// both beginning (if feasible) and ending of the string.
/// `min_masked_char_count`
/// - this ensures the minimum number of characters to be masked
///
/// # Behaviour
/// - Returns the original string if its length is less than or equal to `unmasked_char_count`.
/// - If the string length allows, keeps `unmasked_char_count` characters unmasked at both start and end.
/// - Otherwise, keeps `unmasked_char_count` characters unmasked only at the end.
/// - Only alphanumeric characters are masked; other characters remain unchanged.
///
/// # Examples
/// Sort Code
/// (12-34-56, 2, 2) -> 12-**-56
/// Routing number
/// (026009593, 3, 3) -> 026***593
/// CNPJ
/// (12345678901, 4, 4) -> *******8901
/// CNPJ
/// (12345678901, 4, 3) -> 1234***8901
/// Pix key
/// (123e-a452-1243-1244-000, 4, 4) -> 123e-****-****-****-000
/// IBAN
/// (AL35202111090000000001234567, 5, 5) -> AL352******************34567
fn apply_mask(val: &str, unmasked_char_count: usize, min_masked_char_count: usize) -> String {
let len = val.len();
if len <= unmasked_char_count {
return val.to_string();
}
let mask_start_index =
// For showing only last `unmasked_char_count` characters
if len < (unmasked_char_count * 2 + min_masked_char_count) {
0
// For showing first and last `unmasked_char_count` characters
} else {
unmasked_char_count
};
let mask_end_index = len - unmasked_char_count - 1;
let range = mask_start_index..=mask_end_index;
val.chars()
.enumerate()
.fold(String::new(), |mut acc, (index, ch)| {
if ch.is_alphanumeric() && range.contains(&index) {
acc.push('*');
} else {
acc.push(ch);
}
acc
})
}
/// Masked sort code
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaskedSortCode(Secret<String>);
impl From<String> for MaskedSortCode {
fn from(src: String) -> Self {
let masked_value = apply_mask(src.as_ref(), 2, 2);
Self(Secret::from(masked_value))
}
}
impl From<Secret<String>> for MaskedSortCode {
fn from(secret: Secret<String>) -> Self {
Self::from(secret.expose())
}
}
/// Masked Routing number
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaskedRoutingNumber(Secret<String>);
impl From<String> for MaskedRoutingNumber {
fn from(src: String) -> Self {
let masked_value = apply_mask(src.as_ref(), 3, 3);
Self(Secret::from(masked_value))
}
}
impl From<Secret<String>> for MaskedRoutingNumber {
fn from(secret: Secret<String>) -> Self {
Self::from(secret.expose())
}
}
/// Masked bank account
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaskedBankAccount(Secret<String>);
impl From<String> for MaskedBankAccount {
fn from(src: String) -> Self {
let masked_value = apply_mask(src.as_ref(), 4, 4);
Self(Secret::from(masked_value))
}
}
impl From<Secret<String>> for MaskedBankAccount {
fn from(secret: Secret<String>) -> Self {
Self::from(secret.expose())
}
}
/// Masked IBAN
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaskedIban(Secret<String>);
impl From<String> for MaskedIban {
fn from(src: String) -> Self {
let masked_value = apply_mask(src.as_ref(), 5, 5);
Self(Secret::from(masked_value))
}
}
impl From<Secret<String>> for MaskedIban {
fn from(secret: Secret<String>) -> Self {
Self::from(secret.expose())
}
}
/// Masked IBAN
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaskedBic(Secret<String>);
impl From<String> for MaskedBic {
fn from(src: String) -> Self {
let masked_value = apply_mask(src.as_ref(), 3, 2);
Self(Secret::from(masked_value))
}
}
impl From<Secret<String>> for MaskedBic {
fn from(secret: Secret<String>) -> Self {
Self::from(secret.expose())
}
}
/// Masked UPI ID
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaskedUpiVpaId(Secret<String>);
impl From<String> for MaskedUpiVpaId {
fn from(src: String) -> Self {
let unmasked_char_count = 2;
let masked_value = if let Some((user_identifier, bank_or_psp)) = src.split_once('@') {
let masked_user_identifier = user_identifier
.to_string()
.chars()
.take(unmasked_char_count)
.collect::<String>()
+ &"*".repeat(user_identifier.len() - unmasked_char_count);
format!("{}@{}", masked_user_identifier, bank_or_psp)
} else {
let masked_value = apply_mask(src.as_ref(), unmasked_char_count, 8);
masked_value
};
Self(Secret::from(masked_value))
}
}
impl From<Secret<String, UpiVpaMaskingStrategy>> for MaskedUpiVpaId {
fn from(secret: Secret<String, UpiVpaMaskingStrategy>) -> Self {
Self::from(secret.expose())
}
}
/// Masked Email
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaskedEmail(Secret<String>);
impl From<String> for MaskedEmail {
fn from(src: String) -> Self {
let unmasked_char_count = 2;
let masked_value = if let Some((user_identifier, domain)) = src.split_once('@') {
let masked_user_identifier = user_identifier
.to_string()
.chars()
.take(unmasked_char_count)
.collect::<String>()
+ &"*".repeat(user_identifier.len() - unmasked_char_count);
format!("{}@{}", masked_user_identifier, domain)
} else {
let masked_value = apply_mask(src.as_ref(), unmasked_char_count, 8);
masked_value
};
Self(Secret::from(masked_value))
}
}
impl From<Secret<String>> for MaskedEmail {
fn from(secret: Secret<String>) -> Self {
Self::from(secret.expose())
}
}
impl ForeignFrom<Email> for MaskedEmail {
fn foreign_from(email: Email) -> Self {
let email_value: String = email.expose().peek().to_owned();
Self::from(email_value)
}
}
/// Masked Phone Number
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaskedPhoneNumber(Secret<String>);
impl From<String> for MaskedPhoneNumber {
fn from(src: String) -> Self {
let unmasked_char_count = 2;
let masked_value = if unmasked_char_count <= src.len() {
let len = src.len();
// mask every character except the last 2
"*".repeat(len - unmasked_char_count).to_string()
+ src
.get(len.saturating_sub(unmasked_char_count)..)
.unwrap_or("")
} else {
src
};
Self(Secret::from(masked_value))
}
}
impl From<Secret<String>> for MaskedPhoneNumber {
fn from(secret: Secret<String>) -> Self {
Self::from(secret.expose())
}
}
#[cfg(test)]
mod apply_mask_fn_test {
use masking::PeekInterface;
use crate::new_type::{
apply_mask, MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode,
MaskedUpiVpaId,
};
#[test]
fn test_masked_types() {
let sort_code = MaskedSortCode::from("110011".to_string());
let routing_number = MaskedRoutingNumber::from("056008849".to_string());
let bank_account = MaskedBankAccount::from("12345678901234".to_string());
let iban = MaskedIban::from("NL02ABNA0123456789".to_string());
let upi_vpa = MaskedUpiVpaId::from("someusername@okhdfcbank".to_string());
// Standard masked data tests
assert_eq!(sort_code.0.peek().to_owned(), "11**11".to_string());
assert_eq!(routing_number.0.peek().to_owned(), "056***849".to_string());
assert_eq!(
bank_account.0.peek().to_owned(),
"1234******1234".to_string()
);
assert_eq!(iban.0.peek().to_owned(), "NL02A********56789".to_string());
assert_eq!(
upi_vpa.0.peek().to_owned(),
"so**********@okhdfcbank".to_string()
);
}
#[test]
fn test_apply_mask_fn() {
let value = "12345678901".to_string();
// Generic masked tests
assert_eq!(apply_mask(&value, 2, 2), "12*******01".to_string());
assert_eq!(apply_mask(&value, 3, 2), "123*****901".to_string());
assert_eq!(apply_mask(&value, 3, 3), "123*****901".to_string());
assert_eq!(apply_mask(&value, 4, 3), "1234***8901".to_string());
assert_eq!(apply_mask(&value, 4, 4), "*******8901".to_string());
assert_eq!(apply_mask(&value, 5, 4), "******78901".to_string());
assert_eq!(apply_mask(&value, 5, 5), "******78901".to_string());
assert_eq!(apply_mask(&value, 6, 5), "*****678901".to_string());
assert_eq!(apply_mask(&value, 6, 6), "*****678901".to_string());
assert_eq!(apply_mask(&value, 7, 6), "****5678901".to_string());
assert_eq!(apply_mask(&value, 7, 7), "****5678901".to_string());
assert_eq!(apply_mask(&value, 8, 7), "***45678901".to_string());
assert_eq!(apply_mask(&value, 8, 8), "***45678901".to_string());
}
}
| 2,802 | 2,038 |
hyperswitch | crates/common_utils/src/consts.rs | .rs | //! Commonly used constants
/// Number of characters in a generated ID
pub const ID_LENGTH: usize = 20;
/// Characters to use for generating NanoID
pub(crate) const ALPHABETS: [char; 62] = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z',
];
/// TTL for token
pub const TOKEN_TTL: i64 = 900;
///an example of the frm_configs json
pub static FRM_CONFIGS_EG: &str = r#"
[{"gateway":"stripe","payment_methods":[{"payment_method":"card","payment_method_types":[{"payment_method_type":"credit","card_networks":["Visa"],"flow":"pre","action":"cancel_txn"},{"payment_method_type":"debit","card_networks":["Visa"],"flow":"pre"}]}]}]
"#;
/// Maximum limit for payments list get api
pub const PAYMENTS_LIST_MAX_LIMIT_V1: u32 = 100;
/// Maximum limit for payments list post api with filters
pub const PAYMENTS_LIST_MAX_LIMIT_V2: u32 = 50;
/// Default limit for payments list API
pub fn default_payments_list_limit() -> u32 {
10
}
/// Average delay (in seconds) between account onboarding's API response and the changes to actually reflect at Stripe's end
pub const STRIPE_ACCOUNT_ONBOARDING_DELAY_IN_SECONDS: i64 = 15;
/// Maximum limit for payment link list get api
pub const PAYMENTS_LINK_LIST_LIMIT: u32 = 100;
/// Maximum limit for payouts list get api
pub const PAYOUTS_LIST_MAX_LIMIT_GET: u32 = 100;
/// Maximum limit for payouts list post api
pub const PAYOUTS_LIST_MAX_LIMIT_POST: u32 = 20;
/// Default limit for payouts list API
pub fn default_payouts_list_limit() -> u32 {
10
}
/// surcharge percentage maximum precision length
pub const SURCHARGE_PERCENTAGE_PRECISION_LENGTH: u8 = 2;
/// Header Key for application overhead of a request
pub const X_HS_LATENCY: &str = "x-hs-latency";
/// Redirect url for Prophetpay
pub const PROPHETPAY_REDIRECT_URL: &str = "https://ccm-thirdparty.cps.golf/hp/tokenize/";
/// Variable which store the card token for Prophetpay
pub const PROPHETPAY_TOKEN: &str = "cctoken";
/// Payment intent default client secret expiry (in seconds)
pub const DEFAULT_SESSION_EXPIRY: i64 = 15 * 60;
/// Payment intent fulfillment time (in seconds)
pub const DEFAULT_INTENT_FULFILLMENT_TIME: i64 = 15 * 60;
/// Payment order fulfillment time (in seconds)
pub const DEFAULT_ORDER_FULFILLMENT_TIME: i64 = 15 * 60;
/// Default ttl for Extended card info in redis (in seconds)
pub const DEFAULT_TTL_FOR_EXTENDED_CARD_INFO: u16 = 15 * 60;
/// Max ttl for Extended card info in redis (in seconds)
pub const MAX_TTL_FOR_EXTENDED_CARD_INFO: u16 = 60 * 60 * 2;
/// Default tenant to be used when multitenancy is disabled
pub const DEFAULT_TENANT: &str = "public";
/// Default tenant to be used when multitenancy is disabled
pub const TENANT_HEADER: &str = "x-tenant-id";
/// Max Length for MerchantReferenceId
pub const MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 64;
/// Maximum length allowed for a global id
pub const MIN_GLOBAL_ID_LENGTH: u8 = 32;
/// Minimum length required for a global id
pub const MAX_GLOBAL_ID_LENGTH: u8 = 64;
/// Minimum allowed length for MerchantReferenceId
pub const MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 1;
/// Length of a cell identifier in a distributed system
pub const CELL_IDENTIFIER_LENGTH: u8 = 5;
/// General purpose base64 engine
pub const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
/// URL Safe base64 engine
pub const BASE64_ENGINE_URL_SAFE: base64::engine::GeneralPurpose =
base64::engine::general_purpose::URL_SAFE;
/// Regex for matching a domain
/// Eg -
/// http://www.example.com
/// https://www.example.com
/// www.example.com
/// example.io
pub const STRICT_DOMAIN_REGEX: &str = r"^(https?://)?(([A-Za-z0-9][-A-Za-z0-9]\.)*[A-Za-z0-9][-A-Za-z0-9]*|(\d{1,3}\.){3}\d{1,3})+(:[0-9]{2,4})?$";
/// Regex for matching a wildcard domain
/// Eg -
/// *.example.com
/// *.subdomain.domain.com
/// *://example.com
/// *example.com
pub const WILDCARD_DOMAIN_REGEX: &str = r"^((\*|https?)?://)?((\*\.|[A-Za-z0-9][-A-Za-z0-9]*\.)*[A-Za-z0-9][-A-Za-z0-9]*|((\d{1,3}|\*)\.){3}(\d{1,3}|\*)|\*)(:\*|:[0-9]{2,4})?(/\*)?$";
/// Maximum allowed length for MerchantName
pub const MAX_ALLOWED_MERCHANT_NAME_LENGTH: usize = 64;
/// Default locale
pub const DEFAULT_LOCALE: &str = "en";
/// Role ID for Tenant Admin
pub const ROLE_ID_TENANT_ADMIN: &str = "tenant_admin";
/// Role ID for Org Admin
pub const ROLE_ID_ORGANIZATION_ADMIN: &str = "org_admin";
/// Role ID for Internal View Only
pub const ROLE_ID_INTERNAL_VIEW_ONLY_USER: &str = "internal_view_only";
/// Role ID for Internal Admin
pub const ROLE_ID_INTERNAL_ADMIN: &str = "internal_admin";
/// Max length allowed for Description
pub const MAX_DESCRIPTION_LENGTH: u16 = 255;
/// Max length allowed for Statement Descriptor
pub const MAX_STATEMENT_DESCRIPTOR_LENGTH: u16 = 22;
/// Payout flow identifier used for performing GSM operations
pub const PAYOUT_FLOW_STR: &str = "payout_flow";
/// length of the publishable key
pub const PUBLISHABLE_KEY_LENGTH: u16 = 39;
/// The number of bytes allocated for the hashed connector transaction ID.
/// Total number of characters equals CONNECTOR_TRANSACTION_ID_HASH_BYTES times 2.
pub const CONNECTOR_TRANSACTION_ID_HASH_BYTES: usize = 25;
/// Apple Pay validation url
pub const APPLEPAY_VALIDATION_URL: &str =
"https://apple-pay-gateway-cert.apple.com/paymentservices/startSession";
/// Request ID
pub const X_REQUEST_ID: &str = "x-request-id";
/// Default Tenant ID for the `Global` tenant
pub const DEFAULT_GLOBAL_TENANT_ID: &str = "global";
/// Default status of Card IP Blocking
pub const DEFAULT_CARD_IP_BLOCKING_STATUS: bool = false;
/// Default Threshold for Card IP Blocking
pub const DEFAULT_CARD_IP_BLOCKING_THRESHOLD: i32 = 3;
/// Default status of Guest User Card Blocking
pub const DEFAULT_GUEST_USER_CARD_BLOCKING_STATUS: bool = false;
/// Default Threshold for Card Blocking for Guest Users
pub const DEFAULT_GUEST_USER_CARD_BLOCKING_THRESHOLD: i32 = 10;
/// Default status of Customer ID Blocking
pub const DEFAULT_CUSTOMER_ID_BLOCKING_STATUS: bool = false;
/// Default Threshold for Customer ID Blocking
pub const DEFAULT_CUSTOMER_ID_BLOCKING_THRESHOLD: i32 = 5;
/// Default Card Testing Guard Redis Expiry in seconds
pub const DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS: i32 = 3600;
/// SOAP 1.1 Envelope Namespace
pub const SOAP_ENV_NAMESPACE: &str = "http://schemas.xmlsoap.org/soap/envelope/";
| 1,928 | 2,039 |
hyperswitch | crates/common_utils/src/types.rs | .rs | //! Types that can be used in other crates
pub mod keymanager;
/// Enum for Authentication Level
pub mod authentication;
/// Enum for Theme Lineage
pub mod theme;
/// types that are wrappers around primitive types
pub mod primitive_wrappers;
use std::{
borrow::Cow,
fmt::Display,
iter::Sum,
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,
};
/// 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 {} decimal digits",
precision
)
}
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,
)]
#[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)
}
/// 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 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, serde::Serialize, Clone, PartialEq)]
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))
}
}
/// 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()
}
}
#[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))
}
}
#[cfg(feature = "v2")]
pub use client_secret_type::ClientSecret;
#[cfg(feature = "v2")]
mod client_secret_type {
use std::fmt;
use masking::PeekInterface;
use router_env::logger;
use super::*;
use crate::id_type;
/// A domain type that can be used to represent a client secret
/// Client secret is generated for a payment and is used to authenticate the client side api calls
#[derive(Debug, PartialEq, Clone, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub struct ClientSecret {
/// The payment id of the payment
pub payment_id: id_type::GlobalPaymentId,
/// The secret string
pub secret: masking::Secret<String>,
}
impl ClientSecret {
pub(crate) fn get_string_repr(&self) -> String {
format!(
"{}_secret_{}",
self.payment_id.get_string_repr(),
self.secret.peek()
)
}
/// Create a new client secret
pub(crate) fn new(payment_id: id_type::GlobalPaymentId, secret: String) -> Self {
Self {
payment_id,
secret: masking::Secret::new(secret),
}
}
}
impl FromStr for ClientSecret {
type Err = ParsingError;
fn from_str(str_value: &str) -> Result<Self, Self::Err> {
let (payment_id, secret) =
str_value
.rsplit_once("_secret_")
.ok_or(ParsingError::EncodeError(
"Expected a string in the format '{payment_id}_secret_{secret}'",
))?;
let payment_id = id_type::GlobalPaymentId::try_from(Cow::Owned(payment_id.to_owned()))
.map_err(|err| {
logger::error!(global_payment_id_error=?err);
ParsingError::EncodeError("Error while constructing GlobalPaymentId")
})?;
Ok(Self {
payment_id,
secret: masking::Secret::new(secret.to_owned()),
})
}
}
impl<'de> Deserialize<'de> for ClientSecret {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct ClientSecretVisitor;
impl Visitor<'_> for ClientSecretVisitor {
type Value = ClientSecret;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a string in the format '{payment_id}_secret_{secret}'")
}
fn visit_str<E>(self, value: &str) -> Result<ClientSecret, E>
where
E: serde::de::Error,
{
let (payment_id, secret) = value.rsplit_once("_secret_").ok_or_else(|| {
E::invalid_value(
serde::de::Unexpected::Str(value),
&"a string with '_secret_'",
)
})?;
let payment_id =
id_type::GlobalPaymentId::try_from(Cow::Owned(payment_id.to_owned()))
.map_err(serde::de::Error::custom)?;
Ok(ClientSecret {
payment_id,
secret: masking::Secret::new(secret.to_owned()),
})
}
}
deserializer.deserialize_str(ClientSecretVisitor)
}
}
impl Serialize for ClientSecret {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
serializer.serialize_str(self.get_string_repr().as_str())
}
}
impl ToSql<sql_types::Text, diesel::pg::Pg> for ClientSecret
where
String: ToSql<sql_types::Text, diesel::pg::Pg>,
{
fn to_sql<'b>(
&'b self,
out: &mut Output<'b, '_, diesel::pg::Pg>,
) -> diesel::serialize::Result {
let string_repr = self.get_string_repr();
<String as ToSql<sql_types::Text, diesel::pg::Pg>>::to_sql(
&string_repr,
&mut out.reborrow(),
)
}
}
impl<DB> FromSql<sql_types::Text, DB> for ClientSecret
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> {
let string_repr = String::from_sql(value)?;
let (payment_id, secret) =
string_repr
.rsplit_once("_secret_")
.ok_or(ParsingError::EncodeError(
"Expected a string in the format '{payment_id}_secret_{secret}'",
))?;
let payment_id = id_type::GlobalPaymentId::try_from(Cow::Owned(payment_id.to_owned()))
.map_err(|err| {
logger::error!(global_payment_id_error=?err);
ParsingError::EncodeError("Error while constructing GlobalPaymentId")
})?;
Ok(Self {
payment_id,
secret: masking::Secret::new(secret.to_owned()),
})
}
}
impl<DB> Queryable<sql_types::Text, DB> for ClientSecret
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
crate::impl_serializable_secret_id_type!(ClientSecret);
#[cfg(test)]
mod client_secret_tests {
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
use serde_json;
use super::*;
use crate::id_type::GlobalPaymentId;
#[test]
fn test_serialize_client_secret() {
let global_payment_id = "12345_pay_1a961ed9093c48b09781bf8ab17ba6bd";
let secret = "fc34taHLw1ekPgNh92qr".to_string();
let expected_client_secret_string = format!("\"{global_payment_id}_secret_{secret}\"");
let client_secret1 = ClientSecret {
payment_id: GlobalPaymentId::try_from(Cow::Borrowed(global_payment_id)).unwrap(),
secret: masking::Secret::new(secret),
};
let parsed_client_secret =
serde_json::to_string(&client_secret1).expect("Failed to serialize client_secret1");
assert_eq!(expected_client_secret_string, parsed_client_secret);
}
#[test]
fn test_deserialize_client_secret() {
// This is a valid global id
let global_payment_id_str = "12345_pay_1a961ed9093c48b09781bf8ab17ba6bd";
let secret = "fc34taHLw1ekPgNh92qr".to_string();
let valid_payment_global_id =
GlobalPaymentId::try_from(Cow::Borrowed(global_payment_id_str))
.expect("Failed to create valid global payment id");
// This is an invalid global id because of the cell id being in invalid length
let invalid_global_payment_id = "123_pay_1a961ed9093c48b09781bf8ab17ba6bd";
// Create a client secret string which is valid
let valid_client_secret = format!(r#""{global_payment_id_str}_secret_{secret}""#);
dbg!(&valid_client_secret);
// Create a client secret string which is invalid
let invalid_client_secret_because_of_invalid_payment_id =
format!(r#""{invalid_global_payment_id}_secret_{secret}""#);
// Create a client secret string which is invalid because of invalid secret
let invalid_client_secret_because_of_invalid_secret =
format!(r#""{invalid_global_payment_id}""#);
let valid_client_secret = serde_json::from_str::<ClientSecret>(&valid_client_secret)
.expect("Failed to deserialize client_secret_str1");
let invalid_deser1 = serde_json::from_str::<ClientSecret>(
&invalid_client_secret_because_of_invalid_payment_id,
);
dbg!(&invalid_deser1);
let invalid_deser2 = serde_json::from_str::<ClientSecret>(
&invalid_client_secret_because_of_invalid_secret,
);
dbg!(&invalid_deser2);
assert_eq!(valid_client_secret.payment_id, valid_payment_global_id);
assert_eq!(valid_client_secret.secret.peek(), &secret);
assert_eq!(
invalid_deser1.err().unwrap().to_string(),
"Incorrect value provided for field: payment_id at line 1 column 70"
);
assert_eq!(
invalid_deser2.err().unwrap().to_string(),
"invalid value: string \"123_pay_1a961ed9093c48b09781bf8ab17ba6bd\", expected a string with '_secret_' at line 1 column 42"
);
}
}
}
/// 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 {
#![allow(clippy::unwrap_used)]
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>,
}
#[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 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)
}
}
| 12,357 | 2,040 |
hyperswitch | crates/common_utils/src/payout_method_utils.rs | .rs | //! This module has common utilities for payout method data in HyperSwitch
use common_enums;
use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow};
use masking::Secret;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::new_type::{
MaskedBankAccount, MaskedBic, MaskedEmail, MaskedIban, MaskedPhoneNumber, MaskedRoutingNumber,
MaskedSortCode,
};
/// Masked payout method details for storing in db
#[derive(
Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub enum AdditionalPayoutMethodData {
/// Additional data for card payout method
Card(Box<CardAdditionalData>),
/// Additional data for bank payout method
Bank(Box<BankAdditionalData>),
/// Additional data for wallet payout method
Wallet(Box<WalletAdditionalData>),
}
crate::impl_to_sql_from_sql_json!(AdditionalPayoutMethodData);
/// Masked payout method details for card payout method
#[derive(
Eq, PartialEq, Clone, Debug, Serialize, Deserialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct CardAdditionalData {
/// Issuer of the card
pub card_issuer: Option<String>,
/// Card network of the card
#[schema(value_type = Option<CardNetwork>)]
pub card_network: Option<common_enums::CardNetwork>,
/// Card type, can be either `credit` or `debit`
pub card_type: Option<String>,
/// Card issuing country
pub card_issuing_country: Option<String>,
/// Code for Card issuing bank
pub bank_code: Option<String>,
/// Last 4 digits of the card number
pub last4: Option<String>,
/// The ISIN of the card
pub card_isin: Option<String>,
/// Extended bin of card, contains the first 8 digits of card number
pub card_extended_bin: Option<String>,
/// Card expiry month
#[schema(value_type = String, example = "01")]
pub card_exp_month: Option<Secret<String>>,
/// Card expiry year
#[schema(value_type = String, example = "2026")]
pub card_exp_year: Option<Secret<String>>,
/// Card holder name
#[schema(value_type = String, example = "John Doe")]
pub card_holder_name: Option<Secret<String>>,
}
/// Masked payout method details for bank payout method
#[derive(
Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(untagged)]
pub enum BankAdditionalData {
/// Additional data for ach bank transfer payout method
Ach(Box<AchBankTransferAdditionalData>),
/// Additional data for bacs bank transfer payout method
Bacs(Box<BacsBankTransferAdditionalData>),
/// Additional data for sepa bank transfer payout method
Sepa(Box<SepaBankTransferAdditionalData>),
/// Additional data for pix bank transfer payout method
Pix(Box<PixBankTransferAdditionalData>),
}
/// Masked payout method details for ach bank transfer payout method
#[derive(
Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct AchBankTransferAdditionalData {
/// Partially masked account number for ach bank debit payment
#[schema(value_type = String, example = "0001****3456")]
pub bank_account_number: MaskedBankAccount,
/// Partially masked routing number for ach bank debit payment
#[schema(value_type = String, example = "110***000")]
pub bank_routing_number: MaskedRoutingNumber,
/// Name of the bank
#[schema(value_type = Option<BankNames>, example = "Deutsche Bank")]
pub bank_name: Option<String>,
/// Bank country code
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub bank_country_code: Option<common_enums::CountryAlpha2>,
/// Bank city
#[schema(value_type = Option<String>, example = "California")]
pub bank_city: Option<String>,
}
/// Masked payout method details for bacs bank transfer payout method
#[derive(
Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct BacsBankTransferAdditionalData {
/// Partially masked sort code for Bacs payment method
#[schema(value_type = String, example = "108800")]
pub bank_sort_code: MaskedSortCode,
/// Bank account's owner name
#[schema(value_type = String, example = "0001****3456")]
pub bank_account_number: MaskedBankAccount,
/// 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<common_enums::CountryAlpha2>,
/// Bank city
#[schema(value_type = Option<String>, example = "California")]
pub bank_city: Option<String>,
}
/// Masked payout method details for sepa bank transfer payout method
#[derive(
Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct SepaBankTransferAdditionalData {
/// Partially masked international bank account number (iban) for SEPA
#[schema(value_type = String, example = "DE8937******013000")]
pub iban: MaskedIban,
/// 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<common_enums::CountryAlpha2>,
/// Bank city
#[schema(value_type = Option<String>, example = "California")]
pub bank_city: Option<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 = Option<String>, example = "HSBCGB2LXXX")]
pub bic: Option<MaskedBic>,
}
/// Masked payout method details for pix bank transfer payout method
#[derive(
Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct PixBankTransferAdditionalData {
/// Partially masked unique key for pix transfer
#[schema(value_type = String, example = "a1f4102e ****** 6fa48899c1d1")]
pub pix_key: MaskedBankAccount,
/// Partially masked CPF - CPF is a Brazilian tax identification number
#[schema(value_type = Option<String>, example = "**** 124689")]
pub tax_id: Option<MaskedBankAccount>,
/// Bank account number is an unique identifier assigned by a bank to a customer.
#[schema(value_type = String, example = "**** 23456")]
pub bank_account_number: MaskedBankAccount,
/// 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>,
}
/// Masked payout method details for wallet payout method
#[derive(
Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(untagged)]
pub enum WalletAdditionalData {
/// Additional data for paypal wallet payout method
Paypal(Box<PaypalAdditionalData>),
/// Additional data for venmo wallet payout method
Venmo(Box<VenmoAdditionalData>),
}
/// Masked payout method details for paypal wallet payout method
#[derive(
Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct PaypalAdditionalData {
/// Email linked with paypal account
#[schema(value_type = Option<String>, example = "john.doe@example.com")]
pub email: Option<MaskedEmail>,
/// mobile number linked to paypal account
#[schema(value_type = Option<String>, example = "******* 3349")]
pub telephone_number: Option<MaskedPhoneNumber>,
/// id of the paypal account
#[schema(value_type = Option<String>, example = "G83K ***** HCQ2")]
pub paypal_id: Option<MaskedBankAccount>,
}
/// Masked payout method details for venmo wallet payout method
#[derive(
Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct VenmoAdditionalData {
/// mobile number linked to venmo account
#[schema(value_type = Option<String>, example = "******* 3349")]
pub telephone_number: Option<MaskedPhoneNumber>,
}
| 2,104 | 2,041 |
hyperswitch | crates/common_utils/src/lib.rs | .rs | #![warn(missing_docs, missing_debug_implementations)]
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))]
use masking::{PeekInterface, Secret};
pub mod access_token;
pub mod consts;
pub mod crypto;
pub mod custom_serde;
#[allow(missing_docs)] // Todo: add docs
pub mod encryption;
pub mod errors;
#[allow(missing_docs)] // Todo: add docs
pub mod events;
pub mod ext_traits;
pub mod fp_utils;
pub mod id_type;
#[cfg(feature = "keymanager")]
pub mod keymanager;
pub mod link_utils;
pub mod macros;
pub mod new_type;
pub mod payout_method_utils;
pub mod pii;
#[allow(missing_docs)] // Todo: add docs
pub mod request;
#[cfg(feature = "signals")]
pub mod signals;
pub mod transformers;
pub mod types;
pub mod validation;
/// Used for hashing
pub mod hashing;
#[cfg(feature = "metrics")]
pub mod metrics;
pub use base64_serializer::Base64Serializer;
/// Date-time utilities.
pub mod date_time {
#[cfg(feature = "async_ext")]
use std::time::Instant;
use std::{marker::PhantomData, num::NonZeroU8};
use masking::{Deserialize, Serialize};
use time::{
format_description::{
well_known::iso8601::{Config, EncodedConfig, Iso8601, TimePrecision},
BorrowedFormatItem,
},
OffsetDateTime, PrimitiveDateTime,
};
/// Enum to represent date formats
#[derive(Debug)]
pub enum DateFormat {
/// Format the date in 20191105081132 format
YYYYMMDDHHmmss,
/// Format the date in 20191105 format
YYYYMMDD,
/// Format the date in 201911050811 format
YYYYMMDDHHmm,
/// Format the date in 05112019081132 format
DDMMYYYYHHmmss,
}
/// Create a new [`PrimitiveDateTime`] with the current date and time in UTC.
pub fn now() -> PrimitiveDateTime {
let utc_date_time = OffsetDateTime::now_utc();
PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())
}
/// Convert from OffsetDateTime to PrimitiveDateTime
pub fn convert_to_pdt(offset_time: OffsetDateTime) -> PrimitiveDateTime {
PrimitiveDateTime::new(offset_time.date(), offset_time.time())
}
/// Return the UNIX timestamp of the current date and time in UTC
pub fn now_unix_timestamp() -> i64 {
OffsetDateTime::now_utc().unix_timestamp()
}
/// Calculate execution time for a async block in milliseconds
#[cfg(feature = "async_ext")]
pub async fn time_it<T, Fut: futures::Future<Output = T>, F: FnOnce() -> Fut>(
block: F,
) -> (T, f64) {
let start = Instant::now();
let result = block().await;
(result, start.elapsed().as_secs_f64() * 1000f64)
}
/// Return the given date and time in UTC with the given format Eg: format: YYYYMMDDHHmmss Eg: 20191105081132
pub fn format_date(
date: PrimitiveDateTime,
format: DateFormat,
) -> Result<String, time::error::Format> {
let format = <&[BorrowedFormatItem<'_>]>::from(format);
date.format(&format)
}
/// Return the current date and time in UTC with the format [year]-[month]-[day]T[hour]:[minute]:[second].mmmZ Eg: 2023-02-15T13:33:18.898Z
pub fn date_as_yyyymmddthhmmssmmmz() -> Result<String, time::error::Format> {
const ISO_CONFIG: EncodedConfig = Config::DEFAULT
.set_time_precision(TimePrecision::Second {
decimal_digits: NonZeroU8::new(3),
})
.encode();
now().assume_utc().format(&Iso8601::<ISO_CONFIG>)
}
impl From<DateFormat> for &[BorrowedFormatItem<'_>] {
fn from(format: DateFormat) -> Self {
match format {
DateFormat::YYYYMMDDHHmmss => time::macros::format_description!("[year repr:full][month padding:zero repr:numerical][day padding:zero][hour padding:zero repr:24][minute padding:zero][second padding:zero]"),
DateFormat::YYYYMMDD => time::macros::format_description!("[year repr:full][month padding:zero repr:numerical][day padding:zero]"),
DateFormat::YYYYMMDDHHmm => time::macros::format_description!("[year repr:full][month padding:zero repr:numerical][day padding:zero][hour padding:zero repr:24][minute padding:zero]"),
DateFormat::DDMMYYYYHHmmss => time::macros::format_description!("[day padding:zero][month padding:zero repr:numerical][year repr:full][hour padding:zero repr:24][minute padding:zero][second padding:zero]"),
}
}
}
/// Format the date in 05112019 format
#[derive(Debug, Clone)]
pub struct DDMMYYYY;
/// Format the date in 20191105 format
#[derive(Debug, Clone)]
pub struct YYYYMMDD;
/// Format the date in 20191105081132 format
#[derive(Debug, Clone)]
pub struct YYYYMMDDHHmmss;
/// To serialize the date in Dateformats like YYYYMMDDHHmmss, YYYYMMDD, DDMMYYYY
#[derive(Debug, Deserialize, Clone)]
pub struct DateTime<T: TimeStrategy> {
inner: PhantomData<T>,
value: PrimitiveDateTime,
}
impl<T: TimeStrategy> From<PrimitiveDateTime> for DateTime<T> {
fn from(value: PrimitiveDateTime) -> Self {
Self {
inner: PhantomData,
value,
}
}
}
/// Time strategy for the Date, Eg: YYYYMMDDHHmmss, YYYYMMDD, DDMMYYYY
pub trait TimeStrategy {
/// Stringify the date as per the Time strategy
fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
}
impl<T: TimeStrategy> Serialize for DateTime<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.collect_str(self)
}
}
impl<T: TimeStrategy> std::fmt::Display for DateTime<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
T::fmt(&self.value, f)
}
}
impl TimeStrategy for DDMMYYYY {
fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let year = input.year();
#[allow(clippy::as_conversions)]
let month = input.month() as u8;
let day = input.day();
let output = format!("{day:02}{month:02}{year}");
f.write_str(&output)
}
}
impl TimeStrategy for YYYYMMDD {
fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let year = input.year();
#[allow(clippy::as_conversions)]
let month: u8 = input.month() as u8;
let day = input.day();
let output = format!("{year}{month:02}{day:02}");
f.write_str(&output)
}
}
impl TimeStrategy for YYYYMMDDHHmmss {
fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let year = input.year();
#[allow(clippy::as_conversions)]
let month = input.month() as u8;
let day = input.day();
let hour = input.hour();
let minute = input.minute();
let second = input.second();
let output = format!("{year}{month:02}{day:02}{hour:02}{minute:02}{second:02}");
f.write_str(&output)
}
}
}
/// Generate a nanoid with the given prefix and length
#[inline]
pub fn generate_id(length: usize, prefix: &str) -> String {
format!("{}_{}", prefix, nanoid::nanoid!(length, &consts::ALPHABETS))
}
/// Generate a ReferenceId with the default length with the given prefix
fn generate_ref_id_with_default_length<const MAX_LENGTH: u8, const MIN_LENGTH: u8>(
prefix: &str,
) -> id_type::LengthId<MAX_LENGTH, MIN_LENGTH> {
id_type::LengthId::<MAX_LENGTH, MIN_LENGTH>::new(prefix)
}
/// Generate a customer id with default length, with prefix as `cus`
pub fn generate_customer_id_of_default_length() -> id_type::CustomerId {
use id_type::GenerateId;
id_type::CustomerId::generate()
}
/// Generate a organization id with default length, with prefix as `org`
pub fn generate_organization_id_of_default_length() -> id_type::OrganizationId {
use id_type::GenerateId;
id_type::OrganizationId::generate()
}
/// Generate a profile id with default length, with prefix as `pro`
pub fn generate_profile_id_of_default_length() -> id_type::ProfileId {
use id_type::GenerateId;
id_type::ProfileId::generate()
}
/// Generate a routing id with default length, with prefix as `routing`
pub fn generate_routing_id_of_default_length() -> id_type::RoutingId {
use id_type::GenerateId;
id_type::RoutingId::generate()
}
/// Generate a merchant_connector_account id with default length, with prefix as `mca`
pub fn generate_merchant_connector_account_id_of_default_length(
) -> id_type::MerchantConnectorAccountId {
use id_type::GenerateId;
id_type::MerchantConnectorAccountId::generate()
}
/// Generate a nanoid with the given prefix and a default length
#[inline]
pub fn generate_id_with_default_len(prefix: &str) -> String {
let len: usize = consts::ID_LENGTH;
format!("{}_{}", prefix, nanoid::nanoid!(len, &consts::ALPHABETS))
}
/// Generate a time-ordered (time-sortable) unique identifier using the current time
#[inline]
pub fn generate_time_ordered_id(prefix: &str) -> String {
format!("{prefix}_{}", uuid::Uuid::now_v7().as_simple())
}
/// Generate a time-ordered (time-sortable) unique identifier using the current time without prefix
#[inline]
pub fn generate_time_ordered_id_without_prefix() -> String {
uuid::Uuid::now_v7().as_simple().to_string()
}
/// Generate a nanoid with the specified length
#[inline]
pub fn generate_id_with_len(length: usize) -> String {
nanoid::nanoid!(length, &consts::ALPHABETS)
}
#[allow(missing_docs)]
pub trait DbConnectionParams {
fn get_username(&self) -> &str;
fn get_password(&self) -> Secret<String>;
fn get_host(&self) -> &str;
fn get_port(&self) -> u16;
fn get_dbname(&self) -> &str;
fn get_database_url(&self, schema: &str) -> String {
format!(
"postgres://{}:{}@{}:{}/{}?application_name={}&options=-c search_path%3D{}",
self.get_username(),
self.get_password().peek(),
self.get_host(),
self.get_port(),
self.get_dbname(),
schema,
schema,
)
}
}
// Can't add doc comments for macro invocations, neither does the macro allow it.
#[allow(missing_docs)]
mod base64_serializer {
use base64_serde::base64_serde_type;
base64_serde_type!(pub Base64Serializer, crate::consts::BASE64_ENGINE);
}
#[cfg(test)]
mod nanoid_tests {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::{
consts::{
MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH, MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH,
},
id_type::AlphaNumericId,
};
#[test]
fn test_generate_id_with_alphanumeric_id() {
let alphanumeric_id = AlphaNumericId::from(generate_id(10, "def").into());
assert!(alphanumeric_id.is_ok())
}
#[test]
fn test_generate_merchant_ref_id_with_default_length() {
let ref_id = id_type::LengthId::<
MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH,
MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH,
>::from(generate_id_with_default_len("def").into());
assert!(ref_id.is_ok())
}
}
| 2,919 | 2,042 |
hyperswitch | crates/common_utils/src/errors.rs | .rs | //! Errors and error specific types for universal use
use crate::types::MinorUnit;
/// Custom Result
/// A custom datatype that wraps the error variant <E> into a report, allowing
/// error_stack::Report<E> specific extendability
///
/// Effectively, equivalent to `Result<T, error_stack::Report<E>>`
pub type CustomResult<T, E> = error_stack::Result<T, E>;
/// Parsing Errors
#[allow(missing_docs)] // Only to prevent warnings about struct fields not being documented
#[derive(Debug, thiserror::Error)]
pub enum ParsingError {
///Failed to parse enum
#[error("Failed to parse enum: {0}")]
EnumParseFailure(&'static str),
///Failed to parse struct
#[error("Failed to parse struct: {0}")]
StructParseFailure(&'static str),
/// Failed to encode data to given format
#[error("Failed to serialize to {0} format")]
EncodeError(&'static str),
/// Failed to parse data
#[error("Unknown error while parsing")]
UnknownError,
/// Failed to parse datetime
#[error("Failed to parse datetime")]
DateTimeParsingError,
/// Failed to parse email
#[error("Failed to parse email")]
EmailParsingError,
/// Failed to parse phone number
#[error("Failed to parse phone number")]
PhoneNumberParsingError,
/// Failed to parse Float value for converting to decimal points
#[error("Failed to parse Float value for converting to decimal points")]
FloatToDecimalConversionFailure,
/// Failed to parse Decimal value for i64 value conversion
#[error("Failed to parse Decimal value for i64 value conversion")]
DecimalToI64ConversionFailure,
/// Failed to parse string value for f64 value conversion
#[error("Failed to parse string value for f64 value conversion")]
StringToFloatConversionFailure,
/// Failed to parse i64 value for f64 value conversion
#[error("Failed to parse i64 value for f64 value conversion")]
I64ToDecimalConversionFailure,
/// Failed to parse String value to Decimal value conversion because `error`
#[error("Failed to parse String value to Decimal value conversion because {error}")]
StringToDecimalConversionFailure { error: String },
/// Failed to convert the given integer because of integer overflow error
#[error("Integer Overflow error")]
IntegerOverflow,
}
/// Validation errors.
#[allow(missing_docs)] // Only to prevent warnings about struct fields not being documented
#[derive(Debug, thiserror::Error, Clone, PartialEq)]
pub enum ValidationError {
/// The provided input is missing a required field.
#[error("Missing required field: {field_name}")]
MissingRequiredField { field_name: String },
/// An incorrect value was provided for the field specified by `field_name`.
#[error("Incorrect value provided for field: {field_name}")]
IncorrectValueProvided { field_name: &'static str },
/// An invalid input was provided.
#[error("{message}")]
InvalidValue { message: String },
}
/// Integrity check errors.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct IntegrityCheckError {
/// Field names for which integrity check failed!
pub field_names: String,
/// Connector transaction reference id
pub connector_transaction_id: Option<String>,
}
/// Cryptographic algorithm errors
#[derive(Debug, thiserror::Error)]
pub enum CryptoError {
/// The cryptographic algorithm was unable to encode the message
#[error("Failed to encode given message")]
EncodingFailed,
/// The cryptographic algorithm was unable to decode the message
#[error("Failed to decode given message")]
DecodingFailed,
/// The cryptographic algorithm was unable to sign the message
#[error("Failed to sign message")]
MessageSigningFailed,
/// The cryptographic algorithm was unable to verify the given signature
#[error("Failed to verify signature")]
SignatureVerificationFailed,
/// The provided key length is invalid for the cryptographic algorithm
#[error("Invalid key length")]
InvalidKeyLength,
/// The provided IV length is invalid for the cryptographic algorithm
#[error("Invalid IV length")]
InvalidIvLength,
}
/// Errors for Qr code handling
#[derive(Debug, thiserror::Error)]
pub enum QrCodeError {
/// Failed to encode data into Qr code
#[error("Failed to create Qr code")]
FailedToCreateQrCode,
/// Failed to parse hex color
#[error("Invalid hex color code supplied")]
InvalidHexColor,
}
/// Api Models construction error
#[derive(Debug, Clone, thiserror::Error, PartialEq)]
pub enum PercentageError {
/// Percentage Value provided was invalid
#[error("Invalid Percentage value")]
InvalidPercentageValue,
/// Error occurred while calculating percentage
#[error("Failed apply percentage of {percentage} on {amount}")]
UnableToApplyPercentage {
/// percentage value
percentage: f32,
/// amount value
amount: MinorUnit,
},
}
/// Allows [error_stack::Report] to change between error contexts
/// using the dependent [ErrorSwitch] trait to define relations & mappings between traits
pub trait ReportSwitchExt<T, U> {
/// Switch to the intended report by calling switch
/// requires error switch to be already implemented on the error type
fn switch(self) -> Result<T, error_stack::Report<U>>;
}
impl<T, U, V> ReportSwitchExt<T, U> for Result<T, error_stack::Report<V>>
where
V: ErrorSwitch<U> + error_stack::Context,
U: error_stack::Context,
{
#[track_caller]
fn switch(self) -> Result<T, error_stack::Report<U>> {
match self {
Ok(i) => Ok(i),
Err(er) => {
let new_c = er.current_context().switch();
Err(er.change_context(new_c))
}
}
}
}
#[allow(missing_docs)]
#[derive(Debug, thiserror::Error)]
pub enum KeyManagerClientError {
#[error("Failed to construct header from the given value")]
FailedtoConstructHeader,
#[error("Failed to send request to Keymanager")]
RequestNotSent(String),
#[error("URL encoding of request failed")]
UrlEncodingFailed,
#[error("Failed to build the reqwest client ")]
ClientConstructionFailed,
#[error("Failed to send the request to Keymanager")]
RequestSendFailed,
#[error("Internal Server Error Received {0:?}")]
InternalServerError(bytes::Bytes),
#[error("Bad request received {0:?}")]
BadRequest(bytes::Bytes),
#[error("Unexpected Error occurred while calling the KeyManager")]
Unexpected(bytes::Bytes),
#[error("Response Decoding failed")]
ResponseDecodingFailed,
}
#[allow(missing_docs)]
#[derive(Debug, thiserror::Error)]
pub enum KeyManagerError {
#[error("Failed to add key to the KeyManager")]
KeyAddFailed,
#[error("Failed to transfer the key to the KeyManager")]
KeyTransferFailed,
#[error("Failed to Encrypt the data in the KeyManager")]
EncryptionFailed,
#[error("Failed to Decrypt the data in the KeyManager")]
DecryptionFailed,
}
/// Allow [error_stack::Report] to convert between error types
/// This auto-implements [ReportSwitchExt] for the corresponding errors
pub trait ErrorSwitch<T> {
/// Get the next error type that the source error can be escalated into
/// This does not consume the source error since we need to keep it in context
fn switch(&self) -> T;
}
/// Allow [error_stack::Report] to convert between error types
/// This serves as an alternative to [ErrorSwitch]
pub trait ErrorSwitchFrom<T> {
/// Convert to an error type that the source can be escalated into
/// This does not consume the source error since we need to keep it in context
fn switch_from(error: &T) -> Self;
}
impl<T, S> ErrorSwitch<T> for S
where
T: ErrorSwitchFrom<Self>,
{
fn switch(&self) -> T {
T::switch_from(self)
}
}
| 1,743 | 2,043 |
hyperswitch | crates/common_utils/src/validation.rs | .rs | //! Custom validations for some shared types.
use std::collections::HashSet;
use error_stack::report;
use globset::Glob;
use once_cell::sync::Lazy;
use regex::Regex;
#[cfg(feature = "logs")]
use router_env::logger;
use crate::errors::{CustomResult, ValidationError};
/// Validates a given phone number using the [phonenumber] crate
///
/// It returns a [ValidationError::InvalidValue] in case it could not parse the phone number
pub fn validate_phone_number(phone_number: &str) -> Result<(), ValidationError> {
let _ = phonenumber::parse(None, phone_number).map_err(|e| ValidationError::InvalidValue {
message: format!("Could not parse phone number: {phone_number}, because: {e:?}"),
})?;
Ok(())
}
/// Performs a simple validation against a provided email address.
pub fn validate_email(email: &str) -> CustomResult<(), ValidationError> {
#[deny(clippy::invalid_regex)]
static EMAIL_REGEX: Lazy<Option<Regex>> = Lazy::new(|| {
#[allow(unknown_lints)]
#[allow(clippy::manual_ok_err)]
match Regex::new(
r"^(?i)[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$",
) {
Ok(regex) => Some(regex),
Err(_error) => {
#[cfg(feature = "logs")]
logger::error!(?_error);
None
}
}
});
let email_regex = match EMAIL_REGEX.as_ref() {
Some(regex) => Ok(regex),
None => Err(report!(ValidationError::InvalidValue {
message: "Invalid regex expression".into()
})),
}?;
const EMAIL_MAX_LENGTH: usize = 319;
if email.is_empty() || email.chars().count() > EMAIL_MAX_LENGTH {
return Err(report!(ValidationError::InvalidValue {
message: "Email address is either empty or exceeds maximum allowed length".into()
}));
}
if !email_regex.is_match(email) {
return Err(report!(ValidationError::InvalidValue {
message: "Invalid email address format".into()
}));
}
Ok(())
}
/// Checks whether a given domain matches against a list of valid domain glob patterns
pub fn validate_domain_against_allowed_domains(
domain: &str,
allowed_domains: HashSet<String>,
) -> bool {
allowed_domains.iter().any(|allowed_domain| {
Glob::new(allowed_domain)
.map(|glob| glob.compile_matcher().is_match(domain))
.map_err(|err| {
let err_msg = format!(
"Invalid glob pattern for configured allowed_domain [{:?}]! - {:?}",
allowed_domain, err
);
#[cfg(feature = "logs")]
logger::error!(err_msg);
err_msg
})
.unwrap_or(false)
})
}
#[cfg(test)]
mod tests {
use fake::{faker::internet::en::SafeEmail, Fake};
use proptest::{
prop_assert,
strategy::{Just, NewTree, Strategy},
test_runner::TestRunner,
};
use test_case::test_case;
use super::*;
#[derive(Debug)]
struct ValidEmail;
impl Strategy for ValidEmail {
type Tree = Just<String>;
type Value = String;
fn new_tree(&self, _runner: &mut TestRunner) -> NewTree<Self> {
Ok(Just(SafeEmail().fake()))
}
}
#[test]
fn test_validate_email() {
let result = validate_email("abc@example.com");
assert!(result.is_ok());
let result = validate_email("abc+123@example.com");
assert!(result.is_ok());
let result = validate_email("");
assert!(result.is_err());
}
#[test_case("+40745323456" ; "Romanian valid phone number")]
#[test_case("+34912345678" ; "Spanish valid phone number")]
#[test_case("+41 79 123 45 67" ; "Swiss valid phone number")]
#[test_case("+66 81 234 5678" ; "Thailand valid phone number")]
fn test_validate_phone_number(phone_number: &str) {
assert!(validate_phone_number(phone_number).is_ok());
}
#[test_case("9123456789" ; "Romanian invalid phone number")]
fn test_invalid_phone_number(phone_number: &str) {
let res = validate_phone_number(phone_number);
assert!(res.is_err());
}
proptest::proptest! {
/// Example of unit test
#[test]
fn proptest_valid_fake_email(email in ValidEmail) {
prop_assert!(validate_email(&email).is_ok());
}
/// Example of unit test
#[test]
fn proptest_invalid_data_email(email in "\\PC*") {
prop_assert!(validate_email(&email).is_err());
}
#[test]
fn proptest_invalid_email(email in "[.+]@(.+)") {
prop_assert!(validate_email(&email).is_err());
}
}
}
| 1,173 | 2,044 |
hyperswitch | crates/common_utils/src/events.rs | .rs | use serde::Serialize;
use crate::{id_type, types::TimeRange};
pub trait ApiEventMetric {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(tag = "flow_type", rename_all = "snake_case")]
pub enum ApiEventsType {
Payout {
payout_id: String,
},
#[cfg(feature = "v1")]
Payment {
payment_id: id_type::PaymentId,
},
#[cfg(feature = "v2")]
Payment {
payment_id: id_type::GlobalPaymentId,
},
#[cfg(feature = "v1")]
Refund {
payment_id: Option<id_type::PaymentId>,
refund_id: String,
},
#[cfg(feature = "v2")]
Refund {
payment_id: id_type::GlobalPaymentId,
refund_id: id_type::GlobalRefundId,
},
#[cfg(feature = "v1")]
PaymentMethod {
payment_method_id: String,
payment_method: Option<common_enums::PaymentMethod>,
payment_method_type: Option<common_enums::PaymentMethodType>,
},
#[cfg(feature = "v2")]
PaymentMethod {
payment_method_id: id_type::GlobalPaymentMethodId,
payment_method_type: Option<common_enums::PaymentMethod>,
payment_method_subtype: Option<common_enums::PaymentMethodType>,
},
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
PaymentMethodCreate,
#[cfg(all(feature = "v2", feature = "customer_v2"))]
Customer {
customer_id: Option<id_type::GlobalCustomerId>,
},
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
Customer {
customer_id: id_type::CustomerId,
},
BusinessProfile {
profile_id: id_type::ProfileId,
},
ApiKey {
key_id: id_type::ApiKeyId,
},
User {
user_id: String,
},
PaymentMethodList {
payment_id: Option<String>,
},
#[cfg(feature = "v2")]
PaymentMethodListForPaymentMethods {
payment_method_id: id_type::GlobalPaymentMethodId,
},
#[cfg(feature = "v1")]
Webhooks {
connector: String,
payment_id: Option<id_type::PaymentId>,
},
#[cfg(feature = "v2")]
Webhooks {
connector: id_type::MerchantConnectorAccountId,
payment_id: Option<id_type::GlobalPaymentId>,
},
Routing,
ResourceListAPI,
#[cfg(feature = "v1")]
PaymentRedirectionResponse {
connector: Option<String>,
payment_id: Option<id_type::PaymentId>,
},
#[cfg(feature = "v2")]
PaymentRedirectionResponse {
payment_id: id_type::GlobalPaymentId,
},
Gsm,
// TODO: This has to be removed once the corresponding apiEventTypes are created
Miscellaneous,
Keymanager,
RustLocker,
ApplePayCertificatesMigration,
FraudCheck,
Recon,
ExternalServiceAuth,
Dispute {
dispute_id: String,
},
Events {
merchant_id: id_type::MerchantId,
},
PaymentMethodCollectLink {
link_id: String,
},
Poll {
poll_id: String,
},
Analytics,
#[cfg(feature = "v2")]
ClientSecret {
key_id: id_type::ClientSecretId,
},
#[cfg(feature = "v2")]
PaymentMethodSession {
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
},
ProcessTracker,
}
impl ApiEventMetric for serde_json::Value {}
impl ApiEventMetric for () {}
#[cfg(feature = "v1")]
impl ApiEventMetric for id_type::PaymentId {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for id_type::GlobalPaymentId {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.clone(),
})
}
}
impl<Q: ApiEventMetric, E> ApiEventMetric for Result<Q, E> {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
match self {
Ok(q) => q.get_api_event_type(),
Err(_) => None,
}
}
}
// TODO: Ideally all these types should be replaced by newtype responses
impl<T> ApiEventMetric for Vec<T> {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Miscellaneous)
}
}
#[macro_export]
macro_rules! impl_api_event_type {
($event: ident, ($($type:ty),+))=> {
$(
impl ApiEventMetric for $type {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::$event)
}
}
)+
};
}
impl_api_event_type!(
Miscellaneous,
(
String,
id_type::MerchantId,
(Option<i64>, Option<i64>, String),
(Option<i64>, Option<i64>, id_type::MerchantId),
bool
)
);
impl<T: ApiEventMetric> ApiEventMetric for &T {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
T::get_api_event_type(self)
}
}
impl ApiEventMetric for TimeRange {}
| 1,245 | 2,045 |
hyperswitch | crates/common_utils/src/macros.rs | .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
}
}
};
}
/// 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();
};
}
| 3,316 | 2,046 |
hyperswitch | crates/common_utils/src/types/authentication.rs | .rs | use crate::id_type;
/// Enum for different levels of authentication
#[derive(
Clone,
Debug,
Hash,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
)]
pub enum AuthInfo {
/// OrgLevel: Authentication at the organization level
OrgLevel {
/// org_id: OrganizationId
org_id: id_type::OrganizationId,
},
/// MerchantLevel: Authentication at the merchant level
MerchantLevel {
/// org_id: OrganizationId
org_id: id_type::OrganizationId,
/// merchant_ids: Vec<MerchantId>
merchant_ids: Vec<id_type::MerchantId>,
},
/// ProfileLevel: Authentication at the profile level
ProfileLevel {
/// org_id: OrganizationId
org_id: id_type::OrganizationId,
/// merchant_id: MerchantId
merchant_id: id_type::MerchantId,
/// profile_ids: Vec<ProfileId>
profile_ids: Vec<id_type::ProfileId>,
},
}
/// Enum for different resource types supported in client secret
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ResourceId {
/// Global Payment ID (Not exposed in api_models version of enum)
Payment(id_type::GlobalPaymentId),
/// Global Customer ID
Customer(id_type::GlobalCustomerId),
/// Global Payment Methods Session ID
PaymentMethodSession(id_type::GlobalPaymentMethodSessionId),
}
#[cfg(feature = "v2")]
impl ResourceId {
/// Get string representation of enclosed ID type
pub fn to_str(&self) -> &str {
match self {
Self::Payment(id) => id.get_string_repr(),
Self::Customer(id) => id.get_string_repr(),
Self::PaymentMethodSession(id) => id.get_string_repr(),
}
}
}
| 421 | 2,047 |
hyperswitch | crates/common_utils/src/types/keymanager.rs | .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::tracing_actix_web::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 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: 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>;
}
| 3,524 | 2,048 |
hyperswitch | crates/common_utils/src/types/primitive_wrappers.rs | .rs | pub(crate) mod bool_wrappers {
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 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 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 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<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)
}
}
}
| 927 | 2,049 |
hyperswitch | crates/common_utils/src/types/theme.rs | .rs | use common_enums::EntityType;
use serde::{Deserialize, Serialize};
use crate::{
events::{ApiEventMetric, ApiEventsType},
id_type, impl_api_event_type,
};
/// Enum for having all the required lineage for every level.
/// Currently being used for theme related APIs and queries.
#[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "entity_type", rename_all = "snake_case")]
pub enum ThemeLineage {
/// Tenant lineage variant
Tenant {
/// tenant_id: TenantId
tenant_id: id_type::TenantId,
},
/// Org lineage variant
Organization {
/// tenant_id: TenantId
tenant_id: id_type::TenantId,
/// org_id: OrganizationId
org_id: id_type::OrganizationId,
},
/// Merchant lineage variant
Merchant {
/// tenant_id: TenantId
tenant_id: id_type::TenantId,
/// org_id: OrganizationId
org_id: id_type::OrganizationId,
/// merchant_id: MerchantId
merchant_id: id_type::MerchantId,
},
/// Profile lineage variant
Profile {
/// tenant_id: TenantId
tenant_id: id_type::TenantId,
/// org_id: OrganizationId
org_id: id_type::OrganizationId,
/// merchant_id: MerchantId
merchant_id: id_type::MerchantId,
/// profile_id: ProfileId
profile_id: id_type::ProfileId,
},
}
impl_api_event_type!(Miscellaneous, (ThemeLineage));
impl ThemeLineage {
/// Constructor for ThemeLineage
pub fn new(
entity_type: EntityType,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
merchant_id: id_type::MerchantId,
profile_id: id_type::ProfileId,
) -> Self {
match entity_type {
EntityType::Tenant => Self::Tenant { tenant_id },
EntityType::Organization => Self::Organization { tenant_id, org_id },
EntityType::Merchant => Self::Merchant {
tenant_id,
org_id,
merchant_id,
},
EntityType::Profile => Self::Profile {
tenant_id,
org_id,
merchant_id,
profile_id,
},
}
}
/// Get the entity_type from the lineage
pub fn entity_type(&self) -> EntityType {
match self {
Self::Tenant { .. } => EntityType::Tenant,
Self::Organization { .. } => EntityType::Organization,
Self::Merchant { .. } => EntityType::Merchant,
Self::Profile { .. } => EntityType::Profile,
}
}
/// Get the tenant_id from the lineage
pub fn tenant_id(&self) -> &id_type::TenantId {
match self {
Self::Tenant { tenant_id }
| Self::Organization { tenant_id, .. }
| Self::Merchant { tenant_id, .. }
| Self::Profile { tenant_id, .. } => tenant_id,
}
}
/// Get the org_id from the lineage
pub fn org_id(&self) -> Option<&id_type::OrganizationId> {
match self {
Self::Tenant { .. } => None,
Self::Organization { org_id, .. }
| Self::Merchant { org_id, .. }
| Self::Profile { org_id, .. } => Some(org_id),
}
}
/// Get the merchant_id from the lineage
pub fn merchant_id(&self) -> Option<&id_type::MerchantId> {
match self {
Self::Tenant { .. } | Self::Organization { .. } => None,
Self::Merchant { merchant_id, .. } | Self::Profile { merchant_id, .. } => {
Some(merchant_id)
}
}
}
/// Get the profile_id from the lineage
pub fn profile_id(&self) -> Option<&id_type::ProfileId> {
match self {
Self::Tenant { .. } | Self::Organization { .. } | Self::Merchant { .. } => None,
Self::Profile { profile_id, .. } => Some(profile_id),
}
}
/// Get higher lineages from the current lineage
pub fn get_same_and_higher_lineages(self) -> Vec<Self> {
match &self {
Self::Tenant { .. } => vec![self],
Self::Organization { tenant_id, .. } => vec![
Self::Tenant {
tenant_id: tenant_id.clone(),
},
self,
],
Self::Merchant {
tenant_id, org_id, ..
} => vec![
Self::Tenant {
tenant_id: tenant_id.clone(),
},
Self::Organization {
tenant_id: tenant_id.clone(),
org_id: org_id.clone(),
},
self,
],
Self::Profile {
tenant_id,
org_id,
merchant_id,
..
} => vec![
Self::Tenant {
tenant_id: tenant_id.clone(),
},
Self::Organization {
tenant_id: tenant_id.clone(),
org_id: org_id.clone(),
},
Self::Merchant {
tenant_id: tenant_id.clone(),
org_id: org_id.clone(),
merchant_id: merchant_id.clone(),
},
self,
],
}
}
}
/// Struct for holding the theme settings for email
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct EmailThemeConfig {
/// The entity name to be used in the email
pub entity_name: String,
/// The URL of the entity logo to be used in the email
pub entity_logo_url: String,
/// The primary color to be used in the email
pub primary_color: String,
/// The foreground color to be used in the email
pub foreground_color: String,
/// The background color to be used in the email
pub background_color: String,
}
| 1,250 | 2,050 |
hyperswitch | crates/common_utils/src/id_type/merchant.rs | .rs | //! Contains the id type for merchant account
//!
//! Ids for merchant account are derived from the merchant name
//! If there are any special characters, they are removed
use std::fmt::Display;
use crate::{
date_time,
errors::{CustomResult, ValidationError},
generate_id_with_default_len,
id_type::{AlphaNumericId, LengthId},
new_type::MerchantName,
types::keymanager,
};
crate::id_type!(
MerchantId,
"A type for merchant_id that can be used for merchant ids"
);
crate::impl_id_type_methods!(MerchantId, "merchant_id");
// This is to display the `MerchantId` as MerchantId(abcd)
crate::impl_debug_id_type!(MerchantId);
crate::impl_default_id_type!(MerchantId, "mer");
crate::impl_try_from_cow_str_id_type!(MerchantId, "merchant_id");
crate::impl_generate_id_id_type!(MerchantId, "mer");
crate::impl_serializable_secret_id_type!(MerchantId);
crate::impl_queryable_id_type!(MerchantId);
crate::impl_to_sql_from_sql_id_type!(MerchantId);
// This is implemented so that we can use merchant id directly as attribute in metrics
#[cfg(feature = "metrics")]
impl From<MerchantId> for router_env::opentelemetry::Value {
fn from(val: MerchantId) -> Self {
Self::from(val.0 .0 .0)
}
}
impl MerchantId {
/// Create a Merchant id from MerchantName
pub fn from_merchant_name(merchant_name: MerchantName) -> Self {
let merchant_name_string = merchant_name.into_inner();
let merchant_id_prefix = merchant_name_string.trim().to_lowercase().replace(' ', "");
let alphanumeric_id =
AlphaNumericId::new_unchecked(generate_id_with_default_len(&merchant_id_prefix));
let length_id = LengthId::new_unchecked(alphanumeric_id);
Self(length_id)
}
/// Get a merchant id with the const value of `MERCHANT_ID_NOT_FOUND`
pub fn get_merchant_id_not_found() -> Self {
let alphanumeric_id = AlphaNumericId::new_unchecked("MERCHANT_ID_NOT_FOUND".to_string());
let length_id = LengthId::new_unchecked(alphanumeric_id);
Self(length_id)
}
/// Get a merchant id for internal use only
pub fn get_internal_user_merchant_id(merchant_id: &str) -> Self {
let alphanumeric_id = AlphaNumericId::new_unchecked(merchant_id.to_string());
let length_id = LengthId::new_unchecked(alphanumeric_id);
Self(length_id)
}
/// Create a new merchant_id from unix timestamp, of the format `merchant_{timestamp}`
pub fn new_from_unix_timestamp() -> Self {
let merchant_id = format!("merchant_{}", date_time::now_unix_timestamp());
let alphanumeric_id = AlphaNumericId::new_unchecked(merchant_id);
let length_id = LengthId::new_unchecked(alphanumeric_id);
Self(length_id)
}
/// Get a merchant id with a value of `irrelevant_merchant_id`
pub fn get_irrelevant_merchant_id() -> Self {
let alphanumeric_id = AlphaNumericId::new_unchecked("irrelevant_merchant_id".to_string());
let length_id = LengthId::new_unchecked(alphanumeric_id);
Self(length_id)
}
/// Get a merchant id from String
pub fn wrap(merchant_id: String) -> CustomResult<Self, ValidationError> {
Self::try_from(std::borrow::Cow::from(merchant_id))
}
}
impl From<MerchantId> for keymanager::Identifier {
fn from(value: MerchantId) -> Self {
Self::Merchant(value)
}
}
/// All the keys that can be formed from merchant id
impl MerchantId {
/// get step up enabled key
pub fn get_step_up_enabled_key(&self) -> String {
format!("step_up_enabled_{}", self.get_string_repr())
}
/// get_max_auto_retries_enabled key
pub fn get_max_auto_retries_enabled(&self) -> String {
format!("max_auto_retries_enabled_{}", self.get_string_repr())
}
/// get_requires_cvv_key
pub fn get_requires_cvv_key(&self) -> String {
format!("{}_requires_cvv", self.get_string_repr())
}
/// get_pm_filters_cgraph_key
pub fn get_pm_filters_cgraph_key(&self) -> String {
format!("pm_filters_cgraph_{}", self.get_string_repr())
}
/// get_blocklist_enabled_key
pub fn get_blocklist_guard_key(&self) -> String {
format!("guard_blocklist_for_{}", self.get_string_repr())
}
/// get_merchant_fingerprint_secret_key
pub fn get_merchant_fingerprint_secret_key(&self) -> String {
format!("fingerprint_secret_{}", self.get_string_repr())
}
/// get_surcharge_dsk_key
pub fn get_surcharge_dsk_key(&self) -> String {
format!("surcharge_dsl_{}", self.get_string_repr())
}
/// get_dsk_key
pub fn get_dsl_config(&self) -> String {
format!("dsl_{}", self.get_string_repr())
}
/// get_creds_identifier_key
pub fn get_creds_identifier_key(&self, creds_identifier: &str) -> String {
format!("mcd_{}_{creds_identifier}", self.get_string_repr())
}
/// get_poll_id
pub fn get_poll_id(&self, unique_id: &str) -> String {
format!("poll_{}_{unique_id}", self.get_string_repr())
}
/// get_access_token_key
pub fn get_access_token_key(
&self,
merchant_connector_id_or_connector_name: impl Display,
) -> String {
format!(
"access_token_{}_{merchant_connector_id_or_connector_name}",
self.get_string_repr()
)
}
/// get_skip_saving_wallet_at_connector_key
pub fn get_skip_saving_wallet_at_connector_key(&self) -> String {
format!("skip_saving_wallet_at_connector_{}", self.get_string_repr())
}
/// get_payment_config_routing_id
pub fn get_payment_config_routing_id(&self) -> String {
format!("payment_config_id_{}", self.get_string_repr())
}
/// get_payment_method_surcharge_routing_id
pub fn get_payment_method_surcharge_routing_id(&self) -> String {
format!("payment_method_surcharge_id_{}", self.get_string_repr())
}
/// get_webhook_config_disabled_events_key
pub fn get_webhook_config_disabled_events_key(&self, connector_id: &str) -> String {
format!(
"whconf_disabled_events_{}_{connector_id}",
self.get_string_repr()
)
}
/// get_should_call_gsm_payout_key
pub fn get_should_call_gsm_payout_key(
&self,
payout_retry_type: common_enums::PayoutRetryType,
) -> String {
match payout_retry_type {
common_enums::PayoutRetryType::SingleConnector => format!(
"should_call_gsm_single_connector_payout_{}",
self.get_string_repr()
),
common_enums::PayoutRetryType::MultiConnector => format!(
"should_call_gsm_multiple_connector_payout_{}",
self.get_string_repr()
),
}
}
/// Get should call gsm key for payment
pub fn get_should_call_gsm_key(&self) -> String {
format!("should_call_gsm_{}", self.get_string_repr())
}
/// get_max_auto_single_connector_payout_retries_enabled_
pub fn get_max_auto_single_connector_payout_retries_enabled(
&self,
payout_retry_type: common_enums::PayoutRetryType,
) -> String {
match payout_retry_type {
common_enums::PayoutRetryType::SingleConnector => format!(
"max_auto_single_connector_payout_retries_enabled_{}",
self.get_string_repr()
),
common_enums::PayoutRetryType::MultiConnector => format!(
"max_auto_multiple_connector_payout_retries_enabled_{}",
self.get_string_repr()
),
}
}
}
| 1,750 | 2,051 |
hyperswitch | crates/common_utils/src/id_type/organization.rs | .rs | use crate::errors::{CustomResult, ValidationError};
crate::id_type!(
OrganizationId,
"A type for organization_id that can be used for organization ids"
);
crate::impl_id_type_methods!(OrganizationId, "organization_id");
// This is to display the `OrganizationId` as OrganizationId(abcd)
crate::impl_debug_id_type!(OrganizationId);
crate::impl_default_id_type!(OrganizationId, "org");
crate::impl_try_from_cow_str_id_type!(OrganizationId, "organization_id");
crate::impl_generate_id_id_type!(OrganizationId, "org");
crate::impl_serializable_secret_id_type!(OrganizationId);
crate::impl_queryable_id_type!(OrganizationId);
crate::impl_to_sql_from_sql_id_type!(OrganizationId);
impl OrganizationId {
/// Get an organization id from String
pub fn try_from_string(org_id: String) -> CustomResult<Self, ValidationError> {
Self::try_from(std::borrow::Cow::from(org_id))
}
}
| 206 | 2,052 |
hyperswitch | crates/common_utils/src/id_type/relay.rs | .rs | use std::str::FromStr;
crate::id_type!(
RelayId,
"A type for relay_id that can be used for relay ids"
);
crate::impl_id_type_methods!(RelayId, "relay_id");
crate::impl_try_from_cow_str_id_type!(RelayId, "relay_id");
crate::impl_generate_id_id_type!(RelayId, "relay");
crate::impl_serializable_secret_id_type!(RelayId);
crate::impl_queryable_id_type!(RelayId);
crate::impl_to_sql_from_sql_id_type!(RelayId);
crate::impl_debug_id_type!(RelayId);
impl FromStr for RelayId {
type Err = error_stack::Report<crate::errors::ValidationError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let cow_string = std::borrow::Cow::Owned(s.to_string());
Self::try_from(cow_string)
}
}
| 200 | 2,053 |
hyperswitch | crates/common_utils/src/id_type/routing.rs | .rs | crate::id_type!(
RoutingId,
" A type for routing_id that can be used for routing ids"
);
crate::impl_id_type_methods!(RoutingId, "routing_id");
// This is to display the `RoutingId` as RoutingId(abcd)
crate::impl_debug_id_type!(RoutingId);
crate::impl_try_from_cow_str_id_type!(RoutingId, "routing_id");
crate::impl_generate_id_id_type!(RoutingId, "routing");
crate::impl_serializable_secret_id_type!(RoutingId);
crate::impl_queryable_id_type!(RoutingId);
crate::impl_to_sql_from_sql_id_type!(RoutingId);
impl crate::events::ApiEventMetric for RoutingId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::Routing)
}
}
| 181 | 2,054 |
hyperswitch | crates/common_utils/src/id_type/payment.rs | .rs | use crate::{
errors::{CustomResult, ValidationError},
generate_id_with_default_len,
id_type::{AlphaNumericId, LengthId},
};
crate::id_type!(
PaymentId,
"A type for payment_id that can be used for payment ids"
);
crate::impl_id_type_methods!(PaymentId, "payment_id");
// This is to display the `PaymentId` as PaymentId(abcd)
crate::impl_debug_id_type!(PaymentId);
crate::impl_default_id_type!(PaymentId, "pay");
crate::impl_try_from_cow_str_id_type!(PaymentId, "payment_id");
// Database related implementations so that this field can be used directly in the database tables
crate::impl_queryable_id_type!(PaymentId);
crate::impl_to_sql_from_sql_id_type!(PaymentId);
impl PaymentId {
/// Get the hash key to be stored in redis
pub fn get_hash_key_for_kv_store(&self) -> String {
format!("pi_{}", self.0 .0 .0)
}
// This function should be removed once we have a better way to handle mandatory payment id in other flows
/// Get payment id in the format of irrelevant_payment_id_in_{flow}
pub fn get_irrelevant_id(flow: &str) -> Self {
let alphanumeric_id =
AlphaNumericId::new_unchecked(format!("irrelevant_payment_id_in_{flow}"));
let id = LengthId::new_unchecked(alphanumeric_id);
Self(id)
}
/// Get the attempt id for the payment id based on the attempt count
pub fn get_attempt_id(&self, attempt_count: i16) -> String {
format!("{}_{attempt_count}", self.get_string_repr())
}
/// Generate a client id for the payment id
pub fn generate_client_secret(&self) -> String {
generate_id_with_default_len(&format!("{}_secret", self.get_string_repr()))
}
/// Generate a key for pm_auth
pub fn get_pm_auth_key(&self) -> String {
format!("pm_auth_{}", self.get_string_repr())
}
/// Get external authentication request poll id
pub fn get_external_authentication_request_poll_id(&self) -> String {
format!("external_authentication_{}", self.get_string_repr())
}
/// Generate a test payment id with prefix test_
pub fn generate_test_payment_id_for_sample_data() -> Self {
let id = generate_id_with_default_len("test");
let alphanumeric_id = AlphaNumericId::new_unchecked(id);
let id = LengthId::new_unchecked(alphanumeric_id);
Self(id)
}
/// Wrap a string inside PaymentId
pub fn wrap(payment_id_string: String) -> CustomResult<Self, ValidationError> {
Self::try_from(std::borrow::Cow::from(payment_id_string))
}
}
crate::id_type!(PaymentReferenceId, "A type for payment_reference_id");
crate::impl_id_type_methods!(PaymentReferenceId, "payment_reference_id");
// This is to display the `PaymentReferenceId` as PaymentReferenceId(abcd)
crate::impl_debug_id_type!(PaymentReferenceId);
crate::impl_try_from_cow_str_id_type!(PaymentReferenceId, "payment_reference_id");
// Database related implementations so that this field can be used directly in the database tables
crate::impl_queryable_id_type!(PaymentReferenceId);
crate::impl_to_sql_from_sql_id_type!(PaymentReferenceId);
// This is implemented so that we can use payment id directly as attribute in metrics
#[cfg(feature = "metrics")]
impl From<PaymentId> for router_env::opentelemetry::Value {
fn from(val: PaymentId) -> Self {
Self::from(val.0 .0 .0)
}
}
impl std::str::FromStr for PaymentReferenceId {
type Err = error_stack::Report<ValidationError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let cow_string = std::borrow::Cow::Owned(s.to_string());
Self::try_from(cow_string)
}
}
| 854 | 2,055 |
hyperswitch | crates/common_utils/src/id_type/customer.rs | .rs | crate::id_type!(
CustomerId,
"A type for customer_id that can be used for customer ids"
);
crate::impl_id_type_methods!(CustomerId, "customer_id");
// This is to display the `CustomerId` as CustomerId(abcd)
crate::impl_debug_id_type!(CustomerId);
crate::impl_default_id_type!(CustomerId, "cus");
crate::impl_try_from_cow_str_id_type!(CustomerId, "customer_id");
crate::impl_generate_id_id_type!(CustomerId, "cus");
crate::impl_serializable_secret_id_type!(CustomerId);
crate::impl_queryable_id_type!(CustomerId);
crate::impl_to_sql_from_sql_id_type!(CustomerId);
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
impl crate::events::ApiEventMetric for CustomerId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::Customer {
customer_id: self.clone(),
})
}
}
| 219 | 2,056 |
hyperswitch | crates/common_utils/src/id_type/api_key.rs | .rs | crate::id_type!(
ApiKeyId,
"A type for key_id that can be used for API key IDs"
);
crate::impl_id_type_methods!(ApiKeyId, "key_id");
// This is to display the `ApiKeyId` as ApiKeyId(abcd)
crate::impl_debug_id_type!(ApiKeyId);
crate::impl_try_from_cow_str_id_type!(ApiKeyId, "key_id");
crate::impl_serializable_secret_id_type!(ApiKeyId);
crate::impl_queryable_id_type!(ApiKeyId);
crate::impl_to_sql_from_sql_id_type!(ApiKeyId);
impl ApiKeyId {
/// Generate Api Key Id from prefix
pub fn generate_key_id(prefix: &'static str) -> Self {
Self(crate::generate_ref_id_with_default_length(prefix))
}
}
impl crate::events::ApiEventMetric for ApiKeyId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::ApiKey {
key_id: self.clone(),
})
}
}
impl crate::events::ApiEventMetric for (super::MerchantId, ApiKeyId) {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::ApiKey {
key_id: self.1.clone(),
})
}
}
impl crate::events::ApiEventMetric for (&super::MerchantId, &ApiKeyId) {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::ApiKey {
key_id: self.1.clone(),
})
}
}
crate::impl_default_id_type!(ApiKeyId, "key");
| 366 | 2,057 |
hyperswitch | crates/common_utils/src/id_type/refunds.rs | .rs | crate::id_type!(RefundReferenceId, "A type for refund_reference_id");
crate::impl_id_type_methods!(RefundReferenceId, "refund_reference_id");
// This is to display the `RefundReferenceId` as RefundReferenceId(abcd)
crate::impl_debug_id_type!(RefundReferenceId);
crate::impl_try_from_cow_str_id_type!(RefundReferenceId, "refund_reference_id");
// Database related implementations so that this field can be used directly in the database tables
crate::impl_queryable_id_type!(RefundReferenceId);
crate::impl_to_sql_from_sql_id_type!(RefundReferenceId);
| 133 | 2,058 |
hyperswitch | crates/common_utils/src/id_type/global_id.rs | .rs | pub(super) mod customer;
pub(super) mod payment;
pub(super) mod payment_methods;
pub(super) mod refunds;
use diesel::{backend::Backend, deserialize::FromSql, serialize::ToSql, sql_types};
use error_stack::ResultExt;
use thiserror::Error;
use crate::{
consts::{CELL_IDENTIFIER_LENGTH, MAX_GLOBAL_ID_LENGTH, MIN_GLOBAL_ID_LENGTH},
errors, generate_time_ordered_id,
id_type::{AlphaNumericId, AlphaNumericIdError, LengthId, LengthIdError},
};
#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize)]
/// A global id that can be used to identify any entity
/// This id will have information about the entity and cell in a distributed system architecture
pub(crate) struct GlobalId(LengthId<MAX_GLOBAL_ID_LENGTH, MIN_GLOBAL_ID_LENGTH>);
#[derive(Clone, Copy)]
/// Entities that can be identified by a global id
pub(crate) enum GlobalEntity {
Customer,
Payment,
Attempt,
PaymentMethod,
Refund,
PaymentMethodSession,
}
impl GlobalEntity {
fn prefix(self) -> &'static str {
match self {
Self::Customer => "cus",
Self::Payment => "pay",
Self::PaymentMethod => "pm",
Self::Attempt => "att",
Self::Refund => "ref",
Self::PaymentMethodSession => "pms",
}
}
}
/// Cell identifier for an instance / deployment of application
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct CellId(LengthId<CELL_IDENTIFIER_LENGTH, CELL_IDENTIFIER_LENGTH>);
#[derive(Debug, Error, PartialEq, Eq)]
pub enum CellIdError {
#[error("cell id error: {0}")]
InvalidCellLength(LengthIdError),
#[error("{0}")]
InvalidCellIdFormat(AlphaNumericIdError),
}
impl From<LengthIdError> for CellIdError {
fn from(error: LengthIdError) -> Self {
Self::InvalidCellLength(error)
}
}
impl From<AlphaNumericIdError> for CellIdError {
fn from(error: AlphaNumericIdError) -> Self {
Self::InvalidCellIdFormat(error)
}
}
impl CellId {
/// Create a new cell id from a string
fn from_str(cell_id_string: impl AsRef<str>) -> Result<Self, CellIdError> {
let trimmed_input_string = cell_id_string.as_ref().trim().to_string();
let alphanumeric_id = AlphaNumericId::from(trimmed_input_string.into())?;
let length_id = LengthId::from_alphanumeric_id(alphanumeric_id)?;
Ok(Self(length_id))
}
/// Create a new cell id from a string
pub fn from_string(
input_string: impl AsRef<str>,
) -> error_stack::Result<Self, errors::ValidationError> {
Self::from_str(input_string).change_context(
errors::ValidationError::IncorrectValueProvided {
field_name: "cell_id",
},
)
}
/// Get the string representation of the cell id
fn get_string_repr(&self) -> &str {
&self.0 .0 .0
}
}
impl<'de> serde::Deserialize<'de> for CellId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let deserialized_string = String::deserialize(deserializer)?;
Self::from_str(deserialized_string.as_str()).map_err(serde::de::Error::custom)
}
}
/// Error generated from violation of constraints for MerchantReferenceId
#[derive(Debug, Error, PartialEq, Eq)]
pub(crate) enum GlobalIdError {
/// The format for the global id is invalid
#[error("The id format is invalid, expected format is {{cell_id:5}}_{{entity_prefix:3}}_{{uuid:32}}_{{random:24}}")]
InvalidIdFormat,
/// LengthIdError and AlphanumericIdError
#[error("{0}")]
LengthIdError(#[from] LengthIdError),
/// CellIdError because of invalid cell id format
#[error("{0}")]
CellIdError(#[from] CellIdError),
}
impl GlobalId {
/// Create a new global id from entity and cell information
/// The entity prefix is used to identify the entity, `cus` for customers, `pay`` for payments etc.
pub fn generate(cell_id: &CellId, entity: GlobalEntity) -> Self {
let prefix = format!("{}_{}", cell_id.get_string_repr(), entity.prefix());
let id = generate_time_ordered_id(&prefix);
let alphanumeric_id = AlphaNumericId::new_unchecked(id);
Self(LengthId::new_unchecked(alphanumeric_id))
}
pub(crate) fn from_string(
input_string: std::borrow::Cow<'static, str>,
) -> Result<Self, GlobalIdError> {
let length_id = LengthId::from(input_string)?;
let input_string = &length_id.0 .0;
let (cell_id, remaining) = input_string
.split_once("_")
.ok_or(GlobalIdError::InvalidIdFormat)?;
CellId::from_str(cell_id)?;
Ok(Self(length_id))
}
pub(crate) fn get_string_repr(&self) -> &str {
&self.0 .0 .0
}
}
impl<DB> ToSql<sql_types::Text, DB> for GlobalId
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0 .0 .0.to_sql(out)
}
}
impl<DB> FromSql<sql_types::Text, DB> for GlobalId
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
let string_val = String::from_sql(value)?;
let alphanumeric_id = AlphaNumericId::from(string_val.into())?;
let length_id = LengthId::from_alphanumeric_id(alphanumeric_id)?;
Ok(Self(length_id))
}
}
/// Deserialize the global id from string
/// The format should match {cell_id:5}_{entity_prefix:3}_{time_ordered_id:32}_{.*:24}
impl<'de> serde::Deserialize<'de> for GlobalId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let deserialized_string = String::deserialize(deserializer)?;
Self::from_string(deserialized_string.into()).map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod global_id_tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn test_cell_id_from_str() {
let cell_id_string = "12345";
let cell_id = CellId::from_str(cell_id_string).unwrap();
assert_eq!(cell_id.get_string_repr(), cell_id_string);
}
#[test]
fn test_global_id_generate() {
let cell_id_string = "12345";
let entity = GlobalEntity::Customer;
let cell_id = CellId::from_str(cell_id_string).unwrap();
let global_id = GlobalId::generate(&cell_id, entity);
// Generate a regex for globalid
// Eg - 12abc_cus_abcdefghijklmnopqrstuvwxyz1234567890
let regex = regex::Regex::new(r"[a-z0-9]{5}_cus_[a-z0-9]{32}").unwrap();
assert!(regex.is_match(&global_id.0 .0 .0));
}
#[test]
fn test_global_id_from_string() {
let input_string = "12345_cus_abcdefghijklmnopqrstuvwxyz1234567890";
let global_id = GlobalId::from_string(input_string.into()).unwrap();
assert_eq!(global_id.0 .0 .0, input_string);
}
#[test]
fn test_global_id_deser() {
let input_string_for_serde_json_conversion =
r#""12345_cus_abcdefghijklmnopqrstuvwxyz1234567890""#;
let input_string = "12345_cus_abcdefghijklmnopqrstuvwxyz1234567890";
let global_id =
serde_json::from_str::<GlobalId>(input_string_for_serde_json_conversion).unwrap();
assert_eq!(global_id.0 .0 .0, input_string);
}
#[test]
fn test_global_id_deser_error() {
let input_string_for_serde_json_conversion =
r#""123_45_cus_abcdefghijklmnopqrstuvwxyz1234567890""#;
let global_id = serde_json::from_str::<GlobalId>(input_string_for_serde_json_conversion);
assert!(global_id.is_err());
let expected_error_message = format!(
"cell id error: the minimum required length for this field is {CELL_IDENTIFIER_LENGTH}"
);
let error_message = global_id.unwrap_err().to_string();
assert_eq!(error_message, expected_error_message);
}
}
| 2,032 | 2,059 |
hyperswitch | crates/common_utils/src/id_type/tenant.rs | .rs | use crate::{
consts::DEFAULT_GLOBAL_TENANT_ID,
errors::{CustomResult, ValidationError},
};
crate::id_type!(
TenantId,
"A type for tenant_id that can be used for unique identifier for a tenant"
);
crate::impl_id_type_methods!(TenantId, "tenant_id");
// This is to display the `TenantId` as TenantId(abcd)
crate::impl_debug_id_type!(TenantId);
crate::impl_try_from_cow_str_id_type!(TenantId, "tenant_id");
crate::impl_serializable_secret_id_type!(TenantId);
crate::impl_queryable_id_type!(TenantId);
crate::impl_to_sql_from_sql_id_type!(TenantId);
impl TenantId {
/// Get the default global tenant ID
pub fn get_default_global_tenant_id() -> Self {
Self(super::LengthId::new_unchecked(
super::AlphaNumericId::new_unchecked(DEFAULT_GLOBAL_TENANT_ID.to_string()),
))
}
/// Get tenant id from String
pub fn try_from_string(tenant_id: String) -> CustomResult<Self, ValidationError> {
Self::try_from(std::borrow::Cow::from(tenant_id))
}
}
| 251 | 2,060 |
hyperswitch | crates/common_utils/src/id_type/merchant_connector_account.rs | .rs | use crate::errors::{CustomResult, ValidationError};
crate::id_type!(
MerchantConnectorAccountId,
"A type for merchant_connector_id that can be used for merchant_connector_account ids"
);
crate::impl_id_type_methods!(MerchantConnectorAccountId, "merchant_connector_id");
// This is to display the `MerchantConnectorAccountId` as MerchantConnectorAccountId(abcd)
crate::impl_debug_id_type!(MerchantConnectorAccountId);
crate::impl_generate_id_id_type!(MerchantConnectorAccountId, "mca");
crate::impl_try_from_cow_str_id_type!(MerchantConnectorAccountId, "merchant_connector_id");
crate::impl_serializable_secret_id_type!(MerchantConnectorAccountId);
crate::impl_queryable_id_type!(MerchantConnectorAccountId);
crate::impl_to_sql_from_sql_id_type!(MerchantConnectorAccountId);
impl MerchantConnectorAccountId {
/// Get a merchant connector account id from String
pub fn wrap(merchant_connector_account_id: String) -> CustomResult<Self, ValidationError> {
Self::try_from(std::borrow::Cow::from(merchant_connector_account_id))
}
}
| 216 | 2,061 |
hyperswitch | crates/common_utils/src/id_type/client_secret.rs | .rs | crate::id_type!(
ClientSecretId,
"A type for key_id that can be used for Ephemeral key IDs"
);
crate::impl_id_type_methods!(ClientSecretId, "key_id");
// This is to display the `ClientSecretId` as ClientSecretId(abcd)
crate::impl_debug_id_type!(ClientSecretId);
crate::impl_try_from_cow_str_id_type!(ClientSecretId, "key_id");
crate::impl_generate_id_id_type!(ClientSecretId, "csi");
crate::impl_serializable_secret_id_type!(ClientSecretId);
crate::impl_queryable_id_type!(ClientSecretId);
crate::impl_to_sql_from_sql_id_type!(ClientSecretId);
#[cfg(feature = "v2")]
impl crate::events::ApiEventMetric for ClientSecretId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::ClientSecret {
key_id: self.clone(),
})
}
}
crate::impl_default_id_type!(ClientSecretId, "key");
impl ClientSecretId {
/// Generate a key for redis
pub fn generate_redis_key(&self) -> String {
format!("cs_{}", self.get_string_repr())
}
}
| 266 | 2,062 |
hyperswitch | crates/common_utils/src/id_type/profile.rs | .rs | use std::str::FromStr;
crate::id_type!(
ProfileId,
"A type for profile_id that can be used for business profile ids"
);
crate::impl_id_type_methods!(ProfileId, "profile_id");
// This is to display the `ProfileId` as ProfileId(abcd)
crate::impl_debug_id_type!(ProfileId);
crate::impl_try_from_cow_str_id_type!(ProfileId, "profile_id");
crate::impl_generate_id_id_type!(ProfileId, "pro");
crate::impl_serializable_secret_id_type!(ProfileId);
crate::impl_queryable_id_type!(ProfileId);
crate::impl_to_sql_from_sql_id_type!(ProfileId);
impl crate::events::ApiEventMetric for ProfileId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::BusinessProfile {
profile_id: self.clone(),
})
}
}
impl FromStr for ProfileId {
type Err = error_stack::Report<crate::errors::ValidationError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let cow_string = std::borrow::Cow::Owned(s.to_string());
Self::try_from(cow_string)
}
}
// This is implemented so that we can use profile id directly as attribute in metrics
#[cfg(feature = "metrics")]
impl From<ProfileId> for router_env::opentelemetry::Value {
fn from(val: ProfileId) -> Self {
Self::from(val.0 .0 .0)
}
}
| 334 | 2,063 |
hyperswitch | crates/common_utils/src/id_type/global_id/payment.rs | .rs | use common_enums::enums;
use error_stack::ResultExt;
use crate::{errors, generate_id_with_default_len, generate_time_ordered_id_without_prefix, types};
crate::global_id_type!(
GlobalPaymentId,
"A global id that can be used to identify a payment.
The format will be `<cell_id>_<entity_prefix>_<time_ordered_id>`.
Example: `cell1_pay_uu1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p`"
);
// Database related implementations so that this field can be used directly in the database tables
crate::impl_queryable_id_type!(GlobalPaymentId);
crate::impl_to_sql_from_sql_global_id_type!(GlobalPaymentId);
impl GlobalPaymentId {
/// Get string representation of the id
pub fn get_string_repr(&self) -> &str {
self.0.get_string_repr()
}
/// Generate a new GlobalPaymentId from a cell id
pub fn generate(cell_id: &crate::id_type::CellId) -> Self {
let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Payment);
Self(global_id)
}
/// Generate a new ClientId from self
pub fn generate_client_secret(&self) -> types::ClientSecret {
types::ClientSecret::new(self.clone(), generate_time_ordered_id_without_prefix())
}
/// Generate the id for revenue recovery Execute PT workflow
pub fn get_execute_revenue_recovery_id(
&self,
task: &str,
runner: enums::ProcessTrackerRunner,
) -> String {
format!("{task}_{runner}_{}", self.get_string_repr())
}
}
// TODO: refactor the macro to include this id use case as well
impl TryFrom<std::borrow::Cow<'static, str>> for GlobalPaymentId {
type Error = error_stack::Report<errors::ValidationError>;
fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> {
use error_stack::ResultExt;
let merchant_ref_id = super::GlobalId::from_string(value).change_context(
errors::ValidationError::IncorrectValueProvided {
field_name: "payment_id",
},
)?;
Ok(Self(merchant_ref_id))
}
}
crate::global_id_type!(
GlobalAttemptId,
"A global id that can be used to identify a payment attempt"
);
// Database related implementations so that this field can be used directly in the database tables
crate::impl_queryable_id_type!(GlobalAttemptId);
crate::impl_to_sql_from_sql_global_id_type!(GlobalAttemptId);
impl GlobalAttemptId {
/// Generate a new GlobalAttemptId from a cell id
pub fn generate(cell_id: &super::CellId) -> Self {
let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Attempt);
Self(global_id)
}
/// Get string representation of the id
pub fn get_string_repr(&self) -> &str {
self.0.get_string_repr()
}
/// Generate the id for Revenue Recovery Psync PT workflow
pub fn get_psync_revenue_recovery_id(
&self,
task: &str,
runner: enums::ProcessTrackerRunner,
) -> String {
format!("{runner}_{task}_{}", self.get_string_repr())
}
}
impl TryFrom<std::borrow::Cow<'static, str>> for GlobalAttemptId {
type Error = error_stack::Report<errors::ValidationError>;
fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> {
use error_stack::ResultExt;
let global_attempt_id = super::GlobalId::from_string(value).change_context(
errors::ValidationError::IncorrectValueProvided {
field_name: "payment_id",
},
)?;
Ok(Self(global_attempt_id))
}
}
| 842 | 2,064 |
hyperswitch | crates/common_utils/src/id_type/global_id/customer.rs | .rs | use error_stack::ResultExt;
use crate::{errors, generate_id_with_default_len, generate_time_ordered_id_without_prefix, types};
crate::global_id_type!(
GlobalCustomerId,
"A global id that can be used to identify a customer.
The format will be `<cell_id>_<entity_prefix>_<time_ordered_id>`.
Example: `cell1_cus_uu1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p`"
);
// Database related implementations so that this field can be used directly in the database tables
crate::impl_queryable_id_type!(GlobalCustomerId);
crate::impl_to_sql_from_sql_global_id_type!(GlobalCustomerId);
impl GlobalCustomerId {
/// Get string representation of the id
pub fn get_string_repr(&self) -> &str {
self.0.get_string_repr()
}
/// Generate a new GlobalCustomerId from a cell id
pub fn generate(cell_id: &crate::id_type::CellId) -> Self {
let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Customer);
Self(global_id)
}
}
impl TryFrom<GlobalCustomerId> for crate::id_type::CustomerId {
type Error = error_stack::Report<crate::errors::ValidationError>;
fn try_from(value: GlobalCustomerId) -> Result<Self, Self::Error> {
Self::try_from(std::borrow::Cow::from(value.get_string_repr().to_owned()))
}
}
impl crate::events::ApiEventMetric for GlobalCustomerId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::Customer {
customer_id: Some(self.clone()),
})
}
}
| 380 | 2,065 |
hyperswitch | crates/common_utils/src/id_type/global_id/refunds.rs | .rs | use error_stack::ResultExt;
use crate::{errors, generate_id_with_default_len, generate_time_ordered_id_without_prefix, types};
/// A global id that can be used to identify a refund
#[derive(
Debug,
Clone,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Text)]
pub struct GlobalRefundId(super::GlobalId);
// Database related implementations so that this field can be used directly in the database tables
crate::impl_queryable_id_type!(GlobalRefundId);
impl GlobalRefundId {
/// Get string representation of the id
pub fn get_string_repr(&self) -> &str {
self.0.get_string_repr()
}
/// Generate a new GlobalRefundId from a cell id
pub fn generate(cell_id: &crate::id_type::CellId) -> Self {
let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Refund);
Self(global_id)
}
}
// TODO: refactor the macro to include this id use case as well
impl TryFrom<std::borrow::Cow<'static, str>> for GlobalRefundId {
type Error = error_stack::Report<errors::ValidationError>;
fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> {
use error_stack::ResultExt;
let merchant_ref_id = super::GlobalId::from_string(value).change_context(
errors::ValidationError::IncorrectValueProvided {
field_name: "refund_id",
},
)?;
Ok(Self(merchant_ref_id))
}
}
// TODO: refactor the macro to include this id use case as well
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Text, DB> for GlobalRefundId
where
DB: diesel::backend::Backend,
super::GlobalId: 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 GlobalRefundId
where
DB: diesel::backend::Backend,
super::GlobalId: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
super::GlobalId::from_sql(value).map(Self)
}
}
| 586 | 2,066 |
hyperswitch | crates/common_utils/src/id_type/global_id/payment_methods.rs | .rs | use error_stack::ResultExt;
use crate::{
errors::CustomResult,
id_type::global_id::{CellId, GlobalEntity, GlobalId},
};
/// A global id that can be used to identify a payment method
#[derive(
Debug,
Clone,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Text)]
pub struct GlobalPaymentMethodId(GlobalId);
/// A global id that can be used to identify a payment method session
#[derive(
Debug,
Clone,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Text)]
pub struct GlobalPaymentMethodSessionId(GlobalId);
#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
pub enum GlobalPaymentMethodIdError {
#[error("Failed to construct GlobalPaymentMethodId")]
ConstructionError,
}
#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
pub enum GlobalPaymentMethodSessionIdError {
#[error("Failed to construct GlobalPaymentMethodSessionId")]
ConstructionError,
}
impl GlobalPaymentMethodSessionId {
/// Create a new GlobalPaymentMethodSessionId from cell id information
pub fn generate(
cell_id: &CellId,
) -> error_stack::Result<Self, GlobalPaymentMethodSessionIdError> {
let global_id = GlobalId::generate(cell_id, GlobalEntity::PaymentMethodSession);
Ok(Self(global_id))
}
/// Get the string representation of the id
pub fn get_string_repr(&self) -> &str {
self.0.get_string_repr()
}
/// Construct a redis key from the id to be stored in redis
pub fn get_redis_key(&self) -> String {
format!("payment_method_session:{}", self.get_string_repr())
}
}
#[cfg(feature = "v2")]
impl crate::events::ApiEventMetric for GlobalPaymentMethodSessionId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::PaymentMethodSession {
payment_method_session_id: self.clone(),
})
}
}
impl crate::events::ApiEventMetric for GlobalPaymentMethodId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(
crate::events::ApiEventsType::PaymentMethodListForPaymentMethods {
payment_method_id: self.clone(),
},
)
}
}
impl GlobalPaymentMethodId {
/// Create a new GlobalPaymentMethodId from cell id information
pub fn generate(cell_id: &CellId) -> error_stack::Result<Self, GlobalPaymentMethodIdError> {
let global_id = GlobalId::generate(cell_id, GlobalEntity::PaymentMethod);
Ok(Self(global_id))
}
/// Get string representation of the id
pub fn get_string_repr(&self) -> &str {
self.0.get_string_repr()
}
/// Construct a new GlobalPaymentMethodId from a string
pub fn generate_from_string(value: String) -> CustomResult<Self, GlobalPaymentMethodIdError> {
let id = GlobalId::from_string(value.into())
.change_context(GlobalPaymentMethodIdError::ConstructionError)?;
Ok(Self(id))
}
}
impl<DB> diesel::Queryable<diesel::sql_types::Text, DB> for GlobalPaymentMethodId
where
DB: diesel::backend::Backend,
Self: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Text, DB> for GlobalPaymentMethodId
where
DB: diesel::backend::Backend,
GlobalId: 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 GlobalPaymentMethodId
where
DB: diesel::backend::Backend,
GlobalId: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
let global_id = GlobalId::from_sql(value)?;
Ok(Self(global_id))
}
}
impl<DB> diesel::Queryable<diesel::sql_types::Text, DB> for GlobalPaymentMethodSessionId
where
DB: diesel::backend::Backend,
Self: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Text, DB> for GlobalPaymentMethodSessionId
where
DB: diesel::backend::Backend,
GlobalId: 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 GlobalPaymentMethodSessionId
where
DB: diesel::backend::Backend,
GlobalId: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
let global_id = GlobalId::from_sql(value)?;
Ok(Self(global_id))
}
}
| 1,319 | 2,067 |
hyperswitch | crates/common_utils/src/metrics/utils.rs | .rs | //! metric utility functions
use std::time;
use router_env::opentelemetry;
/// Record the time taken by the future to execute
#[inline]
pub async fn time_future<F, R>(future: F) -> (R, time::Duration)
where
F: futures::Future<Output = R>,
{
let start = time::Instant::now();
let result = future.await;
let time_spent = start.elapsed();
(result, time_spent)
}
/// Record the time taken (in seconds) by the operation for the given context
#[inline]
pub async fn record_operation_time<F, R>(
future: F,
metric: &opentelemetry::metrics::Histogram<f64>,
key_value: &[opentelemetry::KeyValue],
) -> R
where
F: futures::Future<Output = R>,
{
let (result, time) = time_future(future).await;
metric.record(time.as_secs_f64(), key_value);
result
}
| 213 | 2,068 |
hyperswitch | crates/hyperswitch_connectors/Cargo.toml | .toml | [package]
name = "hyperswitch_connectors"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[features]
frm = ["hyperswitch_domain_models/frm", "hyperswitch_interfaces/frm"]
payouts = ["hyperswitch_domain_models/payouts", "api_models/payouts", "hyperswitch_interfaces/payouts"]
v1 = ["api_models/v1", "hyperswitch_domain_models/v1", "common_utils/v1"]
v2 = ["api_models/v2", "hyperswitch_domain_models/v2", "common_utils/v2","hyperswitch_interfaces/v2"]
revenue_recovery = ["hyperswitch_interfaces/revenue_recovery","hyperswitch_domain_models/revenue_recovery"]
[dependencies]
actix-http = "3.6.0"
actix-web = "4.5.1"
async-trait = "0.1.79"
base64 = "0.22.0"
bytes = "1.6.0"
encoding_rs = "0.8.33"
error-stack = "0.4.1"
hex = "0.4.3"
http = "0.2.12"
image = { version = "0.25.1", default-features = false, features = ["png"] }
josekit = { git = "https://github.com/sumanmaji4/josekit-rs.git", rev = "5ab54876c29a84f86aef8c169413a46026883efe", features = ["support-empty-payload"]}
mime = "0.3.17"
once_cell = "1.19.0"
qrcode = "0.14.0"
quick-xml = { version = "0.31.0", features = ["serialize"] }
rand = "0.8.5"
regex = "1.10.4"
reqwest = { version = "0.11.27" }
ring = "0.17.8"
roxmltree = "0.19.0"
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
serde_qs = "0.12.0"
serde_urlencoded = "0.7.1"
serde_with = "3.7.0"
sha1 = { version = "0.10.6" }
strum = { version = "0.26", features = ["derive"] }
time = "0.3.35"
url = "2.5.0"
urlencoding = "2.1.3"
uuid = { version = "1.8.0", features = ["v4"] }
lazy_static = "1.4.0"
unicode-normalization = "0.1.21"
html-escape = "0.2"
# First party crates
api_models = { version = "0.1.0", path = "../api_models", features = ["errors"], default-features = false }
cards = { version = "0.1.0", path = "../cards" }
common_enums = { version = "0.1.0", path = "../common_enums" }
common_types = { version = "0.1.0", path = "../common_types" }
common_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext","logs","metrics","crypto_openssl"] }
hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }
hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false }
masking = { version = "0.1.0", path = "../masking" }
router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
[lints]
workspace = true
| 902 | 2,069 |
hyperswitch | crates/hyperswitch_connectors/src/metrics.rs | .rs | //! Metrics interface
use router_env::{counter_metric, global_meter};
global_meter!(GLOBAL_METER, "ROUTER_API");
counter_metric!(CONNECTOR_RESPONSE_DESERIALIZATION_FAILURE, GLOBAL_METER);
| 42 | 2,070 |
hyperswitch | crates/hyperswitch_connectors/src/utils.rs | .rs | use std::{
collections::{HashMap, HashSet},
marker::PhantomData,
str::FromStr,
};
use api_models::payments;
#[cfg(feature = "payouts")]
use api_models::payouts::PayoutVendorAccountDetails;
use base64::Engine;
use common_enums::{
enums,
enums::{
AlbaniaStatesAbbreviation, AndorraStatesAbbreviation, AttemptStatus,
AustriaStatesAbbreviation, BelarusStatesAbbreviation, BelgiumStatesAbbreviation,
BosniaAndHerzegovinaStatesAbbreviation, BulgariaStatesAbbreviation,
CanadaStatesAbbreviation, CroatiaStatesAbbreviation, CzechRepublicStatesAbbreviation,
DenmarkStatesAbbreviation, FinlandStatesAbbreviation, FranceStatesAbbreviation,
FutureUsage, GermanyStatesAbbreviation, GreeceStatesAbbreviation,
HungaryStatesAbbreviation, IcelandStatesAbbreviation, IrelandStatesAbbreviation,
ItalyStatesAbbreviation, LatviaStatesAbbreviation, LiechtensteinStatesAbbreviation,
LithuaniaStatesAbbreviation, LuxembourgStatesAbbreviation, MaltaStatesAbbreviation,
MoldovaStatesAbbreviation, MonacoStatesAbbreviation, MontenegroStatesAbbreviation,
NetherlandsStatesAbbreviation, NorthMacedoniaStatesAbbreviation, NorwayStatesAbbreviation,
PolandStatesAbbreviation, PortugalStatesAbbreviation, RomaniaStatesAbbreviation,
RussiaStatesAbbreviation, SanMarinoStatesAbbreviation, SerbiaStatesAbbreviation,
SlovakiaStatesAbbreviation, SloveniaStatesAbbreviation, SpainStatesAbbreviation,
SwedenStatesAbbreviation, SwitzerlandStatesAbbreviation, UkraineStatesAbbreviation,
UnitedKingdomStatesAbbreviation, UsStatesAbbreviation,
},
};
use common_utils::{
consts::BASE64_ENGINE,
errors::{CustomResult, ParsingError, ReportSwitchExt},
ext_traits::{OptionExt, StringExt, ValueExt},
id_type,
pii::{self, Email, IpAddress},
types::{AmountConvertor, MinorUnit},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
address::{Address, AddressDetails, PhoneDetails},
mandates,
network_tokenization::NetworkTokenNumber,
payment_method_data::{self, Card, CardDetailsForNetworkTransactionId, PaymentMethodData},
router_data::{
ApplePayPredecryptData, ErrorResponse, PaymentMethodToken, RecurringMandatePaymentData,
RouterData as ConnectorRouterData,
},
router_request_types::{
AuthenticationData, BrowserInformation, CompleteAuthorizeData, ConnectorCustomerData,
MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsPostSessionTokensData,
PaymentsPreProcessingData, PaymentsSyncData, RefundsData, ResponseId,
SetupMandateRequestData,
},
router_response_types::{CaptureSyncResponse, PaymentsResponseData},
types::{OrderDetailsWithAmount, SetupMandateRouterData},
};
use hyperswitch_interfaces::{api, consts, errors, types::Response};
use image::{DynamicImage, ImageBuffer, ImageFormat, Luma, Rgba};
use masking::{ExposeInterface, PeekInterface, Secret};
use once_cell::sync::Lazy;
use rand::Rng;
use regex::Regex;
use router_env::logger;
use serde::Deserialize;
use serde_json::Value;
use time::PrimitiveDateTime;
use unicode_normalization::UnicodeNormalization;
use crate::{constants::UNSUPPORTED_ERROR_MESSAGE, types::RefreshTokenRouterData};
type Error = error_stack::Report<errors::ConnectorError>;
pub(crate) fn construct_not_supported_error_report(
capture_method: enums::CaptureMethod,
connector_name: &'static str,
) -> error_stack::Report<errors::ConnectorError> {
errors::ConnectorError::NotSupported {
message: capture_method.to_string(),
connector: connector_name,
}
.into()
}
pub(crate) fn to_currency_base_unit_with_zero_decimal_check(
amount: i64,
currency: enums::Currency,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
currency
.to_currency_base_unit_with_zero_decimal_check(amount)
.change_context(errors::ConnectorError::RequestEncodingFailed)
}
pub(crate) fn get_timestamp_in_milliseconds(datetime: &PrimitiveDateTime) -> i64 {
let utc_datetime = datetime.assume_utc();
utc_datetime.unix_timestamp() * 1000
}
pub(crate) fn get_amount_as_string(
currency_unit: &api::CurrencyUnit,
amount: i64,
currency: enums::Currency,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
let amount = match currency_unit {
api::CurrencyUnit::Minor => amount.to_string(),
api::CurrencyUnit::Base => to_currency_base_unit(amount, currency)?,
};
Ok(amount)
}
pub(crate) fn base64_decode(data: String) -> Result<Vec<u8>, Error> {
BASE64_ENGINE
.decode(data)
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
}
pub(crate) fn to_currency_base_unit(
amount: i64,
currency: enums::Currency,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
currency
.to_currency_base_unit(amount)
.change_context(errors::ConnectorError::ParsingFailed)
}
pub(crate) fn to_currency_lower_unit(
amount: String,
currency: enums::Currency,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
currency
.to_currency_lower_unit(amount)
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
pub trait ConnectorErrorTypeMapping {
fn get_connector_error_type(
&self,
_error_code: String,
_error_message: String,
) -> ConnectorErrorType {
ConnectorErrorType::UnknownError
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ErrorCodeAndMessage {
pub error_code: String,
pub error_message: String,
}
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
//Priority of connector_error_type
pub enum ConnectorErrorType {
UserError = 2,
BusinessError = 3,
TechnicalError = 4,
UnknownError = 1,
}
pub(crate) fn get_error_code_error_message_based_on_priority(
connector: impl ConnectorErrorTypeMapping,
error_list: Vec<ErrorCodeAndMessage>,
) -> Option<ErrorCodeAndMessage> {
let error_type_list = error_list
.iter()
.map(|error| {
connector
.get_connector_error_type(error.error_code.clone(), error.error_message.clone())
})
.collect::<Vec<ConnectorErrorType>>();
let mut error_zip_list = error_list
.iter()
.zip(error_type_list.iter())
.collect::<Vec<(&ErrorCodeAndMessage, &ConnectorErrorType)>>();
error_zip_list.sort_by_key(|&(_, error_type)| error_type);
error_zip_list
.first()
.map(|&(error_code_message, _)| error_code_message)
.cloned()
}
pub trait MultipleCaptureSyncResponse {
fn get_connector_capture_id(&self) -> String;
fn get_capture_attempt_status(&self) -> AttemptStatus;
fn is_capture_response(&self) -> bool;
fn get_connector_reference_id(&self) -> Option<String> {
None
}
fn get_amount_captured(&self) -> Result<Option<MinorUnit>, error_stack::Report<ParsingError>>;
}
pub(crate) fn construct_captures_response_hashmap<T>(
capture_sync_response_list: Vec<T>,
) -> CustomResult<HashMap<String, CaptureSyncResponse>, errors::ConnectorError>
where
T: MultipleCaptureSyncResponse,
{
let mut hashmap = HashMap::new();
for capture_sync_response in capture_sync_response_list {
let connector_capture_id = capture_sync_response.get_connector_capture_id();
if capture_sync_response.is_capture_response() {
hashmap.insert(
connector_capture_id.clone(),
CaptureSyncResponse::Success {
resource_id: ResponseId::ConnectorTransactionId(connector_capture_id),
status: capture_sync_response.get_capture_attempt_status(),
connector_response_reference_id: capture_sync_response
.get_connector_reference_id(),
amount: capture_sync_response
.get_amount_captured()
.change_context(errors::ConnectorError::AmountConversionFailed)
.attach_printable(
"failed to convert back captured response amount to minor unit",
)?,
},
);
}
}
Ok(hashmap)
}
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayWalletData {
#[serde(rename = "type")]
pub pm_type: String,
pub description: String,
pub info: GooglePayPaymentMethodInfo,
pub tokenization_data: GpayTokenizationData,
}
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayPaymentMethodInfo {
pub card_network: String,
pub card_details: String,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct GpayTokenizationData {
#[serde(rename = "type")]
pub token_type: String,
pub token: Secret<String>,
}
impl From<payment_method_data::GooglePayWalletData> for GooglePayWalletData {
fn from(data: payment_method_data::GooglePayWalletData) -> Self {
Self {
pm_type: data.pm_type,
description: data.description,
info: GooglePayPaymentMethodInfo {
card_network: data.info.card_network,
card_details: data.info.card_details,
},
tokenization_data: GpayTokenizationData {
token_type: data.tokenization_data.token_type,
token: Secret::new(data.tokenization_data.token),
},
}
}
}
pub(crate) fn get_amount_as_f64(
currency_unit: &api::CurrencyUnit,
amount: i64,
currency: enums::Currency,
) -> Result<f64, error_stack::Report<errors::ConnectorError>> {
let amount = match currency_unit {
api::CurrencyUnit::Base => to_currency_base_unit_asf64(amount, currency)?,
api::CurrencyUnit::Minor => u32::try_from(amount)
.change_context(errors::ConnectorError::ParsingFailed)?
.into(),
};
Ok(amount)
}
pub(crate) fn to_currency_base_unit_asf64(
amount: i64,
currency: enums::Currency,
) -> Result<f64, error_stack::Report<errors::ConnectorError>> {
currency
.to_currency_base_unit_asf64(amount)
.change_context(errors::ConnectorError::ParsingFailed)
}
pub(crate) fn to_connector_meta_from_secret<T>(
connector_meta: Option<Secret<Value>>,
) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
let connector_meta_secret =
connector_meta.ok_or_else(missing_field_err("connector_meta_data"))?;
let json = connector_meta_secret.expose();
json.parse_value(std::any::type_name::<T>()).switch()
}
pub(crate) fn is_manual_capture(capture_method: Option<enums::CaptureMethod>) -> bool {
capture_method == Some(enums::CaptureMethod::Manual)
|| capture_method == Some(enums::CaptureMethod::ManualMultiple)
}
pub(crate) fn generate_random_bytes(length: usize) -> Vec<u8> {
// returns random bytes of length n
let mut rng = rand::thread_rng();
(0..length).map(|_| Rng::gen(&mut rng)).collect()
}
pub(crate) fn missing_field_err(
message: &'static str,
) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + 'static> {
Box::new(move || {
errors::ConnectorError::MissingRequiredField {
field_name: message,
}
.into()
})
}
pub(crate) fn handle_json_response_deserialization_failure(
res: Response,
connector: &'static str,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
crate::metrics::CONNECTOR_RESPONSE_DESERIALIZATION_FAILURE
.add(1, router_env::metric_attributes!(("connector", connector)));
let response_data = String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
// check for whether the response is in json format
match serde_json::from_str::<Value>(&response_data) {
// in case of unexpected response but in json format
Ok(_) => Err(errors::ConnectorError::ResponseDeserializationFailed)?,
// in case of unexpected response but in html or string format
Err(error_msg) => {
logger::error!(deserialization_error=?error_msg);
logger::error!("UNEXPECTED RESPONSE FROM CONNECTOR: {}", response_data);
Ok(ErrorResponse {
status_code: res.status_code,
code: consts::NO_ERROR_CODE.to_string(),
message: UNSUPPORTED_ERROR_MESSAGE.to_string(),
reason: Some(response_data),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
}
pub(crate) fn construct_not_implemented_error_report(
capture_method: enums::CaptureMethod,
connector_name: &str,
) -> error_stack::Report<errors::ConnectorError> {
errors::ConnectorError::NotImplemented(format!("{} for {}", capture_method, connector_name))
.into()
}
pub(crate) const SELECTED_PAYMENT_METHOD: &str = "Selected payment method";
pub(crate) fn get_unimplemented_payment_method_error_message(connector: &str) -> String {
format!("{} through {}", SELECTED_PAYMENT_METHOD, connector)
}
pub(crate) fn to_connector_meta<T>(connector_meta: Option<Value>) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
let json = connector_meta.ok_or_else(missing_field_err("connector_meta_data"))?;
json.parse_value(std::any::type_name::<T>()).switch()
}
pub(crate) fn convert_amount<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<T, error_stack::Report<errors::ConnectorError>> {
amount_convertor
.convert(amount, currency)
.change_context(errors::ConnectorError::AmountConversionFailed)
}
pub(crate) fn validate_currency(
request_currency: enums::Currency,
merchant_config_currency: Option<enums::Currency>,
) -> Result<(), errors::ConnectorError> {
let merchant_config_currency =
merchant_config_currency.ok_or(errors::ConnectorError::NoConnectorMetaData)?;
if request_currency != merchant_config_currency {
Err(errors::ConnectorError::NotSupported {
message: format!(
"currency {} is not supported for this merchant account",
request_currency
),
connector: "Braintree",
})?
}
Ok(())
}
pub(crate) fn convert_back_amount_to_minor_units<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
amount: T,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>> {
amount_convertor
.convert_back(amount, currency)
.change_context(errors::ConnectorError::AmountConversionFailed)
}
pub(crate) fn is_payment_failure(status: AttemptStatus) -> bool {
match status {
AttemptStatus::AuthenticationFailed
| AttemptStatus::AuthorizationFailed
| AttemptStatus::CaptureFailed
| AttemptStatus::VoidFailed
| AttemptStatus::Failure => true,
AttemptStatus::Started
| AttemptStatus::RouterDeclined
| AttemptStatus::AuthenticationPending
| AttemptStatus::AuthenticationSuccessful
| AttemptStatus::Authorized
| AttemptStatus::Charged
| AttemptStatus::Authorizing
| AttemptStatus::CodInitiated
| AttemptStatus::Voided
| AttemptStatus::VoidInitiated
| AttemptStatus::CaptureInitiated
| AttemptStatus::AutoRefunded
| AttemptStatus::PartialCharged
| AttemptStatus::PartialChargedAndChargeable
| AttemptStatus::Unresolved
| AttemptStatus::Pending
| AttemptStatus::PaymentMethodAwaited
| AttemptStatus::ConfirmationAwaited
| AttemptStatus::DeviceDataCollectionPending => false,
}
}
pub fn is_refund_failure(status: enums::RefundStatus) -> bool {
match status {
common_enums::RefundStatus::Failure | common_enums::RefundStatus::TransactionFailure => {
true
}
common_enums::RefundStatus::ManualReview
| common_enums::RefundStatus::Pending
| common_enums::RefundStatus::Success => false,
}
}
// TODO: Make all traits as `pub(crate) trait` once all connectors are moved.
pub trait RouterData {
fn get_billing(&self) -> Result<&Address, Error>;
fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error>;
fn get_billing_phone(&self) -> Result<&PhoneDetails, Error>;
fn get_description(&self) -> Result<String, Error>;
fn get_billing_address(&self) -> Result<&AddressDetails, Error>;
fn get_shipping_address(&self) -> Result<&AddressDetails, Error>;
fn get_shipping_address_with_phone_number(&self) -> Result<&Address, Error>;
fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error>;
fn get_session_token(&self) -> Result<String, Error>;
fn get_billing_first_name(&self) -> Result<Secret<String>, Error>;
fn get_billing_full_name(&self) -> Result<Secret<String>, Error>;
fn get_billing_last_name(&self) -> Result<Secret<String>, Error>;
fn get_billing_line1(&self) -> Result<Secret<String>, Error>;
fn get_billing_line2(&self) -> Result<Secret<String>, Error>;
fn get_billing_zip(&self) -> Result<Secret<String>, Error>;
fn get_billing_state(&self) -> Result<Secret<String>, Error>;
fn get_billing_state_code(&self) -> Result<Secret<String>, Error>;
fn get_billing_city(&self) -> Result<String, Error>;
fn get_billing_email(&self) -> Result<Email, Error>;
fn get_billing_phone_number(&self) -> Result<Secret<String>, Error>;
fn to_connector_meta<T>(&self) -> Result<T, Error>
where
T: serde::de::DeserializeOwned;
fn is_three_ds(&self) -> bool;
fn get_payment_method_token(&self) -> Result<PaymentMethodToken, Error>;
fn get_customer_id(&self) -> Result<id_type::CustomerId, Error>;
fn get_connector_customer_id(&self) -> Result<String, Error>;
fn get_preprocessing_id(&self) -> Result<String, Error>;
fn get_recurring_mandate_payment_data(&self) -> Result<RecurringMandatePaymentData, Error>;
#[cfg(feature = "payouts")]
fn get_payout_method_data(&self) -> Result<api_models::payouts::PayoutMethodData, Error>;
#[cfg(feature = "payouts")]
fn get_quote_id(&self) -> Result<String, Error>;
fn get_optional_billing(&self) -> Option<&Address>;
fn get_optional_shipping(&self) -> Option<&Address>;
fn get_optional_shipping_line1(&self) -> Option<Secret<String>>;
fn get_optional_shipping_line2(&self) -> Option<Secret<String>>;
fn get_optional_shipping_city(&self) -> Option<String>;
fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2>;
fn get_optional_shipping_zip(&self) -> Option<Secret<String>>;
fn get_optional_shipping_state(&self) -> Option<Secret<String>>;
fn get_optional_shipping_first_name(&self) -> Option<Secret<String>>;
fn get_optional_shipping_last_name(&self) -> Option<Secret<String>>;
fn get_optional_shipping_full_name(&self) -> Option<Secret<String>>;
fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>>;
fn get_optional_shipping_email(&self) -> Option<Email>;
fn get_optional_billing_full_name(&self) -> Option<Secret<String>>;
fn get_optional_billing_line1(&self) -> Option<Secret<String>>;
fn get_optional_billing_line2(&self) -> Option<Secret<String>>;
fn get_optional_billing_city(&self) -> Option<String>;
fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2>;
fn get_optional_billing_zip(&self) -> Option<Secret<String>>;
fn get_optional_billing_state(&self) -> Option<Secret<String>>;
fn get_optional_billing_state_2_digit(&self) -> Option<Secret<String>>;
fn get_optional_billing_first_name(&self) -> Option<Secret<String>>;
fn get_optional_billing_last_name(&self) -> Option<Secret<String>>;
fn get_optional_billing_phone_number(&self) -> Option<Secret<String>>;
fn get_optional_billing_email(&self) -> Option<Email>;
}
impl<Flow, Request, Response> RouterData
for hyperswitch_domain_models::router_data::RouterData<Flow, Request, Response>
{
fn get_billing(&self) -> Result<&Address, Error> {
self.address
.get_payment_method_billing()
.ok_or_else(missing_field_err("billing"))
}
fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error> {
self.address
.get_payment_method_billing()
.and_then(|a| a.address.as_ref())
.and_then(|ad| ad.country)
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.country",
))
}
fn get_billing_phone(&self) -> Result<&PhoneDetails, Error> {
self.address
.get_payment_method_billing()
.and_then(|a| a.phone.as_ref())
.ok_or_else(missing_field_err("billing.phone"))
}
fn get_optional_billing(&self) -> Option<&Address> {
self.address.get_payment_method_billing()
}
fn get_optional_shipping(&self) -> Option<&Address> {
self.address.get_shipping()
}
fn get_optional_shipping_first_name(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.first_name)
})
}
fn get_optional_shipping_last_name(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.last_name)
})
}
fn get_optional_shipping_full_name(&self) -> Option<Secret<String>> {
self.get_optional_shipping()
.and_then(|shipping_details| shipping_details.address.as_ref())
.and_then(|shipping_address| shipping_address.get_optional_full_name())
}
fn get_optional_shipping_line1(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.line1)
})
}
fn get_optional_shipping_line2(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.line2)
})
}
fn get_optional_shipping_city(&self) -> Option<String> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.city)
})
}
fn get_optional_shipping_state(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.state)
})
}
fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.country)
})
}
fn get_optional_shipping_zip(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.zip)
})
}
fn get_optional_shipping_email(&self) -> Option<Email> {
self.address
.get_shipping()
.and_then(|shipping_address| shipping_address.clone().email)
}
fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>> {
self.address
.get_shipping()
.and_then(|shipping_address| shipping_address.clone().phone)
.and_then(|phone_details| phone_details.get_number_with_country_code().ok())
}
fn get_description(&self) -> Result<String, Error> {
self.description
.clone()
.ok_or_else(missing_field_err("description"))
}
fn get_billing_address(&self) -> Result<&AddressDetails, Error> {
self.address
.get_payment_method_billing()
.as_ref()
.and_then(|a| a.address.as_ref())
.ok_or_else(missing_field_err("billing.address"))
}
fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error> {
self.connector_meta_data
.clone()
.ok_or_else(missing_field_err("connector_meta_data"))
}
fn get_session_token(&self) -> Result<String, Error> {
self.session_token
.clone()
.ok_or_else(missing_field_err("session_token"))
}
fn get_billing_first_name(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.first_name.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.first_name",
))
}
fn get_billing_full_name(&self) -> Result<Secret<String>, Error> {
self.get_optional_billing()
.and_then(|billing_details| billing_details.address.as_ref())
.and_then(|billing_address| billing_address.get_optional_full_name())
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.first_name",
))
}
fn get_billing_last_name(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.last_name.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.last_name",
))
}
fn get_billing_line1(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.line1.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.line1",
))
}
fn get_billing_line2(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.line2.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.line2",
))
}
fn get_billing_zip(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.zip.clone())
})
.ok_or_else(missing_field_err("payment_method_data.billing.address.zip"))
}
fn get_billing_state(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.state.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.state",
))
}
fn get_billing_state_code(&self) -> Result<Secret<String>, Error> {
let country = self.get_billing_country()?;
let state = self.get_billing_state()?;
match country {
api_models::enums::CountryAlpha2::US => Ok(Secret::new(
UsStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::CA => Ok(Secret::new(
CanadaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
_ => Ok(state.clone()),
}
}
fn get_billing_city(&self) -> Result<String, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.city)
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.city",
))
}
fn get_billing_email(&self) -> Result<Email, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| billing_address.email.clone())
.ok_or_else(missing_field_err("payment_method_data.billing.email"))
}
fn get_billing_phone_number(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| billing_address.clone().phone)
.map(|phone_details| phone_details.get_number_with_country_code())
.transpose()?
.ok_or_else(missing_field_err("payment_method_data.billing.phone"))
}
fn get_optional_billing_line1(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.line1)
})
}
fn get_optional_billing_line2(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.line2)
})
}
fn get_optional_billing_city(&self) -> Option<String> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.city)
})
}
fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.country)
})
}
fn get_optional_billing_zip(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.zip)
})
}
fn get_optional_billing_state(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.state)
})
}
fn get_optional_billing_state_2_digit(&self) -> Option<Secret<String>> {
self.get_optional_billing_state().and_then(|state| {
if state.clone().expose().len() != 2 {
None
} else {
Some(state)
}
})
}
fn get_optional_billing_first_name(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.first_name)
})
}
fn get_optional_billing_last_name(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.last_name)
})
}
fn get_optional_billing_phone_number(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.phone
.and_then(|phone_data| phone_data.number)
})
}
fn get_optional_billing_email(&self) -> Option<Email> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| billing_address.clone().email)
}
fn to_connector_meta<T>(&self) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
self.get_connector_meta()?
.parse_value(std::any::type_name::<T>())
.change_context(errors::ConnectorError::NoConnectorMetaData)
}
fn is_three_ds(&self) -> bool {
matches!(self.auth_type, enums::AuthenticationType::ThreeDs)
}
fn get_shipping_address(&self) -> Result<&AddressDetails, Error> {
self.address
.get_shipping()
.and_then(|a| a.address.as_ref())
.ok_or_else(missing_field_err("shipping.address"))
}
fn get_shipping_address_with_phone_number(&self) -> Result<&Address, Error> {
self.address
.get_shipping()
.ok_or_else(missing_field_err("shipping"))
}
fn get_payment_method_token(&self) -> Result<PaymentMethodToken, Error> {
self.payment_method_token
.clone()
.ok_or_else(missing_field_err("payment_method_token"))
}
fn get_customer_id(&self) -> Result<id_type::CustomerId, Error> {
self.customer_id
.to_owned()
.ok_or_else(missing_field_err("customer_id"))
}
fn get_connector_customer_id(&self) -> Result<String, Error> {
self.connector_customer
.to_owned()
.ok_or_else(missing_field_err("connector_customer_id"))
}
fn get_preprocessing_id(&self) -> Result<String, Error> {
self.preprocessing_id
.to_owned()
.ok_or_else(missing_field_err("preprocessing_id"))
}
fn get_recurring_mandate_payment_data(&self) -> Result<RecurringMandatePaymentData, Error> {
self.recurring_mandate_payment_data
.to_owned()
.ok_or_else(missing_field_err("recurring_mandate_payment_data"))
}
fn get_optional_billing_full_name(&self) -> Option<Secret<String>> {
self.get_optional_billing()
.and_then(|billing_details| billing_details.address.as_ref())
.and_then(|billing_address| billing_address.get_optional_full_name())
}
#[cfg(feature = "payouts")]
fn get_payout_method_data(&self) -> Result<api_models::payouts::PayoutMethodData, Error> {
self.payout_method_data
.to_owned()
.ok_or_else(missing_field_err("payout_method_data"))
}
#[cfg(feature = "payouts")]
fn get_quote_id(&self) -> Result<String, Error> {
self.quote_id
.to_owned()
.ok_or_else(missing_field_err("quote_id"))
}
}
pub trait AccessTokenRequestInfo {
fn get_request_id(&self) -> Result<Secret<String>, Error>;
}
impl AccessTokenRequestInfo for RefreshTokenRouterData {
fn get_request_id(&self) -> Result<Secret<String>, Error> {
self.request
.id
.clone()
.ok_or_else(missing_field_err("request.id"))
}
}
pub trait ApplePayDecrypt {
fn get_expiry_month(&self) -> Result<Secret<String>, Error>;
fn get_four_digit_expiry_year(&self) -> Result<Secret<String>, Error>;
}
impl ApplePayDecrypt for Box<ApplePayPredecryptData> {
fn get_four_digit_expiry_year(&self) -> Result<Secret<String>, Error> {
Ok(Secret::new(format!(
"20{}",
self.application_expiration_date
.get(0..2)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
)))
}
fn get_expiry_month(&self) -> Result<Secret<String>, Error> {
Ok(Secret::new(
self.application_expiration_date
.get(2..4)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_owned(),
))
}
}
#[derive(Debug, Copy, Clone, strum::Display, Eq, Hash, PartialEq)]
pub enum CardIssuer {
AmericanExpress,
Master,
Maestro,
Visa,
Discover,
DinersClub,
JCB,
CarteBlanche,
}
pub trait CardData {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>;
fn get_card_expiry_month_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>;
fn get_card_issuer(&self) -> Result<CardIssuer, Error>;
fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError>;
fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String>;
fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String>;
fn get_expiry_year_4_digit(&self) -> Secret<String>;
fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError>;
fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError>;
fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error>;
fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error>;
fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error>;
fn get_cardholder_name(&self) -> Result<Secret<String>, Error>;
}
impl CardData for Card {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding = self.card_exp_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
fn get_card_expiry_month_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let exp_month = self
.card_exp_month
.peek()
.to_string()
.parse::<u8>()
.map_err(|_| errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_month",
})?;
let month = ::cards::CardExpirationMonth::try_from(exp_month).map_err(|_| {
errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_month",
}
})?;
Ok(Secret::new(month.two_digits()))
}
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.card_number.peek())
}
fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
self.card_exp_month.peek(),
delimiter,
year.peek()
)))
}
fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
year.peek(),
delimiter,
self.card_exp_month.peek()
))
}
fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
self.card_exp_month.peek(),
delimiter,
year.peek()
))
}
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.card_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{}", year);
}
Secret::new(year)
}
fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.card_exp_month.clone().expose();
Ok(Secret::new(format!("{year}{month}")))
}
fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.card_exp_month.clone().expose();
Ok(Secret::new(format!("{month}{year}")))
}
fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> {
self.card_exp_month
.peek()
.clone()
.parse::<i8>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> {
self.card_exp_year
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error> {
self.get_expiry_year_4_digit()
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_cardholder_name(&self) -> Result<Secret<String>, Error> {
self.card_holder_name
.clone()
.ok_or_else(missing_field_err("card.card_holder_name"))
}
}
impl CardData for CardDetailsForNetworkTransactionId {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding = self.card_exp_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
fn get_card_expiry_month_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let exp_month = self
.card_exp_month
.peek()
.to_string()
.parse::<u8>()
.map_err(|_| errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_month",
})?;
let month = ::cards::CardExpirationMonth::try_from(exp_month).map_err(|_| {
errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_month",
}
})?;
Ok(Secret::new(month.two_digits()))
}
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.card_number.peek())
}
fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
self.card_exp_month.peek(),
delimiter,
year.peek()
)))
}
fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
year.peek(),
delimiter,
self.card_exp_month.peek()
))
}
fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
self.card_exp_month.peek(),
delimiter,
year.peek()
))
}
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.card_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{}", year);
}
Secret::new(year)
}
fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.card_exp_month.clone().expose();
Ok(Secret::new(format!("{year}{month}")))
}
fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.card_exp_month.clone().expose();
Ok(Secret::new(format!("{month}{year}")))
}
fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> {
self.card_exp_month
.peek()
.clone()
.parse::<i8>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> {
self.card_exp_year
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error> {
self.get_expiry_year_4_digit()
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_cardholder_name(&self) -> Result<Secret<String>, Error> {
self.card_holder_name
.clone()
.ok_or_else(missing_field_err("card.card_holder_name"))
}
}
#[track_caller]
fn get_card_issuer(card_number: &str) -> Result<CardIssuer, Error> {
for (k, v) in CARD_REGEX.iter() {
let regex: Regex = v
.clone()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
if regex.is_match(card_number) {
return Ok(*k);
}
}
Err(error_stack::Report::new(
errors::ConnectorError::NotImplemented("Card Type".into()),
))
}
static CARD_REGEX: Lazy<HashMap<CardIssuer, Result<Regex, regex::Error>>> = Lazy::new(|| {
let mut map = HashMap::new();
// Reference: https://gist.github.com/michaelkeevildown/9096cd3aac9029c4e6e05588448a8841
// [#379]: Determine card issuer from card BIN number
map.insert(CardIssuer::Master, Regex::new(r"^5[1-5][0-9]{14}$"));
map.insert(CardIssuer::AmericanExpress, Regex::new(r"^3[47][0-9]{13}$"));
map.insert(CardIssuer::Visa, Regex::new(r"^4[0-9]{12}(?:[0-9]{3})?$"));
map.insert(CardIssuer::Discover, Regex::new(r"^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$"));
map.insert(
CardIssuer::Maestro,
Regex::new(r"^(5018|5020|5038|5893|6304|6759|6761|6762|6763)[0-9]{8,15}$"),
);
map.insert(
CardIssuer::DinersClub,
Regex::new(r"^3(?:0[0-5]|[68][0-9])[0-9]{11}$"),
);
map.insert(
CardIssuer::JCB,
Regex::new(r"^(3(?:088|096|112|158|337|5(?:2[89]|[3-8][0-9]))\d{12})$"),
);
map.insert(CardIssuer::CarteBlanche, Regex::new(r"^389[0-9]{11}$"));
map
});
pub trait AddressDetailsData {
fn get_first_name(&self) -> Result<&Secret<String>, Error>;
fn get_last_name(&self) -> Result<&Secret<String>, Error>;
fn get_full_name(&self) -> Result<Secret<String>, Error>;
fn get_line1(&self) -> Result<&Secret<String>, Error>;
fn get_city(&self) -> Result<&String, Error>;
fn get_line2(&self) -> Result<&Secret<String>, Error>;
fn get_state(&self) -> Result<&Secret<String>, Error>;
fn get_zip(&self) -> Result<&Secret<String>, Error>;
fn get_country(&self) -> Result<&api_models::enums::CountryAlpha2, Error>;
fn get_combined_address_line(&self) -> Result<Secret<String>, Error>;
fn to_state_code(&self) -> Result<Secret<String>, Error>;
fn to_state_code_as_optional(&self) -> Result<Option<Secret<String>>, Error>;
fn get_optional_city(&self) -> Option<String>;
fn get_optional_line1(&self) -> Option<Secret<String>>;
fn get_optional_line2(&self) -> Option<Secret<String>>;
fn get_optional_line3(&self) -> Option<Secret<String>>;
fn get_optional_first_name(&self) -> Option<Secret<String>>;
fn get_optional_last_name(&self) -> Option<Secret<String>>;
fn get_optional_country(&self) -> Option<api_models::enums::CountryAlpha2>;
fn get_optional_zip(&self) -> Option<Secret<String>>;
fn get_optional_state(&self) -> Option<Secret<String>>;
}
impl AddressDetailsData for AddressDetails {
fn get_first_name(&self) -> Result<&Secret<String>, Error> {
self.first_name
.as_ref()
.ok_or_else(missing_field_err("address.first_name"))
}
fn get_last_name(&self) -> Result<&Secret<String>, Error> {
self.last_name
.as_ref()
.ok_or_else(missing_field_err("address.last_name"))
}
fn get_full_name(&self) -> Result<Secret<String>, Error> {
let first_name = self.get_first_name()?.peek().to_owned();
let last_name = self
.get_last_name()
.ok()
.cloned()
.unwrap_or(Secret::new("".to_string()));
let last_name = last_name.peek();
let full_name = format!("{} {}", first_name, last_name).trim().to_string();
Ok(Secret::new(full_name))
}
fn get_line1(&self) -> Result<&Secret<String>, Error> {
self.line1
.as_ref()
.ok_or_else(missing_field_err("address.line1"))
}
fn get_city(&self) -> Result<&String, Error> {
self.city
.as_ref()
.ok_or_else(missing_field_err("address.city"))
}
fn get_state(&self) -> Result<&Secret<String>, Error> {
self.state
.as_ref()
.ok_or_else(missing_field_err("address.state"))
}
fn get_line2(&self) -> Result<&Secret<String>, Error> {
self.line2
.as_ref()
.ok_or_else(missing_field_err("address.line2"))
}
fn get_zip(&self) -> Result<&Secret<String>, Error> {
self.zip
.as_ref()
.ok_or_else(missing_field_err("address.zip"))
}
fn get_country(&self) -> Result<&api_models::enums::CountryAlpha2, Error> {
self.country
.as_ref()
.ok_or_else(missing_field_err("address.country"))
}
fn get_combined_address_line(&self) -> Result<Secret<String>, Error> {
Ok(Secret::new(format!(
"{},{}",
self.get_line1()?.peek(),
self.get_line2()?.peek()
)))
}
fn to_state_code(&self) -> Result<Secret<String>, Error> {
let country = self.get_country()?;
let state = self.get_state()?;
match country {
api_models::enums::CountryAlpha2::US => Ok(Secret::new(
UsStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::CA => Ok(Secret::new(
CanadaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::AL => Ok(Secret::new(
AlbaniaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::AD => Ok(Secret::new(
AndorraStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::AT => Ok(Secret::new(
AustriaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::BY => Ok(Secret::new(
BelarusStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::BA => Ok(Secret::new(
BosniaAndHerzegovinaStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::BG => Ok(Secret::new(
BulgariaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::HR => Ok(Secret::new(
CroatiaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::CZ => Ok(Secret::new(
CzechRepublicStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::DK => Ok(Secret::new(
DenmarkStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::FI => Ok(Secret::new(
FinlandStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::FR => Ok(Secret::new(
FranceStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::DE => Ok(Secret::new(
GermanyStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::GR => Ok(Secret::new(
GreeceStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::HU => Ok(Secret::new(
HungaryStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::IS => Ok(Secret::new(
IcelandStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::IE => Ok(Secret::new(
IrelandStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::LV => Ok(Secret::new(
LatviaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::IT => Ok(Secret::new(
ItalyStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::LI => Ok(Secret::new(
LiechtensteinStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::LT => Ok(Secret::new(
LithuaniaStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::MT => Ok(Secret::new(
MaltaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::MD => Ok(Secret::new(
MoldovaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::MC => Ok(Secret::new(
MonacoStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::ME => Ok(Secret::new(
MontenegroStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::NL => Ok(Secret::new(
NetherlandsStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::MK => Ok(Secret::new(
NorthMacedoniaStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::NO => Ok(Secret::new(
NorwayStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::PL => Ok(Secret::new(
PolandStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::PT => Ok(Secret::new(
PortugalStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::ES => Ok(Secret::new(
SpainStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::CH => Ok(Secret::new(
SwitzerlandStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::GB => Ok(Secret::new(
UnitedKingdomStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
_ => Ok(state.clone()),
}
}
fn to_state_code_as_optional(&self) -> Result<Option<Secret<String>>, Error> {
self.state
.as_ref()
.map(|state| {
if state.peek().len() == 2 {
Ok(state.to_owned())
} else {
self.to_state_code()
}
})
.transpose()
}
fn get_optional_city(&self) -> Option<String> {
self.city.clone()
}
fn get_optional_line1(&self) -> Option<Secret<String>> {
self.line1.clone()
}
fn get_optional_line2(&self) -> Option<Secret<String>> {
self.line2.clone()
}
fn get_optional_first_name(&self) -> Option<Secret<String>> {
self.first_name.clone()
}
fn get_optional_last_name(&self) -> Option<Secret<String>> {
self.last_name.clone()
}
fn get_optional_country(&self) -> Option<api_models::enums::CountryAlpha2> {
self.country
}
fn get_optional_line3(&self) -> Option<Secret<String>> {
self.line3.clone()
}
fn get_optional_zip(&self) -> Option<Secret<String>> {
self.zip.clone()
}
fn get_optional_state(&self) -> Option<Secret<String>> {
self.state.clone()
}
}
pub trait AdditionalCardInfo {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>;
}
impl AdditionalCardInfo for payments::AdditionalCardInfo {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding =
self.card_exp_year
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "card_exp_year",
})?;
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
}
pub trait PhoneDetailsData {
fn get_number(&self) -> Result<Secret<String>, Error>;
fn get_country_code(&self) -> Result<String, Error>;
fn get_number_with_country_code(&self) -> Result<Secret<String>, Error>;
fn get_number_with_hash_country_code(&self) -> Result<Secret<String>, Error>;
fn extract_country_code(&self) -> Result<String, Error>;
}
impl PhoneDetailsData for PhoneDetails {
fn get_country_code(&self) -> Result<String, Error> {
self.country_code
.clone()
.ok_or_else(missing_field_err("billing.phone.country_code"))
}
fn extract_country_code(&self) -> Result<String, Error> {
self.get_country_code()
.map(|cc| cc.trim_start_matches('+').to_string())
}
fn get_number(&self) -> Result<Secret<String>, Error> {
self.number
.clone()
.ok_or_else(missing_field_err("billing.phone.number"))
}
fn get_number_with_country_code(&self) -> Result<Secret<String>, Error> {
let number = self.get_number()?;
let country_code = self.get_country_code()?;
Ok(Secret::new(format!("{}{}", country_code, number.peek())))
}
fn get_number_with_hash_country_code(&self) -> Result<Secret<String>, Error> {
let number = self.get_number()?;
let country_code = self.get_country_code()?;
let number_without_plus = country_code.trim_start_matches('+');
Ok(Secret::new(format!(
"{}#{}",
number_without_plus,
number.peek()
)))
}
}
#[cfg(feature = "payouts")]
pub trait PayoutFulfillRequestData {
fn get_connector_payout_id(&self) -> Result<String, Error>;
fn get_connector_transfer_method_id(&self) -> Result<String, Error>;
}
#[cfg(feature = "payouts")]
impl PayoutFulfillRequestData for hyperswitch_domain_models::router_request_types::PayoutsData {
fn get_connector_payout_id(&self) -> Result<String, Error> {
self.connector_payout_id
.clone()
.ok_or_else(missing_field_err("connector_payout_id"))
}
fn get_connector_transfer_method_id(&self) -> Result<String, Error> {
self.connector_transfer_method_id
.clone()
.ok_or_else(missing_field_err("connector_transfer_method_id"))
}
}
pub trait CustomerData {
fn get_email(&self) -> Result<Email, Error>;
}
impl CustomerData for ConnectorCustomerData {
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
}
pub trait PaymentsAuthorizeRequestData {
fn get_optional_language_from_browser_info(&self) -> Option<String>;
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_email(&self) -> Result<Email, Error>;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>;
fn get_card(&self) -> Result<Card, Error>;
fn connector_mandate_id(&self) -> Option<String>;
fn is_mandate_payment(&self) -> bool;
fn is_customer_initiated_mandate_payment(&self) -> bool;
fn get_webhook_url(&self) -> Result<String, Error>;
fn get_router_return_url(&self) -> Result<String, Error>;
fn is_wallet(&self) -> bool;
fn is_card(&self) -> bool;
fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>;
fn get_connector_mandate_id(&self) -> Result<String, Error>;
fn get_complete_authorize_url(&self) -> Result<String, Error>;
fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>>;
fn get_original_amount(&self) -> i64;
fn get_surcharge_amount(&self) -> Option<i64>;
fn get_tax_on_surcharge_amount(&self) -> Option<i64>;
fn get_total_surcharge_amount(&self) -> Option<i64>;
fn get_metadata_as_object(&self) -> Option<pii::SecretSerdeValue>;
fn get_authentication_data(&self) -> Result<AuthenticationData, Error>;
fn get_customer_name(&self) -> Result<Secret<String>, Error>;
fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error>;
fn get_card_holder_name_from_additional_payment_method_data(
&self,
) -> Result<Secret<String>, Error>;
fn is_cit_mandate_payment(&self) -> bool;
fn get_optional_network_transaction_id(&self) -> Option<String>;
fn get_optional_email(&self) -> Option<Email>;
fn get_card_network_from_additional_payment_method_data(
&self,
) -> Result<enums::CardNetwork, Error>;
}
impl PaymentsAuthorizeRequestData for PaymentsAuthorizeData {
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_optional_language_from_browser_info(&self) -> Option<String> {
self.browser_info
.clone()
.and_then(|browser_info| browser_info.language)
}
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> {
self.order_details
.clone()
.ok_or_else(missing_field_err("order_details"))
}
fn get_card(&self) -> Result<Card, Error> {
match self.payment_method_data.clone() {
PaymentMethodData::Card(card) => Ok(card),
_ => Err(missing_field_err("card")()),
}
}
fn get_complete_authorize_url(&self) -> Result<String, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
}
fn connector_mandate_id(&self) -> Option<String> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
connector_mandate_ids.get_connector_mandate_id()
}
Some(payments::MandateReferenceId::NetworkMandateId(_))
| None
| Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None,
})
}
fn is_mandate_payment(&self) -> bool {
((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& (self.setup_future_usage == Some(FutureUsage::OffSession)))
|| self
.mandate_id
.as_ref()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref())
.is_some()
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
fn get_router_return_url(&self) -> Result<String, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("return_url"))
}
fn is_wallet(&self) -> bool {
matches!(self.payment_method_data, PaymentMethodData::Wallet(_))
}
fn is_card(&self) -> bool {
matches!(self.payment_method_data, PaymentMethodData::Card(_))
}
fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> {
self.payment_method_type
.to_owned()
.ok_or_else(missing_field_err("payment_method_type"))
}
fn get_connector_mandate_id(&self) -> Result<String, Error> {
self.connector_mandate_id()
.ok_or_else(missing_field_err("connector_mandate_id"))
}
fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>> {
self.browser_info.clone().and_then(|browser_info| {
browser_info
.ip_address
.map(|ip| Secret::new(ip.to_string()))
})
}
fn get_original_amount(&self) -> i64 {
self.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.original_amount.get_amount_as_i64())
.unwrap_or(self.amount)
}
fn get_surcharge_amount(&self) -> Option<i64> {
self.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.surcharge_amount.get_amount_as_i64())
}
fn get_tax_on_surcharge_amount(&self) -> Option<i64> {
self.surcharge_details.as_ref().map(|surcharge_details| {
surcharge_details
.tax_on_surcharge_amount
.get_amount_as_i64()
})
}
fn get_total_surcharge_amount(&self) -> Option<i64> {
self.surcharge_details.as_ref().map(|surcharge_details| {
surcharge_details
.get_total_surcharge_amount()
.get_amount_as_i64()
})
}
fn is_customer_initiated_mandate_payment(&self) -> bool {
(self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& self.setup_future_usage == Some(FutureUsage::OffSession)
}
fn get_metadata_as_object(&self) -> Option<pii::SecretSerdeValue> {
self.metadata.clone().and_then(|meta_data| match meta_data {
Value::Null
| Value::Bool(_)
| Value::Number(_)
| Value::String(_)
| Value::Array(_) => None,
Value::Object(_) => Some(meta_data.into()),
})
}
fn get_authentication_data(&self) -> Result<AuthenticationData, Error> {
self.authentication_data
.clone()
.ok_or_else(missing_field_err("authentication_data"))
}
fn get_customer_name(&self) -> Result<Secret<String>, Error> {
self.customer_name
.clone()
.ok_or_else(missing_field_err("customer_name"))
}
fn get_card_holder_name_from_additional_payment_method_data(
&self,
) -> Result<Secret<String>, Error> {
match &self.additional_payment_method_data {
Some(payments::AdditionalPaymentData::Card(card_data)) => Ok(card_data
.card_holder_name
.clone()
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "card_holder_name",
})?),
_ => Err(errors::ConnectorError::MissingRequiredFields {
field_names: vec!["card_holder_name"],
}
.into()),
}
}
/// Attempts to retrieve the connector mandate reference ID as a `Result<String, Error>`.
fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
connector_mandate_ids.get_connector_mandate_request_reference_id()
}
Some(payments::MandateReferenceId::NetworkMandateId(_))
| None
| Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None,
})
.ok_or_else(missing_field_err("connector_mandate_request_reference_id"))
}
fn is_cit_mandate_payment(&self) -> bool {
(self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& self.setup_future_usage == Some(FutureUsage::OffSession)
}
fn get_optional_network_transaction_id(&self) -> Option<String> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => {
Some(network_transaction_id.clone())
}
Some(payments::MandateReferenceId::ConnectorMandateId(_))
| Some(payments::MandateReferenceId::NetworkTokenWithNTI(_))
| None => None,
})
}
fn get_optional_email(&self) -> Option<Email> {
self.email.clone()
}
fn get_card_network_from_additional_payment_method_data(
&self,
) -> Result<enums::CardNetwork, Error> {
match &self.additional_payment_method_data {
Some(payments::AdditionalPaymentData::Card(card_data)) => Ok(card_data
.card_network
.clone()
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "card_network",
})?),
_ => Err(errors::ConnectorError::MissingRequiredFields {
field_names: vec!["card_network"],
}
.into()),
}
}
}
pub trait PaymentsCaptureRequestData {
fn get_optional_language_from_browser_info(&self) -> Option<String>;
fn is_multiple_capture(&self) -> bool;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_webhook_url(&self) -> Result<String, Error>;
}
impl PaymentsCaptureRequestData for PaymentsCaptureData {
fn is_multiple_capture(&self) -> bool {
self.multiple_capture_data.is_some()
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_optional_language_from_browser_info(&self) -> Option<String> {
self.browser_info
.clone()
.and_then(|browser_info| browser_info.language)
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
}
pub trait PaymentsSyncRequestData {
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError>;
}
impl PaymentsSyncRequestData for PaymentsSyncData {
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError> {
match self.connector_transaction_id.clone() {
ResponseId::ConnectorTransactionId(txn_id) => Ok(txn_id),
_ => Err(
common_utils::errors::ValidationError::IncorrectValueProvided {
field_name: "connector_transaction_id",
},
)
.attach_printable("Expected connector transaction ID not found")
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
}
}
}
pub trait PaymentsPostSessionTokensRequestData {
fn is_auto_capture(&self) -> Result<bool, Error>;
}
impl PaymentsPostSessionTokensRequestData for PaymentsPostSessionTokensData {
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| None
| Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
}
pub trait PaymentsCancelRequestData {
fn get_optional_language_from_browser_info(&self) -> Option<String>;
fn get_amount(&self) -> Result<i64, Error>;
fn get_currency(&self) -> Result<enums::Currency, Error>;
fn get_cancellation_reason(&self) -> Result<String, Error>;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_webhook_url(&self) -> Result<String, Error>;
}
impl PaymentsCancelRequestData for PaymentsCancelData {
fn get_amount(&self) -> Result<i64, Error> {
self.amount.ok_or_else(missing_field_err("amount"))
}
fn get_currency(&self) -> Result<enums::Currency, Error> {
self.currency.ok_or_else(missing_field_err("currency"))
}
fn get_cancellation_reason(&self) -> Result<String, Error> {
self.cancellation_reason
.clone()
.ok_or_else(missing_field_err("cancellation_reason"))
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_optional_language_from_browser_info(&self) -> Option<String> {
self.browser_info
.clone()
.and_then(|browser_info| browser_info.language)
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
}
pub trait RefundsRequestData {
fn get_optional_language_from_browser_info(&self) -> Option<String>;
fn get_connector_refund_id(&self) -> Result<String, Error>;
fn get_webhook_url(&self) -> Result<String, Error>;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_connector_metadata(&self) -> Result<Value, Error>;
}
impl RefundsRequestData for RefundsData {
#[track_caller]
fn get_connector_refund_id(&self) -> Result<String, Error> {
self.connector_refund_id
.clone()
.get_required_value("connector_refund_id")
.change_context(errors::ConnectorError::MissingConnectorTransactionID)
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_optional_language_from_browser_info(&self) -> Option<String> {
self.browser_info
.clone()
.and_then(|browser_info| browser_info.language)
}
fn get_connector_metadata(&self) -> Result<Value, Error> {
self.connector_metadata
.clone()
.ok_or_else(missing_field_err("connector_metadata"))
}
}
pub trait PaymentsSetupMandateRequestData {
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_email(&self) -> Result<Email, Error>;
fn get_router_return_url(&self) -> Result<String, Error>;
fn is_card(&self) -> bool;
fn get_return_url(&self) -> Result<String, Error>;
fn get_webhook_url(&self) -> Result<String, Error>;
fn get_optional_language_from_browser_info(&self) -> Option<String>;
fn get_complete_authorize_url(&self) -> Result<String, Error>;
fn is_auto_capture(&self) -> Result<bool, Error>;
}
impl PaymentsSetupMandateRequestData for SetupMandateRequestData {
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn get_router_return_url(&self) -> Result<String, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("router_return_url"))
}
fn is_card(&self) -> bool {
matches!(self.payment_method_data, PaymentMethodData::Card(_))
}
fn get_return_url(&self) -> Result<String, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("return_url"))
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
fn get_optional_language_from_browser_info(&self) -> Option<String> {
self.browser_info
.clone()
.and_then(|browser_info| browser_info.language)
}
fn get_complete_authorize_url(&self) -> Result<String, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
}
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
}
pub trait PaymentMethodTokenizationRequestData {
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
}
impl PaymentMethodTokenizationRequestData for PaymentMethodTokenizationData {
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
}
pub trait PaymentsCompleteAuthorizeRequestData {
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_email(&self) -> Result<Email, Error>;
fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>;
fn get_complete_authorize_url(&self) -> Result<String, Error>;
fn is_mandate_payment(&self) -> bool;
fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error>;
fn is_cit_mandate_payment(&self) -> bool;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_threeds_method_comp_ind(&self) -> Result<payments::ThreeDsCompletionIndicator, Error>;
}
impl PaymentsCompleteAuthorizeRequestData for CompleteAuthorizeData {
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error> {
self.redirect_response
.as_ref()
.and_then(|res| res.payload.to_owned())
.ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
}
.into(),
)
}
fn get_complete_authorize_url(&self) -> Result<String, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
}
fn is_mandate_payment(&self) -> bool {
((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& self.setup_future_usage == Some(FutureUsage::OffSession))
|| self
.mandate_id
.as_ref()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref())
.is_some()
}
/// Attempts to retrieve the connector mandate reference ID as a `Result<String, Error>`.
fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
connector_mandate_ids.get_connector_mandate_request_reference_id()
}
Some(payments::MandateReferenceId::NetworkMandateId(_))
| None
| Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None,
})
.ok_or_else(missing_field_err("connector_mandate_request_reference_id"))
}
fn is_cit_mandate_payment(&self) -> bool {
(self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& self.setup_future_usage == Some(FutureUsage::OffSession)
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_threeds_method_comp_ind(&self) -> Result<payments::ThreeDsCompletionIndicator, Error> {
self.threeds_method_comp_ind
.clone()
.ok_or_else(missing_field_err("threeds_method_comp_ind"))
}
}
pub trait AddressData {
fn get_optional_full_name(&self) -> Option<Secret<String>>;
fn get_email(&self) -> Result<Email, Error>;
fn get_phone_with_country_code(&self) -> Result<Secret<String>, Error>;
fn get_optional_first_name(&self) -> Option<Secret<String>>;
fn get_optional_last_name(&self) -> Option<Secret<String>>;
}
impl AddressData for Address {
fn get_optional_full_name(&self) -> Option<Secret<String>> {
self.address
.as_ref()
.and_then(|billing_address| billing_address.get_optional_full_name())
}
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn get_phone_with_country_code(&self) -> Result<Secret<String>, Error> {
self.phone
.clone()
.map(|phone_details| phone_details.get_number_with_country_code())
.transpose()?
.ok_or_else(missing_field_err("phone"))
}
fn get_optional_first_name(&self) -> Option<Secret<String>> {
self.address
.as_ref()
.and_then(|billing_address| billing_address.get_optional_first_name())
}
fn get_optional_last_name(&self) -> Option<Secret<String>> {
self.address
.as_ref()
.and_then(|billing_address| billing_address.get_optional_last_name())
}
}
pub trait PaymentsPreProcessingRequestData {
fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>;
fn get_email(&self) -> Result<Email, Error>;
fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>;
fn get_currency(&self) -> Result<enums::Currency, Error>;
fn get_amount(&self) -> Result<i64, Error>;
fn get_minor_amount(&self) -> Result<MinorUnit, Error>;
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>;
fn get_webhook_url(&self) -> Result<String, Error>;
fn get_router_return_url(&self) -> Result<String, Error>;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_complete_authorize_url(&self) -> Result<String, Error>;
fn connector_mandate_id(&self) -> Option<String>;
}
impl PaymentsPreProcessingRequestData for PaymentsPreProcessingData {
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> {
self.payment_method_type
.to_owned()
.ok_or_else(missing_field_err("payment_method_type"))
}
fn get_currency(&self) -> Result<enums::Currency, Error> {
self.currency.ok_or_else(missing_field_err("currency"))
}
fn get_amount(&self) -> Result<i64, Error> {
self.amount.ok_or_else(missing_field_err("amount"))
}
// New minor amount function for amount framework
fn get_minor_amount(&self) -> Result<MinorUnit, Error> {
self.minor_amount.ok_or_else(missing_field_err("amount"))
}
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| None
| Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(enums::CaptureMethod::ManualMultiple) | Some(enums::CaptureMethod::Scheduled) => {
Err(errors::ConnectorError::CaptureMethodNotSupported.into())
}
}
}
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> {
self.order_details
.clone()
.ok_or_else(missing_field_err("order_details"))
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
fn get_router_return_url(&self) -> Result<String, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("return_url"))
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_complete_authorize_url(&self) -> Result<String, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
}
fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error> {
self.redirect_response
.as_ref()
.and_then(|res| res.payload.to_owned())
.ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
}
.into(),
)
}
fn connector_mandate_id(&self) -> Option<String> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
connector_mandate_ids.get_connector_mandate_id()
}
Some(payments::MandateReferenceId::NetworkMandateId(_))
| None
| Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None,
})
}
}
pub trait BrowserInformationData {
fn get_accept_header(&self) -> Result<String, Error>;
fn get_language(&self) -> Result<String, Error>;
fn get_screen_height(&self) -> Result<u32, Error>;
fn get_screen_width(&self) -> Result<u32, Error>;
fn get_color_depth(&self) -> Result<u8, Error>;
fn get_user_agent(&self) -> Result<String, Error>;
fn get_time_zone(&self) -> Result<i32, Error>;
fn get_java_enabled(&self) -> Result<bool, Error>;
fn get_java_script_enabled(&self) -> Result<bool, Error>;
fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error>;
fn get_os_type(&self) -> Result<String, Error>;
fn get_os_version(&self) -> Result<String, Error>;
fn get_device_model(&self) -> Result<String, Error>;
}
impl BrowserInformationData for BrowserInformation {
fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error> {
let ip_address = self
.ip_address
.ok_or_else(missing_field_err("browser_info.ip_address"))?;
Ok(Secret::new(ip_address.to_string()))
}
fn get_accept_header(&self) -> Result<String, Error> {
self.accept_header
.clone()
.ok_or_else(missing_field_err("browser_info.accept_header"))
}
fn get_language(&self) -> Result<String, Error> {
self.language
.clone()
.ok_or_else(missing_field_err("browser_info.language"))
}
fn get_screen_height(&self) -> Result<u32, Error> {
self.screen_height
.ok_or_else(missing_field_err("browser_info.screen_height"))
}
fn get_screen_width(&self) -> Result<u32, Error> {
self.screen_width
.ok_or_else(missing_field_err("browser_info.screen_width"))
}
fn get_color_depth(&self) -> Result<u8, Error> {
self.color_depth
.ok_or_else(missing_field_err("browser_info.color_depth"))
}
fn get_user_agent(&self) -> Result<String, Error> {
self.user_agent
.clone()
.ok_or_else(missing_field_err("browser_info.user_agent"))
}
fn get_time_zone(&self) -> Result<i32, Error> {
self.time_zone
.ok_or_else(missing_field_err("browser_info.time_zone"))
}
fn get_java_enabled(&self) -> Result<bool, Error> {
self.java_enabled
.ok_or_else(missing_field_err("browser_info.java_enabled"))
}
fn get_java_script_enabled(&self) -> Result<bool, Error> {
self.java_script_enabled
.ok_or_else(missing_field_err("browser_info.java_script_enabled"))
}
fn get_os_type(&self) -> Result<String, Error> {
self.os_type
.clone()
.ok_or_else(missing_field_err("browser_info.os_type"))
}
fn get_os_version(&self) -> Result<String, Error> {
self.os_version
.clone()
.ok_or_else(missing_field_err("browser_info.os_version"))
}
fn get_device_model(&self) -> Result<String, Error> {
self.device_model
.clone()
.ok_or_else(missing_field_err("browser_info.device_model"))
}
}
pub fn get_header_key_value<'a>(
key: &str,
headers: &'a actix_web::http::header::HeaderMap,
) -> CustomResult<&'a str, errors::ConnectorError> {
get_header_field(headers.get(key))
}
pub fn get_http_header<'a>(
key: &str,
headers: &'a http::HeaderMap,
) -> CustomResult<&'a str, errors::ConnectorError> {
get_header_field(headers.get(key))
}
fn get_header_field(
field: Option<&http::HeaderValue>,
) -> CustomResult<&str, errors::ConnectorError> {
field
.map(|header_value| {
header_value
.to_str()
.change_context(errors::ConnectorError::WebhookSignatureNotFound)
})
.ok_or(report!(
errors::ConnectorError::WebhookSourceVerificationFailed
))?
}
pub trait CryptoData {
fn get_pay_currency(&self) -> Result<String, Error>;
}
impl CryptoData for payment_method_data::CryptoData {
fn get_pay_currency(&self) -> Result<String, Error> {
self.pay_currency
.clone()
.ok_or_else(missing_field_err("crypto_data.pay_currency"))
}
}
#[macro_export]
macro_rules! capture_method_not_supported {
($connector:expr, $capture_method:expr) => {
Err(errors::ConnectorError::NotSupported {
message: format!("{} for selected payment method", $capture_method),
connector: $connector,
}
.into())
};
($connector:expr, $capture_method:expr, $payment_method_type:expr) => {
Err(errors::ConnectorError::NotSupported {
message: format!("{} for {}", $capture_method, $payment_method_type),
connector: $connector,
}
.into())
};
}
#[macro_export]
macro_rules! unimplemented_payment_method {
($payment_method:expr, $connector:expr) => {
errors::ConnectorError::NotImplemented(format!(
"{} through {}",
$payment_method, $connector
))
};
($payment_method:expr, $flow:expr, $connector:expr) => {
errors::ConnectorError::NotImplemented(format!(
"{} {} through {}",
$payment_method, $flow, $connector
))
};
}
impl ForeignTryFrom<String> for UsStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.to_uppercase().clone(), "UsStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => {
let binding = value.as_str().to_lowercase();
let state = binding.as_str();
match state {
"alabama" => Ok(Self::AL),
"alaska" => Ok(Self::AK),
"american samoa" => Ok(Self::AS),
"arizona" => Ok(Self::AZ),
"arkansas" => Ok(Self::AR),
"california" => Ok(Self::CA),
"colorado" => Ok(Self::CO),
"connecticut" => Ok(Self::CT),
"delaware" => Ok(Self::DE),
"district of columbia" | "columbia" => Ok(Self::DC),
"federated states of micronesia" | "micronesia" => Ok(Self::FM),
"florida" => Ok(Self::FL),
"georgia" => Ok(Self::GA),
"guam" => Ok(Self::GU),
"hawaii" => Ok(Self::HI),
"idaho" => Ok(Self::ID),
"illinois" => Ok(Self::IL),
"indiana" => Ok(Self::IN),
"iowa" => Ok(Self::IA),
"kansas" => Ok(Self::KS),
"kentucky" => Ok(Self::KY),
"louisiana" => Ok(Self::LA),
"maine" => Ok(Self::ME),
"marshall islands" => Ok(Self::MH),
"maryland" => Ok(Self::MD),
"massachusetts" => Ok(Self::MA),
"michigan" => Ok(Self::MI),
"minnesota" => Ok(Self::MN),
"mississippi" => Ok(Self::MS),
"missouri" => Ok(Self::MO),
"montana" => Ok(Self::MT),
"nebraska" => Ok(Self::NE),
"nevada" => Ok(Self::NV),
"new hampshire" => Ok(Self::NH),
"new jersey" => Ok(Self::NJ),
"new mexico" => Ok(Self::NM),
"new york" => Ok(Self::NY),
"north carolina" => Ok(Self::NC),
"north dakota" => Ok(Self::ND),
"northern mariana islands" => Ok(Self::MP),
"ohio" => Ok(Self::OH),
"oklahoma" => Ok(Self::OK),
"oregon" => Ok(Self::OR),
"palau" => Ok(Self::PW),
"pennsylvania" => Ok(Self::PA),
"puerto rico" => Ok(Self::PR),
"rhode island" => Ok(Self::RI),
"south carolina" => Ok(Self::SC),
"south dakota" => Ok(Self::SD),
"tennessee" => Ok(Self::TN),
"texas" => Ok(Self::TX),
"utah" => Ok(Self::UT),
"vermont" => Ok(Self::VT),
"virgin islands" => Ok(Self::VI),
"virginia" => Ok(Self::VA),
"washington" => Ok(Self::WA),
"west virginia" => Ok(Self::WV),
"wisconsin" => Ok(Self::WI),
"wyoming" => Ok(Self::WY),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
}
}
}
}
}
impl ForeignTryFrom<String> for CanadaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.to_uppercase().clone(), "CanadaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => {
let binding = value.as_str().to_lowercase();
let state = binding.as_str();
match state {
"alberta" => Ok(Self::AB),
"british columbia" => Ok(Self::BC),
"manitoba" => Ok(Self::MB),
"new brunswick" => Ok(Self::NB),
"newfoundland and labrador" | "newfoundland & labrador" => Ok(Self::NL),
"northwest territories" => Ok(Self::NT),
"nova scotia" => Ok(Self::NS),
"nunavut" => Ok(Self::NU),
"ontario" => Ok(Self::ON),
"prince edward island" => Ok(Self::PE),
"quebec" => Ok(Self::QC),
"saskatchewan" => Ok(Self::SK),
"yukon" => Ok(Self::YT),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
}
}
}
}
}
impl ForeignTryFrom<String> for PolandStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "PolandStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Greater Poland" => Ok(Self::GreaterPoland),
"Holy Cross" => Ok(Self::HolyCross),
"Kuyavia-Pomerania" => Ok(Self::KuyaviaPomerania),
"Lesser Poland" => Ok(Self::LesserPoland),
"Lower Silesia" => Ok(Self::LowerSilesia),
"Lublin" => Ok(Self::Lublin),
"Lubusz" => Ok(Self::Lubusz),
"Łódź" => Ok(Self::Łódź),
"Mazovia" => Ok(Self::Mazovia),
"Podlaskie" => Ok(Self::Podlaskie),
"Pomerania" => Ok(Self::Pomerania),
"Silesia" => Ok(Self::Silesia),
"Subcarpathia" => Ok(Self::Subcarpathia),
"Upper Silesia" => Ok(Self::UpperSilesia),
"Warmia-Masuria" => Ok(Self::WarmiaMasuria),
"West Pomerania" => Ok(Self::WestPomerania),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for FranceStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "FranceStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Ain" => Ok(Self::Ain),
"Aisne" => Ok(Self::Aisne),
"Allier" => Ok(Self::Allier),
"Alpes-de-Haute-Provence" => Ok(Self::AlpesDeHauteProvence),
"Alpes-Maritimes" => Ok(Self::AlpesMaritimes),
"Alsace" => Ok(Self::Alsace),
"Ardèche" => Ok(Self::Ardeche),
"Ardennes" => Ok(Self::Ardennes),
"Ariège" => Ok(Self::Ariege),
"Aube" => Ok(Self::Aube),
"Aude" => Ok(Self::Aude),
"Auvergne-Rhône-Alpes" => Ok(Self::AuvergneRhoneAlpes),
"Aveyron" => Ok(Self::Aveyron),
"Bas-Rhin" => Ok(Self::BasRhin),
"Bouches-du-Rhône" => Ok(Self::BouchesDuRhone),
"Bourgogne-Franche-Comté" => Ok(Self::BourgogneFrancheComte),
"Bretagne" => Ok(Self::Bretagne),
"Calvados" => Ok(Self::Calvados),
"Cantal" => Ok(Self::Cantal),
"Centre-Val de Loire" => Ok(Self::CentreValDeLoire),
"Charente" => Ok(Self::Charente),
"Charente-Maritime" => Ok(Self::CharenteMaritime),
"Cher" => Ok(Self::Cher),
"Clipperton" => Ok(Self::Clipperton),
"Corrèze" => Ok(Self::Correze),
"Corse" => Ok(Self::Corse),
"Corse-du-Sud" => Ok(Self::CorseDuSud),
"Côte-d'Or" => Ok(Self::CoteDor),
"Côtes-d'Armor" => Ok(Self::CotesDarmor),
"Creuse" => Ok(Self::Creuse),
"Deux-Sèvres" => Ok(Self::DeuxSevres),
"Dordogne" => Ok(Self::Dordogne),
"Doubs" => Ok(Self::Doubs),
"Drôme" => Ok(Self::Drome),
"Essonne" => Ok(Self::Essonne),
"Eure" => Ok(Self::Eure),
"Eure-et-Loir" => Ok(Self::EureEtLoir),
"Finistère" => Ok(Self::Finistere),
"French Guiana" => Ok(Self::FrenchGuiana),
"French Polynesia" => Ok(Self::FrenchPolynesia),
"French Southern and Antarctic Lands" => Ok(Self::FrenchSouthernAndAntarcticLands),
"Gard" => Ok(Self::Gard),
"Gers" => Ok(Self::Gers),
"Gironde" => Ok(Self::Gironde),
"Grand-Est" => Ok(Self::GrandEst),
"Guadeloupe" => Ok(Self::Guadeloupe),
"Haut-Rhin" => Ok(Self::HautRhin),
"Haute-Corse" => Ok(Self::HauteCorse),
"Haute-Garonne" => Ok(Self::HauteGaronne),
"Haute-Loire" => Ok(Self::HauteLoire),
"Haute-Marne" => Ok(Self::HauteMarne),
"Haute-Saône" => Ok(Self::HauteSaone),
"Haute-Savoie" => Ok(Self::HauteSavoie),
"Haute-Vienne" => Ok(Self::HauteVienne),
"Hautes-Alpes" => Ok(Self::HautesAlpes),
"Hautes-Pyrénées" => Ok(Self::HautesPyrenees),
"Hauts-de-France" => Ok(Self::HautsDeFrance),
"Hauts-de-Seine" => Ok(Self::HautsDeSeine),
"Hérault" => Ok(Self::Herault),
"Île-de-France" => Ok(Self::IleDeFrance),
"Ille-et-Vilaine" => Ok(Self::IlleEtVilaine),
"Indre" => Ok(Self::Indre),
"Indre-et-Loire" => Ok(Self::IndreEtLoire),
"Isère" => Ok(Self::Isere),
"Jura" => Ok(Self::Jura),
"La Réunion" => Ok(Self::LaReunion),
"Landes" => Ok(Self::Landes),
"Loir-et-Cher" => Ok(Self::LoirEtCher),
"Loire" => Ok(Self::Loire),
"Loire-Atlantique" => Ok(Self::LoireAtlantique),
"Loiret" => Ok(Self::Loiret),
"Lot" => Ok(Self::Lot),
"Lot-et-Garonne" => Ok(Self::LotEtGaronne),
"Lozère" => Ok(Self::Lozere),
"Maine-et-Loire" => Ok(Self::MaineEtLoire),
"Manche" => Ok(Self::Manche),
"Marne" => Ok(Self::Marne),
"Martinique" => Ok(Self::Martinique),
"Mayenne" => Ok(Self::Mayenne),
"Mayotte" => Ok(Self::Mayotte),
"Métropole de Lyon" => Ok(Self::MetropoleDeLyon),
"Meurthe-et-Moselle" => Ok(Self::MeurtheEtMoselle),
"Meuse" => Ok(Self::Meuse),
"Morbihan" => Ok(Self::Morbihan),
"Moselle" => Ok(Self::Moselle),
"Nièvre" => Ok(Self::Nievre),
"Nord" => Ok(Self::Nord),
"Normandie" => Ok(Self::Normandie),
"Nouvelle-Aquitaine" => Ok(Self::NouvelleAquitaine),
"Occitanie" => Ok(Self::Occitanie),
"Oise" => Ok(Self::Oise),
"Orne" => Ok(Self::Orne),
"Paris" => Ok(Self::Paris),
"Pas-de-Calais" => Ok(Self::PasDeCalais),
"Pays-de-la-Loire" => Ok(Self::PaysDeLaLoire),
"Provence-Alpes-Côte-d'Azur" => Ok(Self::ProvenceAlpesCoteDazur),
"Puy-de-Dôme" => Ok(Self::PuyDeDome),
"Pyrénées-Atlantiques" => Ok(Self::PyreneesAtlantiques),
"Pyrénées-Orientales" => Ok(Self::PyreneesOrientales),
"Rhône" => Ok(Self::Rhone),
"Saint Pierre and Miquelon" => Ok(Self::SaintPierreAndMiquelon),
"Saint-Barthélemy" => Ok(Self::SaintBarthelemy),
"Saint-Martin" => Ok(Self::SaintMartin),
"Saône-et-Loire" => Ok(Self::SaoneEtLoire),
"Sarthe" => Ok(Self::Sarthe),
"Savoie" => Ok(Self::Savoie),
"Seine-et-Marne" => Ok(Self::SeineEtMarne),
"Seine-Maritime" => Ok(Self::SeineMaritime),
"Seine-Saint-Denis" => Ok(Self::SeineSaintDenis),
"Somme" => Ok(Self::Somme),
"Tarn" => Ok(Self::Tarn),
"Tarn-et-Garonne" => Ok(Self::TarnEtGaronne),
"Territoire de Belfort" => Ok(Self::TerritoireDeBelfort),
"Val-d'Oise" => Ok(Self::ValDoise),
"Val-de-Marne" => Ok(Self::ValDeMarne),
"Var" => Ok(Self::Var),
"Vaucluse" => Ok(Self::Vaucluse),
"Vendée" => Ok(Self::Vendee),
"Vienne" => Ok(Self::Vienne),
"Vosges" => Ok(Self::Vosges),
"Wallis and Futuna" => Ok(Self::WallisAndFutuna),
"Yonne" => Ok(Self::Yonne),
"Yvelines" => Ok(Self::Yvelines),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for GermanyStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "GermanyStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Baden-Württemberg" => Ok(Self::BW),
"Bavaria" => Ok(Self::BY),
"Berlin" => Ok(Self::BE),
"Brandenburg" => Ok(Self::BB),
"Bremen" => Ok(Self::HB),
"Hamburg" => Ok(Self::HH),
"Hessen" => Ok(Self::HE),
"Lower Saxony" => Ok(Self::NI),
"Mecklenburg-Vorpommern" => Ok(Self::MV),
"North Rhine-Westphalia" => Ok(Self::NW),
"Rhineland-Palatinate" => Ok(Self::RP),
"Saarland" => Ok(Self::SL),
"Saxony" => Ok(Self::SN),
"Saxony-Anhalt" => Ok(Self::ST),
"Schleswig-Holstein" => Ok(Self::SH),
"Thuringia" => Ok(Self::TH),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for SpainStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "SpainStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"A Coruña Province" => Ok(Self::ACorunaProvince),
"Albacete Province" => Ok(Self::AlbaceteProvince),
"Alicante Province" => Ok(Self::AlicanteProvince),
"Almería Province" => Ok(Self::AlmeriaProvince),
"Andalusia" => Ok(Self::Andalusia),
"Araba / Álava" => Ok(Self::ArabaAlava),
"Aragon" => Ok(Self::Aragon),
"Badajoz Province" => Ok(Self::BadajozProvince),
"Balearic Islands" => Ok(Self::BalearicIslands),
"Barcelona Province" => Ok(Self::BarcelonaProvince),
"Basque Country" => Ok(Self::BasqueCountry),
"Biscay" => Ok(Self::Biscay),
"Burgos Province" => Ok(Self::BurgosProvince),
"Canary Islands" => Ok(Self::CanaryIslands),
"Cantabria" => Ok(Self::Cantabria),
"Castellón Province" => Ok(Self::CastellonProvince),
"Castile and León" => Ok(Self::CastileAndLeon),
"Castilla-La Mancha" => Ok(Self::CastileLaMancha),
"Catalonia" => Ok(Self::Catalonia),
"Ceuta" => Ok(Self::Ceuta),
"Ciudad Real Province" => Ok(Self::CiudadRealProvince),
"Community of Madrid" => Ok(Self::CommunityOfMadrid),
"Cuenca Province" => Ok(Self::CuencaProvince),
"Cáceres Province" => Ok(Self::CaceresProvince),
"Cádiz Province" => Ok(Self::CadizProvince),
"Córdoba Province" => Ok(Self::CordobaProvince),
"Extremadura" => Ok(Self::Extremadura),
"Galicia" => Ok(Self::Galicia),
"Gipuzkoa" => Ok(Self::Gipuzkoa),
"Girona Province" => Ok(Self::GironaProvince),
"Granada Province" => Ok(Self::GranadaProvince),
"Guadalajara Province" => Ok(Self::GuadalajaraProvince),
"Huelva Province" => Ok(Self::HuelvaProvince),
"Huesca Province" => Ok(Self::HuescaProvince),
"Jaén Province" => Ok(Self::JaenProvince),
"La Rioja" => Ok(Self::LaRioja),
"Las Palmas Province" => Ok(Self::LasPalmasProvince),
"León Province" => Ok(Self::LeonProvince),
"Lleida Province" => Ok(Self::LleidaProvince),
"Lugo Province" => Ok(Self::LugoProvince),
"Madrid Province" => Ok(Self::MadridProvince),
"Melilla" => Ok(Self::Melilla),
"Murcia Province" => Ok(Self::MurciaProvince),
"Málaga Province" => Ok(Self::MalagaProvince),
"Navarre" => Ok(Self::Navarre),
"Ourense Province" => Ok(Self::OurenseProvince),
"Palencia Province" => Ok(Self::PalenciaProvince),
"Pontevedra Province" => Ok(Self::PontevedraProvince),
"Province of Asturias" => Ok(Self::ProvinceOfAsturias),
"Province of Ávila" => Ok(Self::ProvinceOfAvila),
"Region of Murcia" => Ok(Self::RegionOfMurcia),
"Salamanca Province" => Ok(Self::SalamancaProvince),
"Santa Cruz de Tenerife Province" => Ok(Self::SantaCruzDeTenerifeProvince),
"Segovia Province" => Ok(Self::SegoviaProvince),
"Seville Province" => Ok(Self::SevilleProvince),
"Soria Province" => Ok(Self::SoriaProvince),
"Tarragona Province" => Ok(Self::TarragonaProvince),
"Teruel Province" => Ok(Self::TeruelProvince),
"Toledo Province" => Ok(Self::ToledoProvince),
"Valencia Province" => Ok(Self::ValenciaProvince),
"Valencian Community" => Ok(Self::ValencianCommunity),
"Valladolid Province" => Ok(Self::ValladolidProvince),
"Zamora Province" => Ok(Self::ZamoraProvince),
"Zaragoza Province" => Ok(Self::ZaragozaProvince),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for ItalyStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "ItalyStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Abruzzo" => Ok(Self::Abruzzo),
"Aosta Valley" => Ok(Self::AostaValley),
"Apulia" => Ok(Self::Apulia),
"Basilicata" => Ok(Self::Basilicata),
"Benevento Province" => Ok(Self::BeneventoProvince),
"Calabria" => Ok(Self::Calabria),
"Campania" => Ok(Self::Campania),
"Emilia-Romagna" => Ok(Self::EmiliaRomagna),
"Friuli–Venezia Giulia" => Ok(Self::FriuliVeneziaGiulia),
"Lazio" => Ok(Self::Lazio),
"Liguria" => Ok(Self::Liguria),
"Lombardy" => Ok(Self::Lombardy),
"Marche" => Ok(Self::Marche),
"Molise" => Ok(Self::Molise),
"Piedmont" => Ok(Self::Piedmont),
"Sardinia" => Ok(Self::Sardinia),
"Sicily" => Ok(Self::Sicily),
"Trentino-South Tyrol" => Ok(Self::TrentinoSouthTyrol),
"Tuscany" => Ok(Self::Tuscany),
"Umbria" => Ok(Self::Umbria),
"Veneto" => Ok(Self::Veneto),
"Libero consorzio comunale di Agrigento" => Ok(Self::Agrigento),
"Libero consorzio comunale di Caltanissetta" => Ok(Self::Caltanissetta),
"Libero consorzio comunale di Enna" => Ok(Self::Enna),
"Libero consorzio comunale di Ragusa" => Ok(Self::Ragusa),
"Libero consorzio comunale di Siracusa" => Ok(Self::Siracusa),
"Libero consorzio comunale di Trapani" => Ok(Self::Trapani),
"Metropolitan City of Bari" => Ok(Self::Bari),
"Metropolitan City of Bologna" => Ok(Self::Bologna),
"Metropolitan City of Cagliari" => Ok(Self::Cagliari),
"Metropolitan City of Catania" => Ok(Self::Catania),
"Metropolitan City of Florence" => Ok(Self::Florence),
"Metropolitan City of Genoa" => Ok(Self::Genoa),
"Metropolitan City of Messina" => Ok(Self::Messina),
"Metropolitan City of Milan" => Ok(Self::Milan),
"Metropolitan City of Naples" => Ok(Self::Naples),
"Metropolitan City of Palermo" => Ok(Self::Palermo),
"Metropolitan City of Reggio Calabria" => Ok(Self::ReggioCalabria),
"Metropolitan City of Rome" => Ok(Self::Rome),
"Metropolitan City of Turin" => Ok(Self::Turin),
"Metropolitan City of Venice" => Ok(Self::Venice),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for NorwayStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "NorwayStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Akershus" => Ok(Self::Akershus),
"Buskerud" => Ok(Self::Buskerud),
"Finnmark" => Ok(Self::Finnmark),
"Hedmark" => Ok(Self::Hedmark),
"Hordaland" => Ok(Self::Hordaland),
"Jan Mayen" => Ok(Self::JanMayen),
"Møre og Romsdal" => Ok(Self::MoreOgRomsdal),
"Nord-Trøndelag" => Ok(Self::NordTrondelag),
"Nordland" => Ok(Self::Nordland),
"Oppland" => Ok(Self::Oppland),
"Oslo" => Ok(Self::Oslo),
"Rogaland" => Ok(Self::Rogaland),
"Sogn og Fjordane" => Ok(Self::SognOgFjordane),
"Svalbard" => Ok(Self::Svalbard),
"Sør-Trøndelag" => Ok(Self::SorTrondelag),
"Telemark" => Ok(Self::Telemark),
"Troms" => Ok(Self::Troms),
"Trøndelag" => Ok(Self::Trondelag),
"Vest-Agder" => Ok(Self::VestAgder),
"Vestfold" => Ok(Self::Vestfold),
"Østfold" => Ok(Self::Ostfold),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for AlbaniaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "AlbaniaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Berat" => Ok(Self::Berat),
"Dibër" => Ok(Self::Diber),
"Durrës" => Ok(Self::Durres),
"Elbasan" => Ok(Self::Elbasan),
"Fier" => Ok(Self::Fier),
"Gjirokastër" => Ok(Self::Gjirokaster),
"Korçë" => Ok(Self::Korce),
"Kukës" => Ok(Self::Kukes),
"Lezhë" => Ok(Self::Lezhe),
"Shkodër" => Ok(Self::Shkoder),
"Tiranë" => Ok(Self::Tirane),
"Vlorë" => Ok(Self::Vlore),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for AndorraStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "AndorraStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Andorra la Vella" => Ok(Self::AndorraLaVella),
"Canillo" => Ok(Self::Canillo),
"Encamp" => Ok(Self::Encamp),
"Escaldes-Engordany" => Ok(Self::EscaldesEngordany),
"La Massana" => Ok(Self::LaMassana),
"Ordino" => Ok(Self::Ordino),
"Sant Julià de Lòria" => Ok(Self::SantJuliaDeLoria),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for AustriaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "AustriaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Burgenland" => Ok(Self::Burgenland),
"Carinthia" => Ok(Self::Carinthia),
"Lower Austria" => Ok(Self::LowerAustria),
"Salzburg" => Ok(Self::Salzburg),
"Styria" => Ok(Self::Styria),
"Tyrol" => Ok(Self::Tyrol),
"Upper Austria" => Ok(Self::UpperAustria),
"Vienna" => Ok(Self::Vienna),
"Vorarlberg" => Ok(Self::Vorarlberg),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for RomaniaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "RomaniaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Alba" => Ok(Self::Alba),
"Arad County" => Ok(Self::AradCounty),
"Argeș" => Ok(Self::Arges),
"Bacău County" => Ok(Self::BacauCounty),
"Bihor County" => Ok(Self::BihorCounty),
"Bistrița-Năsăud County" => Ok(Self::BistritaNasaudCounty),
"Botoșani County" => Ok(Self::BotosaniCounty),
"Brăila" => Ok(Self::Braila),
"Brașov County" => Ok(Self::BrasovCounty),
"Bucharest" => Ok(Self::Bucharest),
"Buzău County" => Ok(Self::BuzauCounty),
"Caraș-Severin County" => Ok(Self::CarasSeverinCounty),
"Cluj County" => Ok(Self::ClujCounty),
"Constanța County" => Ok(Self::ConstantaCounty),
"Covasna County" => Ok(Self::CovasnaCounty),
"Călărași County" => Ok(Self::CalarasiCounty),
"Dolj County" => Ok(Self::DoljCounty),
"Dâmbovița County" => Ok(Self::DambovitaCounty),
"Galați County" => Ok(Self::GalatiCounty),
"Giurgiu County" => Ok(Self::GiurgiuCounty),
"Gorj County" => Ok(Self::GorjCounty),
"Harghita County" => Ok(Self::HarghitaCounty),
"Hunedoara County" => Ok(Self::HunedoaraCounty),
"Ialomița County" => Ok(Self::IalomitaCounty),
"Iași County" => Ok(Self::IasiCounty),
"Ilfov County" => Ok(Self::IlfovCounty),
"Mehedinți County" => Ok(Self::MehedintiCounty),
"Mureș County" => Ok(Self::MuresCounty),
"Neamț County" => Ok(Self::NeamtCounty),
"Olt County" => Ok(Self::OltCounty),
"Prahova County" => Ok(Self::PrahovaCounty),
"Satu Mare County" => Ok(Self::SatuMareCounty),
"Sibiu County" => Ok(Self::SibiuCounty),
"Suceava County" => Ok(Self::SuceavaCounty),
"Sălaj County" => Ok(Self::SalajCounty),
"Teleorman County" => Ok(Self::TeleormanCounty),
"Timiș County" => Ok(Self::TimisCounty),
"Tulcea County" => Ok(Self::TulceaCounty),
"Vaslui County" => Ok(Self::VasluiCounty),
"Vrancea County" => Ok(Self::VranceaCounty),
"Vâlcea County" => Ok(Self::ValceaCounty),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for PortugalStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "PortugalStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Aveiro District" => Ok(Self::AveiroDistrict),
"Azores" => Ok(Self::Azores),
"Beja District" => Ok(Self::BejaDistrict),
"Braga District" => Ok(Self::BragaDistrict),
"Bragança District" => Ok(Self::BragancaDistrict),
"Castelo Branco District" => Ok(Self::CasteloBrancoDistrict),
"Coimbra District" => Ok(Self::CoimbraDistrict),
"Faro District" => Ok(Self::FaroDistrict),
"Guarda District" => Ok(Self::GuardaDistrict),
"Leiria District" => Ok(Self::LeiriaDistrict),
"Lisbon District" => Ok(Self::LisbonDistrict),
"Madeira" => Ok(Self::Madeira),
"Portalegre District" => Ok(Self::PortalegreDistrict),
"Porto District" => Ok(Self::PortoDistrict),
"Santarém District" => Ok(Self::SantaremDistrict),
"Setúbal District" => Ok(Self::SetubalDistrict),
"Viana do Castelo District" => Ok(Self::VianaDoCasteloDistrict),
"Vila Real District" => Ok(Self::VilaRealDistrict),
"Viseu District" => Ok(Self::ViseuDistrict),
"Évora District" => Ok(Self::EvoraDistrict),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for SwitzerlandStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "SwitzerlandStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Aargau" => Ok(Self::Aargau),
"Appenzell Ausserrhoden" => Ok(Self::AppenzellAusserrhoden),
"Appenzell Innerrhoden" => Ok(Self::AppenzellInnerrhoden),
"Basel-Landschaft" => Ok(Self::BaselLandschaft),
"Canton of Fribourg" => Ok(Self::CantonOfFribourg),
"Canton of Geneva" => Ok(Self::CantonOfGeneva),
"Canton of Jura" => Ok(Self::CantonOfJura),
"Canton of Lucerne" => Ok(Self::CantonOfLucerne),
"Canton of Neuchâtel" => Ok(Self::CantonOfNeuchatel),
"Canton of Schaffhausen" => Ok(Self::CantonOfSchaffhausen),
"Canton of Solothurn" => Ok(Self::CantonOfSolothurn),
"Canton of St. Gallen" => Ok(Self::CantonOfStGallen),
"Canton of Valais" => Ok(Self::CantonOfValais),
"Canton of Vaud" => Ok(Self::CantonOfVaud),
"Canton of Zug" => Ok(Self::CantonOfZug),
"Glarus" => Ok(Self::Glarus),
"Graubünden" => Ok(Self::Graubunden),
"Nidwalden" => Ok(Self::Nidwalden),
"Obwalden" => Ok(Self::Obwalden),
"Schwyz" => Ok(Self::Schwyz),
"Thurgau" => Ok(Self::Thurgau),
"Ticino" => Ok(Self::Ticino),
"Uri" => Ok(Self::Uri),
"canton of Bern" => Ok(Self::CantonOfBern),
"canton of Zürich" => Ok(Self::CantonOfZurich),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for NorthMacedoniaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "NorthMacedoniaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Aerodrom Municipality" => Ok(Self::AerodromMunicipality),
"Aračinovo Municipality" => Ok(Self::AracinovoMunicipality),
"Berovo Municipality" => Ok(Self::BerovoMunicipality),
"Bitola Municipality" => Ok(Self::BitolaMunicipality),
"Bogdanci Municipality" => Ok(Self::BogdanciMunicipality),
"Bogovinje Municipality" => Ok(Self::BogovinjeMunicipality),
"Bosilovo Municipality" => Ok(Self::BosilovoMunicipality),
"Brvenica Municipality" => Ok(Self::BrvenicaMunicipality),
"Butel Municipality" => Ok(Self::ButelMunicipality),
"Centar Municipality" => Ok(Self::CentarMunicipality),
"Centar Župa Municipality" => Ok(Self::CentarZupaMunicipality),
"Debarca Municipality" => Ok(Self::DebarcaMunicipality),
"Delčevo Municipality" => Ok(Self::DelcevoMunicipality),
"Demir Hisar Municipality" => Ok(Self::DemirHisarMunicipality),
"Demir Kapija Municipality" => Ok(Self::DemirKapijaMunicipality),
"Dojran Municipality" => Ok(Self::DojranMunicipality),
"Dolneni Municipality" => Ok(Self::DolneniMunicipality),
"Drugovo Municipality" => Ok(Self::DrugovoMunicipality),
"Gazi Baba Municipality" => Ok(Self::GaziBabaMunicipality),
"Gevgelija Municipality" => Ok(Self::GevgelijaMunicipality),
"Gjorče Petrov Municipality" => Ok(Self::GjorcePetrovMunicipality),
"Gostivar Municipality" => Ok(Self::GostivarMunicipality),
"Gradsko Municipality" => Ok(Self::GradskoMunicipality),
"Greater Skopje" => Ok(Self::GreaterSkopje),
"Ilinden Municipality" => Ok(Self::IlindenMunicipality),
"Jegunovce Municipality" => Ok(Self::JegunovceMunicipality),
"Karbinci" => Ok(Self::Karbinci),
"Karpoš Municipality" => Ok(Self::KarposMunicipality),
"Kavadarci Municipality" => Ok(Self::KavadarciMunicipality),
"Kisela Voda Municipality" => Ok(Self::KiselaVodaMunicipality),
"Kičevo Municipality" => Ok(Self::KicevoMunicipality),
"Konče Municipality" => Ok(Self::KonceMunicipality),
"Kočani Municipality" => Ok(Self::KocaniMunicipality),
"Kratovo Municipality" => Ok(Self::KratovoMunicipality),
"Kriva Palanka Municipality" => Ok(Self::KrivaPalankaMunicipality),
"Krivogaštani Municipality" => Ok(Self::KrivogastaniMunicipality),
"Kruševo Municipality" => Ok(Self::KrusevoMunicipality),
"Kumanovo Municipality" => Ok(Self::KumanovoMunicipality),
"Lipkovo Municipality" => Ok(Self::LipkovoMunicipality),
"Lozovo Municipality" => Ok(Self::LozovoMunicipality),
"Makedonska Kamenica Municipality" => Ok(Self::MakedonskaKamenicaMunicipality),
"Makedonski Brod Municipality" => Ok(Self::MakedonskiBrodMunicipality),
"Mavrovo and Rostuša Municipality" => Ok(Self::MavrovoAndRostusaMunicipality),
"Mogila Municipality" => Ok(Self::MogilaMunicipality),
"Negotino Municipality" => Ok(Self::NegotinoMunicipality),
"Novaci Municipality" => Ok(Self::NovaciMunicipality),
"Novo Selo Municipality" => Ok(Self::NovoSeloMunicipality),
"Ohrid Municipality" => Ok(Self::OhridMunicipality),
"Oslomej Municipality" => Ok(Self::OslomejMunicipality),
"Pehčevo Municipality" => Ok(Self::PehcevoMunicipality),
"Petrovec Municipality" => Ok(Self::PetrovecMunicipality),
"Plasnica Municipality" => Ok(Self::PlasnicaMunicipality),
"Prilep Municipality" => Ok(Self::PrilepMunicipality),
"Probištip Municipality" => Ok(Self::ProbishtipMunicipality),
"Radoviš Municipality" => Ok(Self::RadovisMunicipality),
"Rankovce Municipality" => Ok(Self::RankovceMunicipality),
"Resen Municipality" => Ok(Self::ResenMunicipality),
"Rosoman Municipality" => Ok(Self::RosomanMunicipality),
"Saraj Municipality" => Ok(Self::SarajMunicipality),
"Sopište Municipality" => Ok(Self::SopisteMunicipality),
"Staro Nagoričane Municipality" => Ok(Self::StaroNagoricaneMunicipality),
"Struga Municipality" => Ok(Self::StrugaMunicipality),
"Strumica Municipality" => Ok(Self::StrumicaMunicipality),
"Studeničani Municipality" => Ok(Self::StudenicaniMunicipality),
"Sveti Nikole Municipality" => Ok(Self::SvetiNikoleMunicipality),
"Tearce Municipality" => Ok(Self::TearceMunicipality),
"Tetovo Municipality" => Ok(Self::TetovoMunicipality),
"Valandovo Municipality" => Ok(Self::ValandovoMunicipality),
"Vasilevo Municipality" => Ok(Self::VasilevoMunicipality),
"Veles Municipality" => Ok(Self::VelesMunicipality),
"Vevčani Municipality" => Ok(Self::VevcaniMunicipality),
"Vinica Municipality" => Ok(Self::VinicaMunicipality),
"Vraneštica Municipality" => Ok(Self::VranesticaMunicipality),
"Vrapčište Municipality" => Ok(Self::VrapcisteMunicipality),
"Zajas Municipality" => Ok(Self::ZajasMunicipality),
"Zelenikovo Municipality" => Ok(Self::ZelenikovoMunicipality),
"Zrnovci Municipality" => Ok(Self::ZrnovciMunicipality),
"Čair Municipality" => Ok(Self::CairMunicipality),
"Čaška Municipality" => Ok(Self::CaskaMunicipality),
"Češinovo-Obleševo Municipality" => Ok(Self::CesinovoOblesevoMunicipality),
"Čučer-Sandevo Municipality" => Ok(Self::CucerSandevoMunicipality),
"Štip Municipality" => Ok(Self::StipMunicipality),
"Šuto Orizari Municipality" => Ok(Self::ShutoOrizariMunicipality),
"Želino Municipality" => Ok(Self::ZelinoMunicipality),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for MontenegroStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "MontenegroStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Andrijevica Municipality" => Ok(Self::AndrijevicaMunicipality),
"Bar Municipality" => Ok(Self::BarMunicipality),
"Berane Municipality" => Ok(Self::BeraneMunicipality),
"Bijelo Polje Municipality" => Ok(Self::BijeloPoljeMunicipality),
"Budva Municipality" => Ok(Self::BudvaMunicipality),
"Danilovgrad Municipality" => Ok(Self::DanilovgradMunicipality),
"Gusinje Municipality" => Ok(Self::GusinjeMunicipality),
"Kolašin Municipality" => Ok(Self::KolasinMunicipality),
"Kotor Municipality" => Ok(Self::KotorMunicipality),
"Mojkovac Municipality" => Ok(Self::MojkovacMunicipality),
"Nikšić Municipality" => Ok(Self::NiksicMunicipality),
"Petnjica Municipality" => Ok(Self::PetnjicaMunicipality),
"Plav Municipality" => Ok(Self::PlavMunicipality),
"Pljevlja Municipality" => Ok(Self::PljevljaMunicipality),
"Plužine Municipality" => Ok(Self::PlužineMunicipality),
"Podgorica Municipality" => Ok(Self::PodgoricaMunicipality),
"Rožaje Municipality" => Ok(Self::RožajeMunicipality),
"Tivat Municipality" => Ok(Self::TivatMunicipality),
"Ulcinj Municipality" => Ok(Self::UlcinjMunicipality),
"Žabljak Municipality" => Ok(Self::ŽabljakMunicipality),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for MonacoStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "MonacoStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Monaco" => Ok(Self::Monaco),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for NetherlandsStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "NetherlandsStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Bonaire" => Ok(Self::Bonaire),
"Drenthe" => Ok(Self::Drenthe),
"Flevoland" => Ok(Self::Flevoland),
"Friesland" => Ok(Self::Friesland),
"Gelderland" => Ok(Self::Gelderland),
"Groningen" => Ok(Self::Groningen),
"Limburg" => Ok(Self::Limburg),
"North Brabant" => Ok(Self::NorthBrabant),
"North Holland" => Ok(Self::NorthHolland),
"Overijssel" => Ok(Self::Overijssel),
"Saba" => Ok(Self::Saba),
"Sint Eustatius" => Ok(Self::SintEustatius),
"South Holland" => Ok(Self::SouthHolland),
"Utrecht" => Ok(Self::Utrecht),
"Zeeland" => Ok(Self::Zeeland),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for MoldovaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "MoldovaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Anenii Noi District" => Ok(Self::AneniiNoiDistrict),
"Basarabeasca District" => Ok(Self::BasarabeascaDistrict),
"Bender Municipality" => Ok(Self::BenderMunicipality),
"Briceni District" => Ok(Self::BriceniDistrict),
"Bălți Municipality" => Ok(Self::BălțiMunicipality),
"Cahul District" => Ok(Self::CahulDistrict),
"Cantemir District" => Ok(Self::CantemirDistrict),
"Chișinău Municipality" => Ok(Self::ChișinăuMunicipality),
"Cimișlia District" => Ok(Self::CimișliaDistrict),
"Criuleni District" => Ok(Self::CriuleniDistrict),
"Călărași District" => Ok(Self::CălărașiDistrict),
"Căușeni District" => Ok(Self::CăușeniDistrict),
"Dondușeni District" => Ok(Self::DondușeniDistrict),
"Drochia District" => Ok(Self::DrochiaDistrict),
"Dubăsari District" => Ok(Self::DubăsariDistrict),
"Edineț District" => Ok(Self::EdinețDistrict),
"Florești District" => Ok(Self::FloreștiDistrict),
"Fălești District" => Ok(Self::FăleștiDistrict),
"Găgăuzia" => Ok(Self::Găgăuzia),
"Glodeni District" => Ok(Self::GlodeniDistrict),
"Hîncești District" => Ok(Self::HînceștiDistrict),
"Ialoveni District" => Ok(Self::IaloveniDistrict),
"Nisporeni District" => Ok(Self::NisporeniDistrict),
"Ocnița District" => Ok(Self::OcnițaDistrict),
"Orhei District" => Ok(Self::OrheiDistrict),
"Rezina District" => Ok(Self::RezinaDistrict),
"Rîșcani District" => Ok(Self::RîșcaniDistrict),
"Soroca District" => Ok(Self::SorocaDistrict),
"Strășeni District" => Ok(Self::StrășeniDistrict),
"Sîngerei District" => Ok(Self::SîngereiDistrict),
"Taraclia District" => Ok(Self::TaracliaDistrict),
"Telenești District" => Ok(Self::TeleneștiDistrict),
"Transnistria Autonomous Territorial Unit" => {
Ok(Self::TransnistriaAutonomousTerritorialUnit)
}
"Ungheni District" => Ok(Self::UngheniDistrict),
"Șoldănești District" => Ok(Self::ȘoldăneștiDistrict),
"Ștefan Vodă District" => Ok(Self::ȘtefanVodăDistrict),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for LithuaniaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "LithuaniaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Akmenė District Municipality" => Ok(Self::AkmeneDistrictMunicipality),
"Alytus City Municipality" => Ok(Self::AlytusCityMunicipality),
"Alytus County" => Ok(Self::AlytusCounty),
"Alytus District Municipality" => Ok(Self::AlytusDistrictMunicipality),
"Birštonas Municipality" => Ok(Self::BirstonasMunicipality),
"Biržai District Municipality" => Ok(Self::BirzaiDistrictMunicipality),
"Druskininkai municipality" => Ok(Self::DruskininkaiMunicipality),
"Elektrėnai municipality" => Ok(Self::ElektrenaiMunicipality),
"Ignalina District Municipality" => Ok(Self::IgnalinaDistrictMunicipality),
"Jonava District Municipality" => Ok(Self::JonavaDistrictMunicipality),
"Joniškis District Municipality" => Ok(Self::JoniskisDistrictMunicipality),
"Jurbarkas District Municipality" => Ok(Self::JurbarkasDistrictMunicipality),
"Kaišiadorys District Municipality" => Ok(Self::KaisiadorysDistrictMunicipality),
"Kalvarija municipality" => Ok(Self::KalvarijaMunicipality),
"Kaunas City Municipality" => Ok(Self::KaunasCityMunicipality),
"Kaunas County" => Ok(Self::KaunasCounty),
"Kaunas District Municipality" => Ok(Self::KaunasDistrictMunicipality),
"Kazlų Rūda municipality" => Ok(Self::KazluRudaMunicipality),
"Kelmė District Municipality" => Ok(Self::KelmeDistrictMunicipality),
"Klaipeda City Municipality" => Ok(Self::KlaipedaCityMunicipality),
"Klaipėda County" => Ok(Self::KlaipedaCounty),
"Klaipėda District Municipality" => Ok(Self::KlaipedaDistrictMunicipality),
"Kretinga District Municipality" => Ok(Self::KretingaDistrictMunicipality),
"Kupiškis District Municipality" => Ok(Self::KupiskisDistrictMunicipality),
"Kėdainiai District Municipality" => Ok(Self::KedainiaiDistrictMunicipality),
"Lazdijai District Municipality" => Ok(Self::LazdijaiDistrictMunicipality),
"Marijampolė County" => Ok(Self::MarijampoleCounty),
"Marijampolė Municipality" => Ok(Self::MarijampoleMunicipality),
"Mažeikiai District Municipality" => Ok(Self::MazeikiaiDistrictMunicipality),
"Molėtai District Municipality" => Ok(Self::MoletaiDistrictMunicipality),
"Neringa Municipality" => Ok(Self::NeringaMunicipality),
"Pagėgiai municipality" => Ok(Self::PagegiaiMunicipality),
"Pakruojis District Municipality" => Ok(Self::PakruojisDistrictMunicipality),
"Palanga City Municipality" => Ok(Self::PalangaCityMunicipality),
"Panevėžys City Municipality" => Ok(Self::PanevezysCityMunicipality),
"Panevėžys County" => Ok(Self::PanevezysCounty),
"Panevėžys District Municipality" => Ok(Self::PanevezysDistrictMunicipality),
"Pasvalys District Municipality" => Ok(Self::PasvalysDistrictMunicipality),
"Plungė District Municipality" => Ok(Self::PlungeDistrictMunicipality),
"Prienai District Municipality" => Ok(Self::PrienaiDistrictMunicipality),
"Radviliškis District Municipality" => Ok(Self::RadviliskisDistrictMunicipality),
"Raseiniai District Municipality" => Ok(Self::RaseiniaiDistrictMunicipality),
"Rietavas municipality" => Ok(Self::RietavasMunicipality),
"Rokiškis District Municipality" => Ok(Self::RokiskisDistrictMunicipality),
"Skuodas District Municipality" => Ok(Self::SkuodasDistrictMunicipality),
"Tauragė County" => Ok(Self::TaurageCounty),
"Tauragė District Municipality" => Ok(Self::TaurageDistrictMunicipality),
"Telšiai County" => Ok(Self::TelsiaiCounty),
"Telšiai District Municipality" => Ok(Self::TelsiaiDistrictMunicipality),
"Trakai District Municipality" => Ok(Self::TrakaiDistrictMunicipality),
"Ukmergė District Municipality" => Ok(Self::UkmergeDistrictMunicipality),
"Utena County" => Ok(Self::UtenaCounty),
"Utena District Municipality" => Ok(Self::UtenaDistrictMunicipality),
"Varėna District Municipality" => Ok(Self::VarenaDistrictMunicipality),
"Vilkaviškis District Municipality" => Ok(Self::VilkaviskisDistrictMunicipality),
"Vilnius City Municipality" => Ok(Self::VilniusCityMunicipality),
"Vilnius County" => Ok(Self::VilniusCounty),
"Vilnius District Municipality" => Ok(Self::VilniusDistrictMunicipality),
"Visaginas Municipality" => Ok(Self::VisaginasMunicipality),
"Zarasai District Municipality" => Ok(Self::ZarasaiDistrictMunicipality),
"Šakiai District Municipality" => Ok(Self::SakiaiDistrictMunicipality),
"Šalčininkai District Municipality" => Ok(Self::SalcininkaiDistrictMunicipality),
"Šiauliai City Municipality" => Ok(Self::SiauliaiCityMunicipality),
"Šiauliai County" => Ok(Self::SiauliaiCounty),
"Šiauliai District Municipality" => Ok(Self::SiauliaiDistrictMunicipality),
"Šilalė District Municipality" => Ok(Self::SilaleDistrictMunicipality),
"Šilutė District Municipality" => Ok(Self::SiluteDistrictMunicipality),
"Širvintos District Municipality" => Ok(Self::SirvintosDistrictMunicipality),
"Švenčionys District Municipality" => Ok(Self::SvencionysDistrictMunicipality),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for LiechtensteinStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "LiechtensteinStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Balzers" => Ok(Self::Balzers),
"Eschen" => Ok(Self::Eschen),
"Gamprin" => Ok(Self::Gamprin),
"Mauren" => Ok(Self::Mauren),
"Planken" => Ok(Self::Planken),
"Ruggell" => Ok(Self::Ruggell),
"Schaan" => Ok(Self::Schaan),
"Schellenberg" => Ok(Self::Schellenberg),
"Triesen" => Ok(Self::Triesen),
"Triesenberg" => Ok(Self::Triesenberg),
"Vaduz" => Ok(Self::Vaduz),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for LatviaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "LatviaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Aglona Municipality" => Ok(Self::AglonaMunicipality),
"Aizkraukle Municipality" => Ok(Self::AizkraukleMunicipality),
"Aizpute Municipality" => Ok(Self::AizputeMunicipality),
"Aknīste Municipality" => Ok(Self::AknīsteMunicipality),
"Aloja Municipality" => Ok(Self::AlojaMunicipality),
"Alsunga Municipality" => Ok(Self::AlsungaMunicipality),
"Alūksne Municipality" => Ok(Self::AlūksneMunicipality),
"Amata Municipality" => Ok(Self::AmataMunicipality),
"Ape Municipality" => Ok(Self::ApeMunicipality),
"Auce Municipality" => Ok(Self::AuceMunicipality),
"Babīte Municipality" => Ok(Self::BabīteMunicipality),
"Baldone Municipality" => Ok(Self::BaldoneMunicipality),
"Baltinava Municipality" => Ok(Self::BaltinavaMunicipality),
"Balvi Municipality" => Ok(Self::BalviMunicipality),
"Bauska Municipality" => Ok(Self::BauskaMunicipality),
"Beverīna Municipality" => Ok(Self::BeverīnaMunicipality),
"Brocēni Municipality" => Ok(Self::BrocēniMunicipality),
"Burtnieki Municipality" => Ok(Self::BurtniekiMunicipality),
"Carnikava Municipality" => Ok(Self::CarnikavaMunicipality),
"Cesvaine Municipality" => Ok(Self::CesvaineMunicipality),
"Cibla Municipality" => Ok(Self::CiblaMunicipality),
"Cēsis Municipality" => Ok(Self::CēsisMunicipality),
"Dagda Municipality" => Ok(Self::DagdaMunicipality),
"Daugavpils" => Ok(Self::Daugavpils),
"Daugavpils Municipality" => Ok(Self::DaugavpilsMunicipality),
"Dobele Municipality" => Ok(Self::DobeleMunicipality),
"Dundaga Municipality" => Ok(Self::DundagaMunicipality),
"Durbe Municipality" => Ok(Self::DurbeMunicipality),
"Engure Municipality" => Ok(Self::EngureMunicipality),
"Garkalne Municipality" => Ok(Self::GarkalneMunicipality),
"Grobiņa Municipality" => Ok(Self::GrobiņaMunicipality),
"Gulbene Municipality" => Ok(Self::GulbeneMunicipality),
"Iecava Municipality" => Ok(Self::IecavaMunicipality),
"Ikšķile Municipality" => Ok(Self::IkšķileMunicipality),
"Ilūkste Municipalityy" => Ok(Self::IlūksteMunicipality),
"Inčukalns Municipality" => Ok(Self::InčukalnsMunicipality),
"Jaunjelgava Municipality" => Ok(Self::JaunjelgavaMunicipality),
"Jaunpiebalga Municipality" => Ok(Self::JaunpiebalgaMunicipality),
"Jaunpils Municipality" => Ok(Self::JaunpilsMunicipality),
"Jelgava" => Ok(Self::Jelgava),
"Jelgava Municipality" => Ok(Self::JelgavaMunicipality),
"Jēkabpils" => Ok(Self::Jēkabpils),
"Jēkabpils Municipality" => Ok(Self::JēkabpilsMunicipality),
"Jūrmala" => Ok(Self::Jūrmala),
"Kandava Municipality" => Ok(Self::KandavaMunicipality),
"Kocēni Municipality" => Ok(Self::KocēniMunicipality),
"Koknese Municipality" => Ok(Self::KokneseMunicipality),
"Krimulda Municipality" => Ok(Self::KrimuldaMunicipality),
"Krustpils Municipality" => Ok(Self::KrustpilsMunicipality),
"Krāslava Municipality" => Ok(Self::KrāslavaMunicipality),
"Kuldīga Municipality" => Ok(Self::KuldīgaMunicipality),
"Kārsava Municipality" => Ok(Self::KārsavaMunicipality),
"Lielvārde Municipality" => Ok(Self::LielvārdeMunicipality),
"Liepāja" => Ok(Self::Liepāja),
"Limbaži Municipality" => Ok(Self::LimbažiMunicipality),
"Lubāna Municipality" => Ok(Self::LubānaMunicipality),
"Ludza Municipality" => Ok(Self::LudzaMunicipality),
"Līgatne Municipality" => Ok(Self::LīgatneMunicipality),
"Līvāni Municipality" => Ok(Self::LīvāniMunicipality),
"Madona Municipality" => Ok(Self::MadonaMunicipality),
"Mazsalaca Municipality" => Ok(Self::MazsalacaMunicipality),
"Mālpils Municipality" => Ok(Self::MālpilsMunicipality),
"Mārupe Municipality" => Ok(Self::MārupeMunicipality),
"Mērsrags Municipality" => Ok(Self::MērsragsMunicipality),
"Naukšēni Municipality" => Ok(Self::NaukšēniMunicipality),
"Nereta Municipality" => Ok(Self::NeretaMunicipality),
"Nīca Municipality" => Ok(Self::NīcaMunicipality),
"Ogre Municipality" => Ok(Self::OgreMunicipality),
"Olaine Municipality" => Ok(Self::OlaineMunicipality),
"Ozolnieki Municipality" => Ok(Self::OzolniekiMunicipality),
"Preiļi Municipality" => Ok(Self::PreiļiMunicipality),
"Priekule Municipality" => Ok(Self::PriekuleMunicipality),
"Priekuļi Municipality" => Ok(Self::PriekuļiMunicipality),
"Pārgauja Municipality" => Ok(Self::PārgaujaMunicipality),
"Pāvilosta Municipality" => Ok(Self::PāvilostaMunicipality),
"Pļaviņas Municipality" => Ok(Self::PļaviņasMunicipality),
"Rauna Municipality" => Ok(Self::RaunaMunicipality),
"Riebiņi Municipality" => Ok(Self::RiebiņiMunicipality),
"Riga" => Ok(Self::Riga),
"Roja Municipality" => Ok(Self::RojaMunicipality),
"Ropaži Municipality" => Ok(Self::RopažiMunicipality),
"Rucava Municipality" => Ok(Self::RucavaMunicipality),
"Rugāji Municipality" => Ok(Self::RugājiMunicipality),
"Rundāle Municipality" => Ok(Self::RundāleMunicipality),
"Rēzekne" => Ok(Self::Rēzekne),
"Rēzekne Municipality" => Ok(Self::RēzekneMunicipality),
"Rūjiena Municipality" => Ok(Self::RūjienaMunicipality),
"Sala Municipality" => Ok(Self::SalaMunicipality),
"Salacgrīva Municipality" => Ok(Self::SalacgrīvaMunicipality),
"Salaspils Municipality" => Ok(Self::SalaspilsMunicipality),
"Saldus Municipality" => Ok(Self::SaldusMunicipality),
"Saulkrasti Municipality" => Ok(Self::SaulkrastiMunicipality),
"Sigulda Municipality" => Ok(Self::SiguldaMunicipality),
"Skrunda Municipality" => Ok(Self::SkrundaMunicipality),
"Skrīveri Municipality" => Ok(Self::SkrīveriMunicipality),
"Smiltene Municipality" => Ok(Self::SmilteneMunicipality),
"Stopiņi Municipality" => Ok(Self::StopiņiMunicipality),
"Strenči Municipality" => Ok(Self::StrenčiMunicipality),
"Sēja Municipality" => Ok(Self::SējaMunicipality),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for MaltaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "MaltaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Attard" => Ok(Self::Attard),
"Balzan" => Ok(Self::Balzan),
"Birgu" => Ok(Self::Birgu),
"Birkirkara" => Ok(Self::Birkirkara),
"Birżebbuġa" => Ok(Self::Birżebbuġa),
"Cospicua" => Ok(Self::Cospicua),
"Dingli" => Ok(Self::Dingli),
"Fgura" => Ok(Self::Fgura),
"Floriana" => Ok(Self::Floriana),
"Fontana" => Ok(Self::Fontana),
"Gudja" => Ok(Self::Gudja),
"Gżira" => Ok(Self::Gżira),
"Għajnsielem" => Ok(Self::Għajnsielem),
"Għarb" => Ok(Self::Għarb),
"Għargħur" => Ok(Self::Għargħur),
"Għasri" => Ok(Self::Għasri),
"Għaxaq" => Ok(Self::Għaxaq),
"Ħamrun" => Ok(Self::Ħamrun),
"Iklin" => Ok(Self::Iklin),
"Senglea" => Ok(Self::Senglea),
"Kalkara" => Ok(Self::Kalkara),
"Kerċem" => Ok(Self::Kerċem),
"Kirkop" => Ok(Self::Kirkop),
"Lija" => Ok(Self::Lija),
"Luqa" => Ok(Self::Luqa),
"Marsa" => Ok(Self::Marsa),
"Marsaskala" => Ok(Self::Marsaskala),
"Marsaxlokk" => Ok(Self::Marsaxlokk),
"Mdina" => Ok(Self::Mdina),
"Mellieħa" => Ok(Self::Mellieħa),
"Mosta" => Ok(Self::Mosta),
"Mqabba" => Ok(Self::Mqabba),
"Msida" => Ok(Self::Msida),
"Mtarfa" => Ok(Self::Mtarfa),
"Munxar" => Ok(Self::Munxar),
"Mġarr" => Ok(Self::Mġarr),
"Nadur" => Ok(Self::Nadur),
"Naxxar" => Ok(Self::Naxxar),
"Paola" => Ok(Self::Paola),
"Pembroke" => Ok(Self::Pembroke),
"Pietà" => Ok(Self::Pietà),
"Qala" => Ok(Self::Qala),
"Qormi" => Ok(Self::Qormi),
"Qrendi" => Ok(Self::Qrendi),
"Rabat" => Ok(Self::Rabat),
"Saint Lawrence" => Ok(Self::SaintLawrence),
"San Ġwann" => Ok(Self::SanĠwann),
"Sannat" => Ok(Self::Sannat),
"Santa Luċija" => Ok(Self::SantaLuċija),
"Santa Venera" => Ok(Self::SantaVenera),
"Siġġiewi" => Ok(Self::Siġġiewi),
"Sliema" => Ok(Self::Sliema),
"St. Julian's" => Ok(Self::StJulians),
"St. Paul's Bay" => Ok(Self::StPaulsBay),
"Swieqi" => Ok(Self::Swieqi),
"Ta' Xbiex" => Ok(Self::TaXbiex),
"Tarxien" => Ok(Self::Tarxien),
"Valletta" => Ok(Self::Valletta),
"Victoria" => Ok(Self::Victoria),
"Xagħra" => Ok(Self::Xagħra),
"Xewkija" => Ok(Self::Xewkija),
"Xgħajra" => Ok(Self::Xgħajra),
"Żabbar" => Ok(Self::Żabbar),
"Żebbuġ Gozo" => Ok(Self::ŻebbuġGozo),
"Żebbuġ Malta" => Ok(Self::ŻebbuġMalta),
"Żejtun" => Ok(Self::Żejtun),
"Żurrieq" => Ok(Self::Żurrieq),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for BelarusStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "BelarusStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Brest Region" => Ok(Self::BrestRegion),
"Gomel Region" => Ok(Self::GomelRegion),
"Grodno Region" => Ok(Self::GrodnoRegion),
"Minsk" => Ok(Self::Minsk),
"Minsk Region" => Ok(Self::MinskRegion),
"Mogilev Region" => Ok(Self::MogilevRegion),
"Vitebsk Region" => Ok(Self::VitebskRegion),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for IrelandStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "IrelandStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Connacht" => Ok(Self::Connacht),
"County Carlow" => Ok(Self::CountyCarlow),
"County Cavan" => Ok(Self::CountyCavan),
"County Clare" => Ok(Self::CountyClare),
"County Cork" => Ok(Self::CountyCork),
"County Donegal" => Ok(Self::CountyDonegal),
"County Dublin" => Ok(Self::CountyDublin),
"County Galway" => Ok(Self::CountyGalway),
"County Kerry" => Ok(Self::CountyKerry),
"County Kildare" => Ok(Self::CountyKildare),
"County Kilkenny" => Ok(Self::CountyKilkenny),
"County Laois" => Ok(Self::CountyLaois),
"County Limerick" => Ok(Self::CountyLimerick),
"County Longford" => Ok(Self::CountyLongford),
"County Louth" => Ok(Self::CountyLouth),
"County Mayo" => Ok(Self::CountyMayo),
"County Meath" => Ok(Self::CountyMeath),
"County Monaghan" => Ok(Self::CountyMonaghan),
"County Offaly" => Ok(Self::CountyOffaly),
"County Roscommon" => Ok(Self::CountyRoscommon),
"County Sligo" => Ok(Self::CountySligo),
"County Tipperary" => Ok(Self::CountyTipperary),
"County Waterford" => Ok(Self::CountyWaterford),
"County Westmeath" => Ok(Self::CountyWestmeath),
"County Wexford" => Ok(Self::CountyWexford),
"County Wicklow" => Ok(Self::CountyWicklow),
"Leinster" => Ok(Self::Leinster),
"Munster" => Ok(Self::Munster),
"Ulster" => Ok(Self::Ulster),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for IcelandStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "IcelandStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Capital Region" => Ok(Self::CapitalRegion),
"Eastern Region" => Ok(Self::EasternRegion),
"Northeastern Region" => Ok(Self::NortheasternRegion),
"Northwestern Region" => Ok(Self::NorthwesternRegion),
"Southern Peninsula Region" => Ok(Self::SouthernPeninsulaRegion),
"Southern Region" => Ok(Self::SouthernRegion),
"Western Region" => Ok(Self::WesternRegion),
"Westfjords" => Ok(Self::Westfjords),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for HungaryStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "HungaryStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Baranya County" => Ok(Self::BaranyaCounty),
"Borsod-Abaúj-Zemplén County" => Ok(Self::BorsodAbaujZemplenCounty),
"Budapest" => Ok(Self::Budapest),
"Bács-Kiskun County" => Ok(Self::BacsKiskunCounty),
"Békés County" => Ok(Self::BekesCounty),
"Békéscsaba" => Ok(Self::Bekescsaba),
"Csongrád County" => Ok(Self::CsongradCounty),
"Debrecen" => Ok(Self::Debrecen),
"Dunaújváros" => Ok(Self::Dunaujvaros),
"Eger" => Ok(Self::Eger),
"Fejér County" => Ok(Self::FejerCounty),
"Győr" => Ok(Self::Gyor),
"Győr-Moson-Sopron County" => Ok(Self::GyorMosonSopronCounty),
"Hajdú-Bihar County" => Ok(Self::HajduBiharCounty),
"Heves County" => Ok(Self::HevesCounty),
"Hódmezővásárhely" => Ok(Self::Hodmezovasarhely),
"Jász-Nagykun-Szolnok County" => Ok(Self::JaszNagykunSzolnokCounty),
"Kaposvár" => Ok(Self::Kaposvar),
"Kecskemét" => Ok(Self::Kecskemet),
"Miskolc" => Ok(Self::Miskolc),
"Nagykanizsa" => Ok(Self::Nagykanizsa),
"Nyíregyháza" => Ok(Self::Nyiregyhaza),
"Nógrád County" => Ok(Self::NogradCounty),
"Pest County" => Ok(Self::PestCounty),
"Pécs" => Ok(Self::Pecs),
"Salgótarján" => Ok(Self::Salgotarjan),
"Somogy County" => Ok(Self::SomogyCounty),
"Sopron" => Ok(Self::Sopron),
"Szabolcs-Szatmár-Bereg County" => Ok(Self::SzabolcsSzatmarBeregCounty),
"Szeged" => Ok(Self::Szeged),
"Szekszárd" => Ok(Self::Szekszard),
"Szolnok" => Ok(Self::Szolnok),
"Szombathely" => Ok(Self::Szombathely),
"Székesfehérvár" => Ok(Self::Szekesfehervar),
"Tatabánya" => Ok(Self::Tatabanya),
"Tolna County" => Ok(Self::TolnaCounty),
"Vas County" => Ok(Self::VasCounty),
"Veszprém" => Ok(Self::Veszprem),
"Veszprém County" => Ok(Self::VeszpremCounty),
"Zala County" => Ok(Self::ZalaCounty),
"Zalaegerszeg" => Ok(Self::Zalaegerszeg),
"Érd" => Ok(Self::Erd),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for GreeceStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "GreeceStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Achaea Regional Unit" => Ok(Self::AchaeaRegionalUnit),
"Aetolia-Acarnania Regional Unit" => Ok(Self::AetoliaAcarnaniaRegionalUnit),
"Arcadia Prefecture" => Ok(Self::ArcadiaPrefecture),
"Argolis Regional Unit" => Ok(Self::ArgolisRegionalUnit),
"Attica Region" => Ok(Self::AtticaRegion),
"Boeotia Regional Unit" => Ok(Self::BoeotiaRegionalUnit),
"Central Greece Region" => Ok(Self::CentralGreeceRegion),
"Central Macedonia" => Ok(Self::CentralMacedonia),
"Chania Regional Unit" => Ok(Self::ChaniaRegionalUnit),
"Corfu Prefecture" => Ok(Self::CorfuPrefecture),
"Corinthia Regional Unit" => Ok(Self::CorinthiaRegionalUnit),
"Crete Region" => Ok(Self::CreteRegion),
"Drama Regional Unit" => Ok(Self::DramaRegionalUnit),
"East Attica Regional Unit" => Ok(Self::EastAtticaRegionalUnit),
"East Macedonia and Thrace" => Ok(Self::EastMacedoniaAndThrace),
"Epirus Region" => Ok(Self::EpirusRegion),
"Euboea" => Ok(Self::Euboea),
"Grevena Prefecture" => Ok(Self::GrevenaPrefecture),
"Imathia Regional Unit" => Ok(Self::ImathiaRegionalUnit),
"Ioannina Regional Unit" => Ok(Self::IoanninaRegionalUnit),
"Ionian Islands Region" => Ok(Self::IonianIslandsRegion),
"Karditsa Regional Unit" => Ok(Self::KarditsaRegionalUnit),
"Kastoria Regional Unit" => Ok(Self::KastoriaRegionalUnit),
"Kefalonia Prefecture" => Ok(Self::KefaloniaPrefecture),
"Kilkis Regional Unit" => Ok(Self::KilkisRegionalUnit),
"Kozani Prefecture" => Ok(Self::KozaniPrefecture),
"Laconia" => Ok(Self::Laconia),
"Larissa Prefecture" => Ok(Self::LarissaPrefecture),
"Lefkada Regional Unit" => Ok(Self::LefkadaRegionalUnit),
"Pella Regional Unit" => Ok(Self::PellaRegionalUnit),
"Peloponnese Region" => Ok(Self::PeloponneseRegion),
"Phthiotis Prefecture" => Ok(Self::PhthiotisPrefecture),
"Preveza Prefecture" => Ok(Self::PrevezaPrefecture),
"Serres Prefecture" => Ok(Self::SerresPrefecture),
"South Aegean" => Ok(Self::SouthAegean),
"Thessaloniki Regional Unit" => Ok(Self::ThessalonikiRegionalUnit),
"West Greece Region" => Ok(Self::WestGreeceRegion),
"West Macedonia Region" => Ok(Self::WestMacedoniaRegion),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for FinlandStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "FinlandStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Central Finland" => Ok(Self::CentralFinland),
"Central Ostrobothnia" => Ok(Self::CentralOstrobothnia),
"Eastern Finland Province" => Ok(Self::EasternFinlandProvince),
"Finland Proper" => Ok(Self::FinlandProper),
"Kainuu" => Ok(Self::Kainuu),
"Kymenlaakso" => Ok(Self::Kymenlaakso),
"Lapland" => Ok(Self::Lapland),
"North Karelia" => Ok(Self::NorthKarelia),
"Northern Ostrobothnia" => Ok(Self::NorthernOstrobothnia),
"Northern Savonia" => Ok(Self::NorthernSavonia),
"Ostrobothnia" => Ok(Self::Ostrobothnia),
"Oulu Province" => Ok(Self::OuluProvince),
"Pirkanmaa" => Ok(Self::Pirkanmaa),
"Päijänne Tavastia" => Ok(Self::PaijanneTavastia),
"Satakunta" => Ok(Self::Satakunta),
"South Karelia" => Ok(Self::SouthKarelia),
"Southern Ostrobothnia" => Ok(Self::SouthernOstrobothnia),
"Southern Savonia" => Ok(Self::SouthernSavonia),
"Tavastia Proper" => Ok(Self::TavastiaProper),
"Uusimaa" => Ok(Self::Uusimaa),
"Åland Islands" => Ok(Self::AlandIslands),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for DenmarkStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "DenmarkStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Capital Region of Denmark" => Ok(Self::CapitalRegionOfDenmark),
"Central Denmark Region" => Ok(Self::CentralDenmarkRegion),
"North Denmark Region" => Ok(Self::NorthDenmarkRegion),
"Region Zealand" => Ok(Self::RegionZealand),
"Region of Southern Denmark" => Ok(Self::RegionOfSouthernDenmark),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for CzechRepublicStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "CzechRepublicStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Benešov District" => Ok(Self::BenesovDistrict),
"Beroun District" => Ok(Self::BerounDistrict),
"Blansko District" => Ok(Self::BlanskoDistrict),
"Brno-City District" => Ok(Self::BrnoCityDistrict),
"Brno-Country District" => Ok(Self::BrnoCountryDistrict),
"Bruntál District" => Ok(Self::BruntalDistrict),
"Břeclav District" => Ok(Self::BreclavDistrict),
"Central Bohemian Region" => Ok(Self::CentralBohemianRegion),
"Cheb District" => Ok(Self::ChebDistrict),
"Chomutov District" => Ok(Self::ChomutovDistrict),
"Chrudim District" => Ok(Self::ChrudimDistrict),
"Domažlice Distric" => Ok(Self::DomazliceDistrict),
"Děčín District" => Ok(Self::DecinDistrict),
"Frýdek-Místek District" => Ok(Self::FrydekMistekDistrict),
"Havlíčkův Brod District" => Ok(Self::HavlickuvBrodDistrict),
"Hodonín District" => Ok(Self::HodoninDistrict),
"Horní Počernice" => Ok(Self::HorniPocernice),
"Hradec Králové District" => Ok(Self::HradecKraloveDistrict),
"Hradec Králové Region" => Ok(Self::HradecKraloveRegion),
"Jablonec nad Nisou District" => Ok(Self::JablonecNadNisouDistrict),
"Jeseník District" => Ok(Self::JesenikDistrict),
"Jihlava District" => Ok(Self::JihlavaDistrict),
"Jindřichův Hradec District" => Ok(Self::JindrichuvHradecDistrict),
"Jičín District" => Ok(Self::JicinDistrict),
"Karlovy Vary District" => Ok(Self::KarlovyVaryDistrict),
"Karlovy Vary Region" => Ok(Self::KarlovyVaryRegion),
"Karviná District" => Ok(Self::KarvinaDistrict),
"Kladno District" => Ok(Self::KladnoDistrict),
"Klatovy District" => Ok(Self::KlatovyDistrict),
"Kolín District" => Ok(Self::KolinDistrict),
"Kroměříž District" => Ok(Self::KromerizDistrict),
"Liberec District" => Ok(Self::LiberecDistrict),
"Liberec Region" => Ok(Self::LiberecRegion),
"Litoměřice District" => Ok(Self::LitomericeDistrict),
"Louny District" => Ok(Self::LounyDistrict),
"Mladá Boleslav District" => Ok(Self::MladaBoleslavDistrict),
"Moravian-Silesian Region" => Ok(Self::MoravianSilesianRegion),
"Most District" => Ok(Self::MostDistrict),
"Mělník District" => Ok(Self::MelnikDistrict),
"Nový Jičín District" => Ok(Self::NovyJicinDistrict),
"Nymburk District" => Ok(Self::NymburkDistrict),
"Náchod District" => Ok(Self::NachodDistrict),
"Olomouc District" => Ok(Self::OlomoucDistrict),
"Olomouc Region" => Ok(Self::OlomoucRegion),
"Opava District" => Ok(Self::OpavaDistrict),
"Ostrava-City District" => Ok(Self::OstravaCityDistrict),
"Pardubice District" => Ok(Self::PardubiceDistrict),
"Pardubice Region" => Ok(Self::PardubiceRegion),
"Pelhřimov District" => Ok(Self::PelhrimovDistrict),
"Plzeň Region" => Ok(Self::PlzenRegion),
"Plzeň-City District" => Ok(Self::PlzenCityDistrict),
"Plzeň-North District" => Ok(Self::PlzenNorthDistrict),
"Plzeň-South District" => Ok(Self::PlzenSouthDistrict),
"Prachatice District" => Ok(Self::PrachaticeDistrict),
"Prague" => Ok(Self::Prague),
"Prague 1" => Ok(Self::Prague1),
"Prague 10" => Ok(Self::Prague10),
"Prague 11" => Ok(Self::Prague11),
"Prague 12" => Ok(Self::Prague12),
"Prague 13" => Ok(Self::Prague13),
"Prague 14" => Ok(Self::Prague14),
"Prague 15" => Ok(Self::Prague15),
"Prague 16" => Ok(Self::Prague16),
"Prague 2" => Ok(Self::Prague2),
"Prague 21" => Ok(Self::Prague21),
"Prague 3" => Ok(Self::Prague3),
"Prague 4" => Ok(Self::Prague4),
"Prague 5" => Ok(Self::Prague5),
"Prague 6" => Ok(Self::Prague6),
"Prague 7" => Ok(Self::Prague7),
"Prague 8" => Ok(Self::Prague8),
"Prague 9" => Ok(Self::Prague9),
"Prague-East District" => Ok(Self::PragueEastDistrict),
"Prague-West District" => Ok(Self::PragueWestDistrict),
"Prostějov District" => Ok(Self::ProstejovDistrict),
"Písek District" => Ok(Self::PisekDistrict),
"Přerov District" => Ok(Self::PrerovDistrict),
"Příbram District" => Ok(Self::PribramDistrict),
"Rakovník District" => Ok(Self::RakovnikDistrict),
"Rokycany District" => Ok(Self::RokycanyDistrict),
"Rychnov nad Kněžnou District" => Ok(Self::RychnovNadKneznouDistrict),
"Semily District" => Ok(Self::SemilyDistrict),
"Sokolov District" => Ok(Self::SokolovDistrict),
"South Bohemian Region" => Ok(Self::SouthBohemianRegion),
"South Moravian Region" => Ok(Self::SouthMoravianRegion),
"Strakonice District" => Ok(Self::StrakoniceDistrict),
"Svitavy District" => Ok(Self::SvitavyDistrict),
"Tachov District" => Ok(Self::TachovDistrict),
"Teplice District" => Ok(Self::TepliceDistrict),
"Trutnov District" => Ok(Self::TrutnovDistrict),
"Tábor District" => Ok(Self::TaborDistrict),
"Třebíč District" => Ok(Self::TrebicDistrict),
"Uherské Hradiště District" => Ok(Self::UherskeHradisteDistrict),
"Vsetín District" => Ok(Self::VsetinDistrict),
"Vysočina Region" => Ok(Self::VysocinaRegion),
"Vyškov District" => Ok(Self::VyskovDistrict),
"Zlín District" => Ok(Self::ZlinDistrict),
"Zlín Region" => Ok(Self::ZlinRegion),
"Znojmo District" => Ok(Self::ZnojmoDistrict),
"Ústí nad Labem District" => Ok(Self::UstiNadLabemDistrict),
"Ústí nad Labem Region" => Ok(Self::UstiNadLabemRegion),
"Ústí nad Orlicí District" => Ok(Self::UstiNadOrliciDistrict),
"Česká Lípa District" => Ok(Self::CeskaLipaDistrict),
"České Budějovice District" => Ok(Self::CeskeBudejoviceDistrict),
"Český Krumlov District" => Ok(Self::CeskyKrumlovDistrict),
"Šumperk District" => Ok(Self::SumperkDistrict),
"Žďár nad Sázavou District" => Ok(Self::ZdarNadSazavouDistrict),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for CroatiaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "CroatiaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Bjelovar-Bilogora County" => Ok(Self::BjelovarBilogoraCounty),
"Brod-Posavina County" => Ok(Self::BrodPosavinaCounty),
"Dubrovnik-Neretva County" => Ok(Self::DubrovnikNeretvaCounty),
"Istria County" => Ok(Self::IstriaCounty),
"Koprivnica-Križevci County" => Ok(Self::KoprivnicaKrizevciCounty),
"Krapina-Zagorje County" => Ok(Self::KrapinaZagorjeCounty),
"Lika-Senj County" => Ok(Self::LikaSenjCounty),
"Međimurje County" => Ok(Self::MedimurjeCounty),
"Osijek-Baranja County" => Ok(Self::OsijekBaranjaCounty),
"Požega-Slavonia County" => Ok(Self::PozegaSlavoniaCounty),
"Primorje-Gorski Kotar County" => Ok(Self::PrimorjeGorskiKotarCounty),
"Sisak-Moslavina County" => Ok(Self::SisakMoslavinaCounty),
"Split-Dalmatia County" => Ok(Self::SplitDalmatiaCounty),
"Varaždin County" => Ok(Self::VarazdinCounty),
"Virovitica-Podravina County" => Ok(Self::ViroviticaPodravinaCounty),
"Vukovar-Syrmia County" => Ok(Self::VukovarSyrmiaCounty),
"Zadar County" => Ok(Self::ZadarCounty),
"Zagreb" => Ok(Self::Zagreb),
"Zagreb County" => Ok(Self::ZagrebCounty),
"Šibenik-Knin County" => Ok(Self::SibenikKninCounty),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for BulgariaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "BulgariaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Blagoevgrad Province" => Ok(Self::BlagoevgradProvince),
"Burgas Province" => Ok(Self::BurgasProvince),
"Dobrich Province" => Ok(Self::DobrichProvince),
"Gabrovo Province" => Ok(Self::GabrovoProvince),
"Haskovo Province" => Ok(Self::HaskovoProvince),
"Kardzhali Province" => Ok(Self::KardzhaliProvince),
"Kyustendil Province" => Ok(Self::KyustendilProvince),
"Lovech Province" => Ok(Self::LovechProvince),
"Montana Province" => Ok(Self::MontanaProvince),
"Pazardzhik Province" => Ok(Self::PazardzhikProvince),
"Pernik Province" => Ok(Self::PernikProvince),
"Pleven Province" => Ok(Self::PlevenProvince),
"Plovdiv Province" => Ok(Self::PlovdivProvince),
"Razgrad Province" => Ok(Self::RazgradProvince),
"Ruse Province" => Ok(Self::RuseProvince),
"Shumen" => Ok(Self::Shumen),
"Silistra Province" => Ok(Self::SilistraProvince),
"Sliven Province" => Ok(Self::SlivenProvince),
"Smolyan Province" => Ok(Self::SmolyanProvince),
"Sofia City Province" => Ok(Self::SofiaCityProvince),
"Sofia Province" => Ok(Self::SofiaProvince),
"Stara Zagora Province" => Ok(Self::StaraZagoraProvince),
"Targovishte Provinc" => Ok(Self::TargovishteProvince),
"Varna Province" => Ok(Self::VarnaProvince),
"Veliko Tarnovo Province" => Ok(Self::VelikoTarnovoProvince),
"Vidin Province" => Ok(Self::VidinProvince),
"Vratsa Province" => Ok(Self::VratsaProvince),
"Yambol Province" => Ok(Self::YambolProvince),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for BosniaAndHerzegovinaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "BosniaAndHerzegovinaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Bosnian Podrinje Canton" => Ok(Self::BosnianPodrinjeCanton),
"Brčko District" => Ok(Self::BrckoDistrict),
"Canton 10" => Ok(Self::Canton10),
"Central Bosnia Canton" => Ok(Self::CentralBosniaCanton),
"Federation of Bosnia and Herzegovina" => {
Ok(Self::FederationOfBosniaAndHerzegovina)
}
"Herzegovina-Neretva Canton" => Ok(Self::HerzegovinaNeretvaCanton),
"Posavina Canton" => Ok(Self::PosavinaCanton),
"Republika Srpska" => Ok(Self::RepublikaSrpska),
"Sarajevo Canton" => Ok(Self::SarajevoCanton),
"Tuzla Canton" => Ok(Self::TuzlaCanton),
"Una-Sana Canton" => Ok(Self::UnaSanaCanton),
"West Herzegovina Canton" => Ok(Self::WestHerzegovinaCanton),
"Zenica-Doboj Canton" => Ok(Self::ZenicaDobojCanton),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for UnitedKingdomStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "UnitedKingdomStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Aberdeen" => Ok(Self::Aberdeen),
"Aberdeenshire" => Ok(Self::Aberdeenshire),
"Angus" => Ok(Self::Angus),
"Antrim" => Ok(Self::Antrim),
"Antrim and Newtownabbey" => Ok(Self::AntrimAndNewtownabbey),
"Ards" => Ok(Self::Ards),
"Ards and North Down" => Ok(Self::ArdsAndNorthDown),
"Argyll and Bute" => Ok(Self::ArgyllAndBute),
"Armagh City and District Council" => Ok(Self::ArmaghCityAndDistrictCouncil),
"Armagh, Banbridge and Craigavon" => Ok(Self::ArmaghBanbridgeAndCraigavon),
"Ascension Island" => Ok(Self::AscensionIsland),
"Ballymena Borough" => Ok(Self::BallymenaBorough),
"Ballymoney" => Ok(Self::Ballymoney),
"Banbridge" => Ok(Self::Banbridge),
"Barnsley" => Ok(Self::Barnsley),
"Bath and North East Somerset" => Ok(Self::BathAndNorthEastSomerset),
"Bedford" => Ok(Self::Bedford),
"Belfast district" => Ok(Self::BelfastDistrict),
"Birmingham" => Ok(Self::Birmingham),
"Blackburn with Darwen" => Ok(Self::BlackburnWithDarwen),
"Blackpool" => Ok(Self::Blackpool),
"Blaenau Gwent County Borough" => Ok(Self::BlaenauGwentCountyBorough),
"Bolton" => Ok(Self::Bolton),
"Bournemouth" => Ok(Self::Bournemouth),
"Bracknell Forest" => Ok(Self::BracknellForest),
"Bradford" => Ok(Self::Bradford),
"Bridgend County Borough" => Ok(Self::BridgendCountyBorough),
"Brighton and Hove" => Ok(Self::BrightonAndHove),
"Buckinghamshire" => Ok(Self::Buckinghamshire),
"Bury" => Ok(Self::Bury),
"Caerphilly County Borough" => Ok(Self::CaerphillyCountyBorough),
"Calderdale" => Ok(Self::Calderdale),
"Cambridgeshire" => Ok(Self::Cambridgeshire),
"Carmarthenshire" => Ok(Self::Carmarthenshire),
"Carrickfergus Borough Council" => Ok(Self::CarrickfergusBoroughCouncil),
"Castlereagh" => Ok(Self::Castlereagh),
"Causeway Coast and Glens" => Ok(Self::CausewayCoastAndGlens),
"Central Bedfordshire" => Ok(Self::CentralBedfordshire),
"Ceredigion" => Ok(Self::Ceredigion),
"Cheshire East" => Ok(Self::CheshireEast),
"Cheshire West and Chester" => Ok(Self::CheshireWestAndChester),
"City and County of Cardiff" => Ok(Self::CityAndCountyOfCardiff),
"City and County of Swansea" => Ok(Self::CityAndCountyOfSwansea),
"City of Bristol" => Ok(Self::CityOfBristol),
"City of Derby" => Ok(Self::CityOfDerby),
"City of Kingston upon Hull" => Ok(Self::CityOfKingstonUponHull),
"City of Leicester" => Ok(Self::CityOfLeicester),
"City of London" => Ok(Self::CityOfLondon),
"City of Nottingham" => Ok(Self::CityOfNottingham),
"City of Peterborough" => Ok(Self::CityOfPeterborough),
"City of Plymouth" => Ok(Self::CityOfPlymouth),
"City of Portsmouth" => Ok(Self::CityOfPortsmouth),
"City of Southampton" => Ok(Self::CityOfSouthampton),
"City of Stoke-on-Trent" => Ok(Self::CityOfStokeOnTrent),
"City of Sunderland" => Ok(Self::CityOfSunderland),
"City of Westminster" => Ok(Self::CityOfWestminster),
"City of Wolverhampton" => Ok(Self::CityOfWolverhampton),
"City of York" => Ok(Self::CityOfYork),
"Clackmannanshire" => Ok(Self::Clackmannanshire),
"Coleraine Borough Council" => Ok(Self::ColeraineBoroughCouncil),
"Conwy County Borough" => Ok(Self::ConwyCountyBorough),
"Cookstown District Council" => Ok(Self::CookstownDistrictCouncil),
"Cornwall" => Ok(Self::Cornwall),
"County Durham" => Ok(Self::CountyDurham),
"Coventry" => Ok(Self::Coventry),
"Craigavon Borough Council" => Ok(Self::CraigavonBoroughCouncil),
"Cumbria" => Ok(Self::Cumbria),
"Darlington" => Ok(Self::Darlington),
"Denbighshire" => Ok(Self::Denbighshire),
"Derbyshire" => Ok(Self::Derbyshire),
"Derry City and Strabane" => Ok(Self::DerryCityAndStrabane),
"Derry City Council" => Ok(Self::DerryCityCouncil),
"Devon" => Ok(Self::Devon),
"Doncaster" => Ok(Self::Doncaster),
"Dorset" => Ok(Self::Dorset),
"Down District Council" => Ok(Self::DownDistrictCouncil),
"Dudley" => Ok(Self::Dudley),
"Dumfries and Galloway" => Ok(Self::DumfriesAndGalloway),
"Dundee" => Ok(Self::Dundee),
"Dungannon and South Tyrone Borough Council" => {
Ok(Self::DungannonAndSouthTyroneBoroughCouncil)
}
"East Ayrshire" => Ok(Self::EastAyrshire),
"East Dunbartonshire" => Ok(Self::EastDunbartonshire),
"East Lothian" => Ok(Self::EastLothian),
"East Renfrewshire" => Ok(Self::EastRenfrewshire),
"East Riding of Yorkshire" => Ok(Self::EastRidingOfYorkshire),
"East Sussex" => Ok(Self::EastSussex),
"Edinburgh" => Ok(Self::Edinburgh),
"England" => Ok(Self::England),
"Essex" => Ok(Self::Essex),
"Falkirk" => Ok(Self::Falkirk),
"Fermanagh and Omagh" => Ok(Self::FermanaghAndOmagh),
"Fermanagh District Council" => Ok(Self::FermanaghDistrictCouncil),
"Fife" => Ok(Self::Fife),
"Flintshire" => Ok(Self::Flintshire),
"Gateshead" => Ok(Self::Gateshead),
"Glasgow" => Ok(Self::Glasgow),
"Gloucestershire" => Ok(Self::Gloucestershire),
"Gwynedd" => Ok(Self::Gwynedd),
"Halton" => Ok(Self::Halton),
"Hampshire" => Ok(Self::Hampshire),
"Hartlepool" => Ok(Self::Hartlepool),
"Herefordshire" => Ok(Self::Herefordshire),
"Hertfordshire" => Ok(Self::Hertfordshire),
"Highland" => Ok(Self::Highland),
"Inverclyde" => Ok(Self::Inverclyde),
"Isle of Wight" => Ok(Self::IsleOfWight),
"Isles of Scilly" => Ok(Self::IslesOfScilly),
"Kent" => Ok(Self::Kent),
"Kirklees" => Ok(Self::Kirklees),
"Knowsley" => Ok(Self::Knowsley),
"Lancashire" => Ok(Self::Lancashire),
"Larne Borough Council" => Ok(Self::LarneBoroughCouncil),
"Leeds" => Ok(Self::Leeds),
"Leicestershire" => Ok(Self::Leicestershire),
"Limavady Borough Council" => Ok(Self::LimavadyBoroughCouncil),
"Lincolnshire" => Ok(Self::Lincolnshire),
"Lisburn and Castlereagh" => Ok(Self::LisburnAndCastlereagh),
"Lisburn City Council" => Ok(Self::LisburnCityCouncil),
"Liverpool" => Ok(Self::Liverpool),
"London Borough of Barking and Dagenham" => {
Ok(Self::LondonBoroughOfBarkingAndDagenham)
}
"London Borough of Barnet" => Ok(Self::LondonBoroughOfBarnet),
"London Borough of Bexley" => Ok(Self::LondonBoroughOfBexley),
"London Borough of Brent" => Ok(Self::LondonBoroughOfBrent),
"London Borough of Bromley" => Ok(Self::LondonBoroughOfBromley),
"London Borough of Camden" => Ok(Self::LondonBoroughOfCamden),
"London Borough of Croydon" => Ok(Self::LondonBoroughOfCroydon),
"London Borough of Ealing" => Ok(Self::LondonBoroughOfEaling),
"London Borough of Enfield" => Ok(Self::LondonBoroughOfEnfield),
"London Borough of Hackney" => Ok(Self::LondonBoroughOfHackney),
"London Borough of Hammersmith and Fulham" => {
Ok(Self::LondonBoroughOfHammersmithAndFulham)
}
"London Borough of Haringey" => Ok(Self::LondonBoroughOfHaringey),
"London Borough of Harrow" => Ok(Self::LondonBoroughOfHarrow),
"London Borough of Havering" => Ok(Self::LondonBoroughOfHavering),
"London Borough of Hillingdon" => Ok(Self::LondonBoroughOfHillingdon),
"London Borough of Hounslow" => Ok(Self::LondonBoroughOfHounslow),
"London Borough of Islington" => Ok(Self::LondonBoroughOfIslington),
"London Borough of Lambeth" => Ok(Self::LondonBoroughOfLambeth),
"London Borough of Lewisham" => Ok(Self::LondonBoroughOfLewisham),
"London Borough of Merton" => Ok(Self::LondonBoroughOfMerton),
"London Borough of Newham" => Ok(Self::LondonBoroughOfNewham),
"London Borough of Redbridge" => Ok(Self::LondonBoroughOfRedbridge),
"London Borough of Richmond upon Thames" => {
Ok(Self::LondonBoroughOfRichmondUponThames)
}
"London Borough of Southwark" => Ok(Self::LondonBoroughOfSouthwark),
"London Borough of Sutton" => Ok(Self::LondonBoroughOfSutton),
"London Borough of Tower Hamlets" => Ok(Self::LondonBoroughOfTowerHamlets),
"London Borough of Waltham Forest" => Ok(Self::LondonBoroughOfWalthamForest),
"London Borough of Wandsworth" => Ok(Self::LondonBoroughOfWandsworth),
"Magherafelt District Council" => Ok(Self::MagherafeltDistrictCouncil),
"Manchester" => Ok(Self::Manchester),
"Medway" => Ok(Self::Medway),
"Merthyr Tydfil County Borough" => Ok(Self::MerthyrTydfilCountyBorough),
"Metropolitan Borough of Wigan" => Ok(Self::MetropolitanBoroughOfWigan),
"Mid and East Antrim" => Ok(Self::MidAndEastAntrim),
"Mid Ulster" => Ok(Self::MidUlster),
"Middlesbrough" => Ok(Self::Middlesbrough),
"Midlothian" => Ok(Self::Midlothian),
"Milton Keynes" => Ok(Self::MiltonKeynes),
"Monmouthshire" => Ok(Self::Monmouthshire),
"Moray" => Ok(Self::Moray),
"Moyle District Council" => Ok(Self::MoyleDistrictCouncil),
"Neath Port Talbot County Borough" => Ok(Self::NeathPortTalbotCountyBorough),
"Newcastle upon Tyne" => Ok(Self::NewcastleUponTyne),
"Newport" => Ok(Self::Newport),
"Newry and Mourne District Council" => Ok(Self::NewryAndMourneDistrictCouncil),
"Newry, Mourne and Down" => Ok(Self::NewryMourneAndDown),
"Newtownabbey Borough Council" => Ok(Self::NewtownabbeyBoroughCouncil),
"Norfolk" => Ok(Self::Norfolk),
"North Ayrshire" => Ok(Self::NorthAyrshire),
"North Down Borough Council" => Ok(Self::NorthDownBoroughCouncil),
"North East Lincolnshire" => Ok(Self::NorthEastLincolnshire),
"North Lanarkshire" => Ok(Self::NorthLanarkshire),
"North Lincolnshire" => Ok(Self::NorthLincolnshire),
"North Somerset" => Ok(Self::NorthSomerset),
"North Tyneside" => Ok(Self::NorthTyneside),
"North Yorkshire" => Ok(Self::NorthYorkshire),
"Northamptonshire" => Ok(Self::Northamptonshire),
"Northern Ireland" => Ok(Self::NorthernIreland),
"Northumberland" => Ok(Self::Northumberland),
"Nottinghamshire" => Ok(Self::Nottinghamshire),
"Oldham" => Ok(Self::Oldham),
"Omagh District Council" => Ok(Self::OmaghDistrictCouncil),
"Orkney Islands" => Ok(Self::OrkneyIslands),
"Outer Hebrides" => Ok(Self::OuterHebrides),
"Oxfordshire" => Ok(Self::Oxfordshire),
"Pembrokeshire" => Ok(Self::Pembrokeshire),
"Perth and Kinross" => Ok(Self::PerthAndKinross),
"Poole" => Ok(Self::Poole),
"Powys" => Ok(Self::Powys),
"Reading" => Ok(Self::Reading),
"Redcar and Cleveland" => Ok(Self::RedcarAndCleveland),
"Renfrewshire" => Ok(Self::Renfrewshire),
"Rhondda Cynon Taf" => Ok(Self::RhonddaCynonTaf),
"Rochdale" => Ok(Self::Rochdale),
"Rotherham" => Ok(Self::Rotherham),
"Royal Borough of Greenwich" => Ok(Self::RoyalBoroughOfGreenwich),
"Royal Borough of Kensington and Chelsea" => {
Ok(Self::RoyalBoroughOfKensingtonAndChelsea)
}
"Royal Borough of Kingston upon Thames" => {
Ok(Self::RoyalBoroughOfKingstonUponThames)
}
"Rutland" => Ok(Self::Rutland),
"Saint Helena" => Ok(Self::SaintHelena),
"Salford" => Ok(Self::Salford),
"Sandwell" => Ok(Self::Sandwell),
"Scotland" => Ok(Self::Scotland),
"Scottish Borders" => Ok(Self::ScottishBorders),
"Sefton" => Ok(Self::Sefton),
"Sheffield" => Ok(Self::Sheffield),
"Shetland Islands" => Ok(Self::ShetlandIslands),
"Shropshire" => Ok(Self::Shropshire),
"Slough" => Ok(Self::Slough),
"Solihull" => Ok(Self::Solihull),
"Somerset" => Ok(Self::Somerset),
"South Ayrshire" => Ok(Self::SouthAyrshire),
"South Gloucestershire" => Ok(Self::SouthGloucestershire),
"South Lanarkshire" => Ok(Self::SouthLanarkshire),
"South Tyneside" => Ok(Self::SouthTyneside),
"Southend-on-Sea" => Ok(Self::SouthendOnSea),
"St Helens" => Ok(Self::StHelens),
"Staffordshire" => Ok(Self::Staffordshire),
"Stirling" => Ok(Self::Stirling),
"Stockport" => Ok(Self::Stockport),
"Stockton-on-Tees" => Ok(Self::StocktonOnTees),
"Strabane District Council" => Ok(Self::StrabaneDistrictCouncil),
"Suffolk" => Ok(Self::Suffolk),
"Surrey" => Ok(Self::Surrey),
"Swindon" => Ok(Self::Swindon),
"Tameside" => Ok(Self::Tameside),
"Telford and Wrekin" => Ok(Self::TelfordAndWrekin),
"Thurrock" => Ok(Self::Thurrock),
"Torbay" => Ok(Self::Torbay),
"Torfaen" => Ok(Self::Torfaen),
"Trafford" => Ok(Self::Trafford),
"United Kingdom" => Ok(Self::UnitedKingdom),
"Vale of Glamorgan" => Ok(Self::ValeOfGlamorgan),
"Wakefield" => Ok(Self::Wakefield),
"Wales" => Ok(Self::Wales),
"Walsall" => Ok(Self::Walsall),
"Warrington" => Ok(Self::Warrington),
"Warwickshire" => Ok(Self::Warwickshire),
"West Berkshire" => Ok(Self::WestBerkshire),
"West Dunbartonshire" => Ok(Self::WestDunbartonshire),
"West Lothian" => Ok(Self::WestLothian),
"West Sussex" => Ok(Self::WestSussex),
"Wiltshire" => Ok(Self::Wiltshire),
"Windsor and Maidenhead" => Ok(Self::WindsorAndMaidenhead),
"Wirral" => Ok(Self::Wirral),
"Wokingham" => Ok(Self::Wokingham),
"Worcestershire" => Ok(Self::Worcestershire),
"Wrexham County Borough" => Ok(Self::WrexhamCountyBorough),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for BelgiumStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "BelgiumStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Antwerp" => Ok(Self::Antwerp),
"Brussels-Capital Region" => Ok(Self::BrusselsCapitalRegion),
"East Flanders" => Ok(Self::EastFlanders),
"Flanders" => Ok(Self::Flanders),
"Flemish Brabant" => Ok(Self::FlemishBrabant),
"Hainaut" => Ok(Self::Hainaut),
"Limburg" => Ok(Self::Limburg),
"Liège" => Ok(Self::Liege),
"Luxembourg" => Ok(Self::Luxembourg),
"Namur" => Ok(Self::Namur),
"Wallonia" => Ok(Self::Wallonia),
"Walloon Brabant" => Ok(Self::WalloonBrabant),
"West Flanders" => Ok(Self::WestFlanders),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for LuxembourgStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "LuxembourgStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Canton of Capellen" => Ok(Self::CantonOfCapellen),
"Canton of Clervaux" => Ok(Self::CantonOfClervaux),
"Canton of Diekirch" => Ok(Self::CantonOfDiekirch),
"Canton of Echternach" => Ok(Self::CantonOfEchternach),
"Canton of Esch-sur-Alzette" => Ok(Self::CantonOfEschSurAlzette),
"Canton of Grevenmacher" => Ok(Self::CantonOfGrevenmacher),
"Canton of Luxembourg" => Ok(Self::CantonOfLuxembourg),
"Canton of Mersch" => Ok(Self::CantonOfMersch),
"Canton of Redange" => Ok(Self::CantonOfRedange),
"Canton of Remich" => Ok(Self::CantonOfRemich),
"Canton of Vianden" => Ok(Self::CantonOfVianden),
"Canton of Wiltz" => Ok(Self::CantonOfWiltz),
"Diekirch District" => Ok(Self::DiekirchDistrict),
"Grevenmacher District" => Ok(Self::GrevenmacherDistrict),
"Luxembourg District" => Ok(Self::LuxembourgDistrict),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for RussiaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "RussiaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Altai Krai" => Ok(Self::AltaiKrai),
"Altai Republic" => Ok(Self::AltaiRepublic),
"Amur Oblast" => Ok(Self::AmurOblast),
"Arkhangelsk" => Ok(Self::Arkhangelsk),
"Astrakhan Oblast" => Ok(Self::AstrakhanOblast),
"Belgorod Oblast" => Ok(Self::BelgorodOblast),
"Bryansk Oblast" => Ok(Self::BryanskOblast),
"Chechen Republic" => Ok(Self::ChechenRepublic),
"Chelyabinsk Oblast" => Ok(Self::ChelyabinskOblast),
"Chukotka Autonomous Okrug" => Ok(Self::ChukotkaAutonomousOkrug),
"Chuvash Republic" => Ok(Self::ChuvashRepublic),
"Irkutsk" => Ok(Self::Irkutsk),
"Ivanovo Oblast" => Ok(Self::IvanovoOblast),
"Jewish Autonomous Oblast" => Ok(Self::JewishAutonomousOblast),
"Kabardino-Balkar Republic" => Ok(Self::KabardinoBalkarRepublic),
"Kaliningrad" => Ok(Self::Kaliningrad),
"Kaluga Oblast" => Ok(Self::KalugaOblast),
"Kamchatka Krai" => Ok(Self::KamchatkaKrai),
"Karachay-Cherkess Republic" => Ok(Self::KarachayCherkessRepublic),
"Kemerovo Oblast" => Ok(Self::KemerovoOblast),
"Khabarovsk Krai" => Ok(Self::KhabarovskKrai),
"Khanty-Mansi Autonomous Okrug" => Ok(Self::KhantyMansiAutonomousOkrug),
"Kirov Oblast" => Ok(Self::KirovOblast),
"Komi Republic" => Ok(Self::KomiRepublic),
"Kostroma Oblast" => Ok(Self::KostromaOblast),
"Krasnodar Krai" => Ok(Self::KrasnodarKrai),
"Krasnoyarsk Krai" => Ok(Self::KrasnoyarskKrai),
"Kurgan Oblast" => Ok(Self::KurganOblast),
"Kursk Oblast" => Ok(Self::KurskOblast),
"Leningrad Oblast" => Ok(Self::LeningradOblast),
"Lipetsk Oblast" => Ok(Self::LipetskOblast),
"Magadan Oblast" => Ok(Self::MagadanOblast),
"Mari El Republic" => Ok(Self::MariElRepublic),
"Moscow" => Ok(Self::Moscow),
"Moscow Oblast" => Ok(Self::MoscowOblast),
"Murmansk Oblast" => Ok(Self::MurmanskOblast),
"Nenets Autonomous Okrug" => Ok(Self::NenetsAutonomousOkrug),
"Nizhny Novgorod Oblast" => Ok(Self::NizhnyNovgorodOblast),
"Novgorod Oblast" => Ok(Self::NovgorodOblast),
"Novosibirsk" => Ok(Self::Novosibirsk),
"Omsk Oblast" => Ok(Self::OmskOblast),
"Orenburg Oblast" => Ok(Self::OrenburgOblast),
"Oryol Oblast" => Ok(Self::OryolOblast),
"Penza Oblast" => Ok(Self::PenzaOblast),
"Perm Krai" => Ok(Self::PermKrai),
"Primorsky Krai" => Ok(Self::PrimorskyKrai),
"Pskov Oblast" => Ok(Self::PskovOblast),
"Republic of Adygea" => Ok(Self::RepublicOfAdygea),
"Republic of Bashkortostan" => Ok(Self::RepublicOfBashkortostan),
"Republic of Buryatia" => Ok(Self::RepublicOfBuryatia),
"Republic of Dagestan" => Ok(Self::RepublicOfDagestan),
"Republic of Ingushetia" => Ok(Self::RepublicOfIngushetia),
"Republic of Kalmykia" => Ok(Self::RepublicOfKalmykia),
"Republic of Karelia" => Ok(Self::RepublicOfKarelia),
"Republic of Khakassia" => Ok(Self::RepublicOfKhakassia),
"Republic of Mordovia" => Ok(Self::RepublicOfMordovia),
"Republic of North Ossetia-Alania" => Ok(Self::RepublicOfNorthOssetiaAlania),
"Republic of Tatarstan" => Ok(Self::RepublicOfTatarstan),
"Rostov Oblast" => Ok(Self::RostovOblast),
"Ryazan Oblast" => Ok(Self::RyazanOblast),
"Saint Petersburg" => Ok(Self::SaintPetersburg),
"Sakha Republic" => Ok(Self::SakhaRepublic),
"Sakhalin" => Ok(Self::Sakhalin),
"Samara Oblast" => Ok(Self::SamaraOblast),
"Saratov Oblast" => Ok(Self::SaratovOblast),
"Sevastopol" => Ok(Self::Sevastopol),
"Smolensk Oblast" => Ok(Self::SmolenskOblast),
"Stavropol Krai" => Ok(Self::StavropolKrai),
"Sverdlovsk" => Ok(Self::Sverdlovsk),
"Tambov Oblast" => Ok(Self::TambovOblast),
"Tomsk Oblast" => Ok(Self::TomskOblast),
"Tula Oblast" => Ok(Self::TulaOblast),
"Tuva Republic" => Ok(Self::TuvaRepublic),
"Tver Oblast" => Ok(Self::TverOblast),
"Tyumen Oblast" => Ok(Self::TyumenOblast),
"Udmurt Republic" => Ok(Self::UdmurtRepublic),
"Ulyanovsk Oblast" => Ok(Self::UlyanovskOblast),
"Vladimir Oblast" => Ok(Self::VladimirOblast),
"Vologda Oblast" => Ok(Self::VologdaOblast),
"Voronezh Oblast" => Ok(Self::VoronezhOblast),
"Yamalo-Nenets Autonomous Okrug" => Ok(Self::YamaloNenetsAutonomousOkrug),
"Yaroslavl Oblast" => Ok(Self::YaroslavlOblast),
"Zabaykalsky Krai" => Ok(Self::ZabaykalskyKrai),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for SanMarinoStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "SanMarinoStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Acquaviva" => Ok(Self::Acquaviva),
"Borgo Maggiore" => Ok(Self::BorgoMaggiore),
"Chiesanuova" => Ok(Self::Chiesanuova),
"Domagnano" => Ok(Self::Domagnano),
"Faetano" => Ok(Self::Faetano),
"Fiorentino" => Ok(Self::Fiorentino),
"Montegiardino" => Ok(Self::Montegiardino),
"San Marino" => Ok(Self::SanMarino),
"Serravalle" => Ok(Self::Serravalle),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for SerbiaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "SerbiaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Belgrade" => Ok(Self::Belgrade),
"Bor District" => Ok(Self::BorDistrict),
"Braničevo District" => Ok(Self::BraničevoDistrict),
"Central Banat District" => Ok(Self::CentralBanatDistrict),
"Jablanica District" => Ok(Self::JablanicaDistrict),
"Kolubara District" => Ok(Self::KolubaraDistrict),
"Mačva District" => Ok(Self::MačvaDistrict),
"Moravica District" => Ok(Self::MoravicaDistrict),
"Nišava District" => Ok(Self::NišavaDistrict),
"North Banat District" => Ok(Self::NorthBanatDistrict),
"North Bačka District" => Ok(Self::NorthBačkaDistrict),
"Pirot District" => Ok(Self::PirotDistrict),
"Podunavlje District" => Ok(Self::PodunavljeDistrict),
"Pomoravlje District" => Ok(Self::PomoravljeDistrict),
"Pčinja District" => Ok(Self::PčinjaDistrict),
"Rasina District" => Ok(Self::RasinaDistrict),
"Raška District" => Ok(Self::RaškaDistrict),
"South Banat District" => Ok(Self::SouthBanatDistrict),
"South Bačka District" => Ok(Self::SouthBačkaDistrict),
"Srem District" => Ok(Self::SremDistrict),
"Toplica District" => Ok(Self::ToplicaDistrict),
"Vojvodina" => Ok(Self::Vojvodina),
"West Bačka District" => Ok(Self::WestBačkaDistrict),
"Zaječar District" => Ok(Self::ZaječarDistrict),
"Zlatibor District" => Ok(Self::ZlatiborDistrict),
"Šumadija District" => Ok(Self::ŠumadijaDistrict),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for SlovakiaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "SlovakiaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Banská Bystrica Region" => Ok(Self::BanskaBystricaRegion),
"Bratislava Region" => Ok(Self::BratislavaRegion),
"Košice Region" => Ok(Self::KosiceRegion),
"Nitra Region" => Ok(Self::NitraRegion),
"Prešov Region" => Ok(Self::PresovRegion),
"Trenčín Region" => Ok(Self::TrencinRegion),
"Trnava Region" => Ok(Self::TrnavaRegion),
"Žilina Region" => Ok(Self::ZilinaRegion),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for SwedenStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "SwedenStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Blekinge" => Ok(Self::Blekinge),
"Dalarna County" => Ok(Self::DalarnaCounty),
"Gotland County" => Ok(Self::GotlandCounty),
"Gävleborg County" => Ok(Self::GävleborgCounty),
"Halland County" => Ok(Self::HallandCounty),
"Jönköping County" => Ok(Self::JönköpingCounty),
"Kalmar County" => Ok(Self::KalmarCounty),
"Kronoberg County" => Ok(Self::KronobergCounty),
"Norrbotten County" => Ok(Self::NorrbottenCounty),
"Skåne County" => Ok(Self::SkåneCounty),
"Stockholm County" => Ok(Self::StockholmCounty),
"Södermanland County" => Ok(Self::SödermanlandCounty),
"Uppsala County" => Ok(Self::UppsalaCounty),
"Värmland County" => Ok(Self::VärmlandCounty),
"Västerbotten County" => Ok(Self::VästerbottenCounty),
"Västernorrland County" => Ok(Self::VästernorrlandCounty),
"Västmanland County" => Ok(Self::VästmanlandCounty),
"Västra Götaland County" => Ok(Self::VästraGötalandCounty),
"Örebro County" => Ok(Self::ÖrebroCounty),
"Östergötland County" => Ok(Self::ÖstergötlandCounty),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for SloveniaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "SloveniaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Ajdovščina Municipality" => Ok(Self::Ajdovščina),
"Ankaran Municipality" => Ok(Self::Ankaran),
"Beltinci Municipality" => Ok(Self::Beltinci),
"Benedikt Municipality" => Ok(Self::Benedikt),
"Bistrica ob Sotli Municipality" => Ok(Self::BistricaObSotli),
"Bled Municipality" => Ok(Self::Bled),
"Bloke Municipality" => Ok(Self::Bloke),
"Bohinj Municipality" => Ok(Self::Bohinj),
"Borovnica Municipality" => Ok(Self::Borovnica),
"Bovec Municipality" => Ok(Self::Bovec),
"Braslovče Municipality" => Ok(Self::Braslovče),
"Brda Municipality" => Ok(Self::Brda),
"Brezovica Municipality" => Ok(Self::Brezovica),
"Brežice Municipality" => Ok(Self::Brežice),
"Cankova Municipality" => Ok(Self::Cankova),
"Cerklje na Gorenjskem Municipality" => Ok(Self::CerkljeNaGorenjskem),
"Cerknica Municipality" => Ok(Self::Cerknica),
"Cerkno Municipality" => Ok(Self::Cerkno),
"Cerkvenjak Municipality" => Ok(Self::Cerkvenjak),
"City Municipality of Celje" => Ok(Self::CityMunicipalityOfCelje),
"City Municipality of Novo Mesto" => Ok(Self::CityMunicipalityOfNovoMesto),
"Destrnik Municipality" => Ok(Self::Destrnik),
"Divača Municipality" => Ok(Self::Divača),
"Dobje Municipality" => Ok(Self::Dobje),
"Dobrepolje Municipality" => Ok(Self::Dobrepolje),
"Dobrna Municipality" => Ok(Self::Dobrna),
"Dobrova–Polhov Gradec Municipality" => Ok(Self::DobrovaPolhovGradec),
"Dobrovnik Municipality" => Ok(Self::Dobrovnik),
"Dol pri Ljubljani Municipality" => Ok(Self::DolPriLjubljani),
"Dolenjske Toplice Municipality" => Ok(Self::DolenjskeToplice),
"Domžale Municipality" => Ok(Self::Domžale),
"Dornava Municipality" => Ok(Self::Dornava),
"Dravograd Municipality" => Ok(Self::Dravograd),
"Duplek Municipality" => Ok(Self::Duplek),
"Gorenja Vas–Poljane Municipality" => Ok(Self::GorenjaVasPoljane),
"Gorišnica Municipality" => Ok(Self::Gorišnica),
"Gorje Municipality" => Ok(Self::Gorje),
"Gornja Radgona Municipality" => Ok(Self::GornjaRadgona),
"Gornji Grad Municipality" => Ok(Self::GornjiGrad),
"Gornji Petrovci Municipality" => Ok(Self::GornjiPetrovci),
"Grad Municipality" => Ok(Self::Grad),
"Grosuplje Municipality" => Ok(Self::Grosuplje),
"Hajdina Municipality" => Ok(Self::Hajdina),
"Hodoš Municipality" => Ok(Self::Hodoš),
"Horjul Municipality" => Ok(Self::Horjul),
"Hoče–Slivnica Municipality" => Ok(Self::HočeSlivnica),
"Hrastnik Municipality" => Ok(Self::Hrastnik),
"Hrpelje–Kozina Municipality" => Ok(Self::HrpeljeKozina),
"Idrija Municipality" => Ok(Self::Idrija),
"Ig Municipality" => Ok(Self::Ig),
"Ivančna Gorica Municipality" => Ok(Self::IvančnaGorica),
"Izola Municipality" => Ok(Self::Izola),
"Jesenice Municipality" => Ok(Self::Jesenice),
"Jezersko Municipality" => Ok(Self::Jezersko),
"Juršinci Municipality" => Ok(Self::Jursinci),
"Kamnik Municipality" => Ok(Self::Kamnik),
"Kanal ob Soči Municipality" => Ok(Self::KanalObSoci),
"Kidričevo Municipality" => Ok(Self::Kidricevo),
"Kobarid Municipality" => Ok(Self::Kobarid),
"Kobilje Municipality" => Ok(Self::Kobilje),
"Komen Municipality" => Ok(Self::Komen),
"Komenda Municipality" => Ok(Self::Komenda),
"Koper City Municipality" => Ok(Self::Koper),
"Kostanjevica na Krki Municipality" => Ok(Self::KostanjevicaNaKrki),
"Kostel Municipality" => Ok(Self::Kostel),
"Kozje Municipality" => Ok(Self::Kozje),
"Kočevje Municipality" => Ok(Self::Kocevje),
"Kranj City Municipality" => Ok(Self::Kranj),
"Kranjska Gora Municipality" => Ok(Self::KranjskaGora),
"Križevci Municipality" => Ok(Self::Krizevci),
"Kungota" => Ok(Self::Kungota),
"Kuzma Municipality" => Ok(Self::Kuzma),
"Laško Municipality" => Ok(Self::Lasko),
"Lenart Municipality" => Ok(Self::Lenart),
"Lendava Municipality" => Ok(Self::Lendava),
"Litija Municipality" => Ok(Self::Litija),
"Ljubljana City Municipality" => Ok(Self::Ljubljana),
"Ljubno Municipality" => Ok(Self::Ljubno),
"Ljutomer Municipality" => Ok(Self::Ljutomer),
"Logatec Municipality" => Ok(Self::Logatec),
"Log–Dragomer Municipality" => Ok(Self::LogDragomer),
"Lovrenc na Pohorju Municipality" => Ok(Self::LovrencNaPohorju),
"Loška Dolina Municipality" => Ok(Self::LoskaDolina),
"Loški Potok Municipality" => Ok(Self::LoskiPotok),
"Lukovica Municipality" => Ok(Self::Lukovica),
"Luče Municipality" => Ok(Self::Luče),
"Majšperk Municipality" => Ok(Self::Majsperk),
"Makole Municipality" => Ok(Self::Makole),
"Maribor City Municipality" => Ok(Self::Maribor),
"Markovci Municipality" => Ok(Self::Markovci),
"Medvode Municipality" => Ok(Self::Medvode),
"Mengeš Municipality" => Ok(Self::Menges),
"Metlika Municipality" => Ok(Self::Metlika),
"Mežica Municipality" => Ok(Self::Mezica),
"Miklavž na Dravskem Polju Municipality" => Ok(Self::MiklavzNaDravskemPolju),
"Miren–Kostanjevica Municipality" => Ok(Self::MirenKostanjevica),
"Mirna Municipality" => Ok(Self::Mirna),
"Mirna Peč Municipality" => Ok(Self::MirnaPec),
"Mislinja Municipality" => Ok(Self::Mislinja),
"Mokronog–Trebelno Municipality" => Ok(Self::MokronogTrebelno),
"Moravske Toplice Municipality" => Ok(Self::MoravskeToplice),
"Moravče Municipality" => Ok(Self::Moravce),
"Mozirje Municipality" => Ok(Self::Mozirje),
"Municipality of Apače" => Ok(Self::Apače),
"Municipality of Cirkulane" => Ok(Self::Cirkulane),
"Municipality of Ilirska Bistrica" => Ok(Self::IlirskaBistrica),
"Municipality of Krško" => Ok(Self::Krsko),
"Municipality of Škofljica" => Ok(Self::Skofljica),
"Murska Sobota City Municipality" => Ok(Self::MurskaSobota),
"Muta Municipality" => Ok(Self::Muta),
"Naklo Municipality" => Ok(Self::Naklo),
"Nazarje Municipality" => Ok(Self::Nazarje),
"Nova Gorica City Municipality" => Ok(Self::NovaGorica),
"Odranci Municipality" => Ok(Self::Odranci),
"Oplotnica" => Ok(Self::Oplotnica),
"Ormož Municipality" => Ok(Self::Ormoz),
"Osilnica Municipality" => Ok(Self::Osilnica),
"Pesnica Municipality" => Ok(Self::Pesnica),
"Piran Municipality" => Ok(Self::Piran),
"Pivka Municipality" => Ok(Self::Pivka),
"Podlehnik Municipality" => Ok(Self::Podlehnik),
"Podvelka Municipality" => Ok(Self::Podvelka),
"Podčetrtek Municipality" => Ok(Self::Podcetrtek),
"Poljčane Municipality" => Ok(Self::Poljcane),
"Polzela Municipality" => Ok(Self::Polzela),
"Postojna Municipality" => Ok(Self::Postojna),
"Prebold Municipality" => Ok(Self::Prebold),
"Preddvor Municipality" => Ok(Self::Preddvor),
"Prevalje Municipality" => Ok(Self::Prevalje),
"Ptuj City Municipality" => Ok(Self::Ptuj),
"Puconci Municipality" => Ok(Self::Puconci),
"Radenci Municipality" => Ok(Self::Radenci),
"Radeče Municipality" => Ok(Self::Radece),
"Radlje ob Dravi Municipality" => Ok(Self::RadljeObDravi),
"Radovljica Municipality" => Ok(Self::Radovljica),
"Ravne na Koroškem Municipality" => Ok(Self::RavneNaKoroskem),
"Razkrižje Municipality" => Ok(Self::Razkrizje),
"Rače–Fram Municipality" => Ok(Self::RaceFram),
"Renče–Vogrsko Municipality" => Ok(Self::RenčeVogrsko),
"Rečica ob Savinji Municipality" => Ok(Self::RecicaObSavinji),
"Ribnica Municipality" => Ok(Self::Ribnica),
"Ribnica na Pohorju Municipality" => Ok(Self::RibnicaNaPohorju),
"Rogatec Municipality" => Ok(Self::Rogatec),
"Rogaška Slatina Municipality" => Ok(Self::RogaskaSlatina),
"Rogašovci Municipality" => Ok(Self::Rogasovci),
"Ruše Municipality" => Ok(Self::Ruse),
"Selnica ob Dravi Municipality" => Ok(Self::SelnicaObDravi),
"Semič Municipality" => Ok(Self::Semic),
"Sevnica Municipality" => Ok(Self::Sevnica),
"Sežana Municipality" => Ok(Self::Sezana),
"Slovenj Gradec City Municipality" => Ok(Self::SlovenjGradec),
"Slovenska Bistrica Municipality" => Ok(Self::SlovenskaBistrica),
"Slovenske Konjice Municipality" => Ok(Self::SlovenskeKonjice),
"Sodražica Municipality" => Ok(Self::Sodrazica),
"Solčava Municipality" => Ok(Self::Solcava),
"Središče ob Dravi" => Ok(Self::SredisceObDravi),
"Starše Municipality" => Ok(Self::Starse),
"Straža Municipality" => Ok(Self::Straza),
"Sveta Ana Municipality" => Ok(Self::SvetaAna),
"Sveta Trojica v Slovenskih Goricah Municipality" => Ok(Self::SvetaTrojica),
"Sveti Andraž v Slovenskih Goricah Municipality" => Ok(Self::SvetiAndraz),
"Sveti Jurij ob Ščavnici Municipality" => Ok(Self::SvetiJurijObScavnici),
"Sveti Jurij v Slovenskih Goricah Municipality" => {
Ok(Self::SvetiJurijVSlovenskihGoricah)
}
"Sveti Tomaž Municipality" => Ok(Self::SvetiTomaz),
"Tabor Municipality" => Ok(Self::Tabor),
"Tišina Municipality" => Ok(Self::Tišina),
"Tolmin Municipality" => Ok(Self::Tolmin),
"Trbovlje Municipality" => Ok(Self::Trbovlje),
"Trebnje Municipality" => Ok(Self::Trebnje),
"Trnovska Vas Municipality" => Ok(Self::TrnovskaVas),
"Trzin Municipality" => Ok(Self::Trzin),
"Tržič Municipality" => Ok(Self::Tržič),
"Turnišče Municipality" => Ok(Self::Turnišče),
"Velika Polana Municipality" => Ok(Self::VelikaPolana),
"Velike Lašče Municipality" => Ok(Self::VelikeLašče),
"Veržej Municipality" => Ok(Self::Veržej),
"Videm Municipality" => Ok(Self::Videm),
"Vipava Municipality" => Ok(Self::Vipava),
"Vitanje Municipality" => Ok(Self::Vitanje),
"Vodice Municipality" => Ok(Self::Vodice),
"Vojnik Municipality" => Ok(Self::Vojnik),
"Vransko Municipality" => Ok(Self::Vransko),
"Vrhnika Municipality" => Ok(Self::Vrhnika),
"Vuzenica Municipality" => Ok(Self::Vuzenica),
"Zagorje ob Savi Municipality" => Ok(Self::ZagorjeObSavi),
"Zavrč Municipality" => Ok(Self::Zavrč),
"Zreče Municipality" => Ok(Self::Zreče),
"Črenšovci Municipality" => Ok(Self::Črenšovci),
"Črna na Koroškem Municipality" => Ok(Self::ČrnaNaKoroškem),
"Črnomelj Municipality" => Ok(Self::Črnomelj),
"Šalovci Municipality" => Ok(Self::Šalovci),
"Šempeter–Vrtojba Municipality" => Ok(Self::ŠempeterVrtojba),
"Šentilj Municipality" => Ok(Self::Šentilj),
"Šentjernej Municipality" => Ok(Self::Šentjernej),
"Šentjur Municipality" => Ok(Self::Šentjur),
"Šentrupert Municipality" => Ok(Self::Šentrupert),
"Šenčur Municipality" => Ok(Self::Šenčur),
"Škocjan Municipality" => Ok(Self::Škocjan),
"Škofja Loka Municipality" => Ok(Self::ŠkofjaLoka),
"Šmarje pri Jelšah Municipality" => Ok(Self::ŠmarjePriJelšah),
"Šmarješke Toplice Municipality" => Ok(Self::ŠmarješkeToplice),
"Šmartno ob Paki Municipality" => Ok(Self::ŠmartnoObPaki),
"Šmartno pri Litiji Municipality" => Ok(Self::ŠmartnoPriLitiji),
"Šoštanj Municipality" => Ok(Self::Šoštanj),
"Štore Municipality" => Ok(Self::Štore),
"Žalec Municipality" => Ok(Self::Žalec),
"Železniki Municipality" => Ok(Self::Železniki),
"Žetale Municipality" => Ok(Self::Žetale),
"Žiri Municipality" => Ok(Self::Žiri),
"Žirovnica Municipality" => Ok(Self::Žirovnica),
"Žužemberk Municipality" => Ok(Self::Žužemberk),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for UkraineStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "UkraineStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Autonomous Republic of Crimea" => Ok(Self::AutonomousRepublicOfCrimea),
"Cherkasy Oblast" => Ok(Self::CherkasyOblast),
"Chernihiv Oblast" => Ok(Self::ChernihivOblast),
"Chernivtsi Oblast" => Ok(Self::ChernivtsiOblast),
"Dnipropetrovsk Oblast" => Ok(Self::DnipropetrovskOblast),
"Donetsk Oblast" => Ok(Self::DonetskOblast),
"Ivano-Frankivsk Oblast" => Ok(Self::IvanoFrankivskOblast),
"Kharkiv Oblast" => Ok(Self::KharkivOblast),
"Kherson Oblast" => Ok(Self::KhersonOblast),
"Khmelnytsky Oblast" => Ok(Self::KhmelnytskyOblast),
"Kiev" => Ok(Self::Kiev),
"Kirovohrad Oblast" => Ok(Self::KirovohradOblast),
"Kyiv Oblast" => Ok(Self::KyivOblast),
"Luhansk Oblast" => Ok(Self::LuhanskOblast),
"Lviv Oblast" => Ok(Self::LvivOblast),
"Mykolaiv Oblast" => Ok(Self::MykolaivOblast),
"Odessa Oblast" => Ok(Self::OdessaOblast),
"Rivne Oblast" => Ok(Self::RivneOblast),
"Sumy Oblast" => Ok(Self::SumyOblast),
"Ternopil Oblast" => Ok(Self::TernopilOblast),
"Vinnytsia Oblast" => Ok(Self::VinnytsiaOblast),
"Volyn Oblast" => Ok(Self::VolynOblast),
"Zakarpattia Oblast" => Ok(Self::ZakarpattiaOblast),
"Zaporizhzhya Oblast" => Ok(Self::ZaporizhzhyaOblast),
"Zhytomyr Oblast" => Ok(Self::ZhytomyrOblast),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
pub trait ForeignTryFrom<F>: Sized {
type Error;
fn foreign_try_from(from: F) -> Result<Self, Self::Error>;
}
#[derive(Debug)]
pub struct QrImage {
pub data: String,
}
// Qr Image data source starts with this string
// The base64 image data will be appended to it to image data source
pub(crate) const QR_IMAGE_DATA_SOURCE_STRING: &str = "data:image/png;base64";
impl QrImage {
pub fn new_from_data(
data: String,
) -> Result<Self, error_stack::Report<common_utils::errors::QrCodeError>> {
let qr_code = qrcode::QrCode::new(data.as_bytes())
.change_context(common_utils::errors::QrCodeError::FailedToCreateQrCode)?;
let qrcode_image_buffer = qr_code.render::<Luma<u8>>().build();
let qrcode_dynamic_image = DynamicImage::ImageLuma8(qrcode_image_buffer);
let mut image_bytes = std::io::BufWriter::new(std::io::Cursor::new(Vec::new()));
// Encodes qrcode_dynamic_image and write it to image_bytes
let _ = qrcode_dynamic_image.write_to(&mut image_bytes, ImageFormat::Png);
let image_data_source = format!(
"{},{}",
QR_IMAGE_DATA_SOURCE_STRING,
BASE64_ENGINE.encode(image_bytes.buffer())
);
Ok(Self {
data: image_data_source,
})
}
pub fn new_colored_from_data(
data: String,
hex_color: &str,
) -> Result<Self, error_stack::Report<common_utils::errors::QrCodeError>> {
let qr_code = qrcode::QrCode::new(data.as_bytes())
.change_context(common_utils::errors::QrCodeError::FailedToCreateQrCode)?;
let qrcode_image_buffer = qr_code.render::<Luma<u8>>().build();
let (width, height) = qrcode_image_buffer.dimensions();
let mut colored_image = ImageBuffer::new(width, height);
let rgb = Self::parse_hex_color(hex_color)?;
for (x, y, pixel) in qrcode_image_buffer.enumerate_pixels() {
let luminance = pixel.0[0];
let color = if luminance == 0 {
Rgba([rgb.0, rgb.1, rgb.2, 255])
} else {
Rgba([255, 255, 255, 255])
};
colored_image.put_pixel(x, y, color);
}
let qrcode_dynamic_image = DynamicImage::ImageRgba8(colored_image);
let mut image_bytes = std::io::Cursor::new(Vec::new());
qrcode_dynamic_image
.write_to(&mut image_bytes, ImageFormat::Png)
.change_context(common_utils::errors::QrCodeError::FailedToCreateQrCode)?;
let image_data_source = format!(
"{},{}",
QR_IMAGE_DATA_SOURCE_STRING,
BASE64_ENGINE.encode(image_bytes.get_ref())
);
Ok(Self {
data: image_data_source,
})
}
pub fn parse_hex_color(hex: &str) -> Result<(u8, u8, u8), common_utils::errors::QrCodeError> {
let hex = hex.trim_start_matches('#');
if hex.len() == 6 {
let r = u8::from_str_radix(&hex[0..2], 16).ok();
let g = u8::from_str_radix(&hex[2..4], 16).ok();
let b = u8::from_str_radix(&hex[4..6], 16).ok();
if let (Some(r), Some(g), Some(b)) = (r, g, b) {
return Ok((r, g, b));
}
}
Err(common_utils::errors::QrCodeError::InvalidHexColor)
}
}
#[cfg(test)]
mod tests {
use crate::utils;
#[test]
fn test_image_data_source_url() {
let qr_image_data_source_url = utils::QrImage::new_from_data("Hyperswitch".to_string());
assert!(qr_image_data_source_url.is_ok());
}
}
pub fn is_mandate_supported(
selected_pmd: PaymentMethodData,
payment_method_type: Option<enums::PaymentMethodType>,
mandate_implemented_pmds: HashSet<PaymentMethodDataType>,
connector: &'static str,
) -> Result<(), Error> {
if mandate_implemented_pmds.contains(&PaymentMethodDataType::from(selected_pmd.clone())) {
Ok(())
} else {
match payment_method_type {
Some(pm_type) => Err(errors::ConnectorError::NotSupported {
message: format!("{} mandate payment", pm_type),
connector,
}
.into()),
None => Err(errors::ConnectorError::NotSupported {
message: "mandate payment".to_string(),
connector,
}
.into()),
}
}
}
pub fn get_mandate_details(
setup_mandate_details: Option<mandates::MandateData>,
) -> Result<Option<mandates::MandateAmountData>, error_stack::Report<errors::ConnectorError>> {
setup_mandate_details
.map(|mandate_data| match &mandate_data.mandate_type {
Some(mandates::MandateDataType::SingleUse(mandate))
| Some(mandates::MandateDataType::MultiUse(Some(mandate))) => Ok(mandate.clone()),
Some(mandates::MandateDataType::MultiUse(None)) => {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "setup_future_usage.mandate_data.mandate_type.multi_use.amount",
}
.into())
}
None => Err(errors::ConnectorError::MissingRequiredField {
field_name: "setup_future_usage.mandate_data.mandate_type",
}
.into()),
})
.transpose()
}
pub fn collect_values_by_removing_signature(value: &Value, signature: &String) -> Vec<String> {
match value {
Value::Null => vec!["null".to_owned()],
Value::Bool(b) => vec![b.to_string()],
Value::Number(n) => match n.as_f64() {
Some(f) => vec![format!("{f:.2}")],
None => vec![n.to_string()],
},
Value::String(s) => {
if signature == s {
vec![]
} else {
vec![s.clone()]
}
}
Value::Array(arr) => arr
.iter()
.flat_map(|v| collect_values_by_removing_signature(v, signature))
.collect(),
Value::Object(obj) => obj
.values()
.flat_map(|v| collect_values_by_removing_signature(v, signature))
.collect(),
}
}
pub fn collect_and_sort_values_by_removing_signature(
value: &Value,
signature: &String,
) -> Vec<String> {
let mut values = collect_values_by_removing_signature(value, signature);
values.sort();
values
}
#[derive(Debug, strum::Display, Eq, PartialEq, Hash)]
pub enum PaymentMethodDataType {
Card,
Knet,
Benefit,
MomoAtm,
CardRedirect,
AliPayQr,
AliPayRedirect,
AliPayHkRedirect,
AmazonPayRedirect,
MomoRedirect,
KakaoPayRedirect,
GoPayRedirect,
GcashRedirect,
ApplePay,
ApplePayRedirect,
ApplePayThirdPartySdk,
DanaRedirect,
DuitNow,
GooglePay,
GooglePayRedirect,
GooglePayThirdPartySdk,
MbWayRedirect,
MobilePayRedirect,
PaypalRedirect,
PaypalSdk,
Paze,
SamsungPay,
TwintRedirect,
VippsRedirect,
TouchNGoRedirect,
WeChatPayRedirect,
WeChatPayQr,
CashappQr,
SwishQr,
KlarnaRedirect,
KlarnaSdk,
AffirmRedirect,
AfterpayClearpayRedirect,
PayBrightRedirect,
WalleyRedirect,
AlmaRedirect,
AtomeRedirect,
BancontactCard,
Bizum,
Blik,
Eft,
Eps,
Giropay,
Ideal,
Interac,
LocalBankRedirect,
OnlineBankingCzechRepublic,
OnlineBankingFinland,
OnlineBankingPoland,
OnlineBankingSlovakia,
OpenBankingUk,
Przelewy24,
Sofort,
Trustly,
OnlineBankingFpx,
OnlineBankingThailand,
AchBankDebit,
SepaBankDebit,
BecsBankDebit,
BacsBankDebit,
AchBankTransfer,
SepaBankTransfer,
BacsBankTransfer,
MultibancoBankTransfer,
PermataBankTransfer,
BcaBankTransfer,
BniVaBankTransfer,
BriVaBankTransfer,
CimbVaBankTransfer,
DanamonVaBankTransfer,
MandiriVaBankTransfer,
Pix,
Pse,
Crypto,
MandatePayment,
Reward,
Upi,
Boleto,
Efecty,
PagoEfectivo,
RedCompra,
RedPagos,
Alfamart,
Indomaret,
Oxxo,
SevenEleven,
Lawson,
MiniStop,
FamilyMart,
Seicomart,
PayEasy,
Givex,
PaySafeCar,
CardToken,
LocalBankTransfer,
Mifinity,
Fps,
PromptPay,
VietQr,
OpenBanking,
NetworkToken,
NetworkTransactionIdAndCardDetails,
DirectCarrierBilling,
InstantBankTransfer,
}
impl From<PaymentMethodData> for PaymentMethodDataType {
fn from(pm_data: PaymentMethodData) -> Self {
match pm_data {
PaymentMethodData::Card(_) => Self::Card,
PaymentMethodData::NetworkToken(_) => Self::NetworkToken,
PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Self::NetworkTransactionIdAndCardDetails
}
PaymentMethodData::CardRedirect(card_redirect_data) => match card_redirect_data {
payment_method_data::CardRedirectData::Knet {} => Self::Knet,
payment_method_data::CardRedirectData::Benefit {} => Self::Benefit,
payment_method_data::CardRedirectData::MomoAtm {} => Self::MomoAtm,
payment_method_data::CardRedirectData::CardRedirect {} => Self::CardRedirect,
},
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
payment_method_data::WalletData::AliPayQr(_) => Self::AliPayQr,
payment_method_data::WalletData::AliPayRedirect(_) => Self::AliPayRedirect,
payment_method_data::WalletData::AliPayHkRedirect(_) => Self::AliPayHkRedirect,
payment_method_data::WalletData::AmazonPayRedirect(_) => Self::AmazonPayRedirect,
payment_method_data::WalletData::MomoRedirect(_) => Self::MomoRedirect,
payment_method_data::WalletData::KakaoPayRedirect(_) => Self::KakaoPayRedirect,
payment_method_data::WalletData::GoPayRedirect(_) => Self::GoPayRedirect,
payment_method_data::WalletData::GcashRedirect(_) => Self::GcashRedirect,
payment_method_data::WalletData::ApplePay(_) => Self::ApplePay,
payment_method_data::WalletData::ApplePayRedirect(_) => Self::ApplePayRedirect,
payment_method_data::WalletData::ApplePayThirdPartySdk(_) => {
Self::ApplePayThirdPartySdk
}
payment_method_data::WalletData::DanaRedirect {} => Self::DanaRedirect,
payment_method_data::WalletData::GooglePay(_) => Self::GooglePay,
payment_method_data::WalletData::GooglePayRedirect(_) => Self::GooglePayRedirect,
payment_method_data::WalletData::GooglePayThirdPartySdk(_) => {
Self::GooglePayThirdPartySdk
}
payment_method_data::WalletData::MbWayRedirect(_) => Self::MbWayRedirect,
payment_method_data::WalletData::MobilePayRedirect(_) => Self::MobilePayRedirect,
payment_method_data::WalletData::PaypalRedirect(_) => Self::PaypalRedirect,
payment_method_data::WalletData::PaypalSdk(_) => Self::PaypalSdk,
payment_method_data::WalletData::Paze(_) => Self::Paze,
payment_method_data::WalletData::SamsungPay(_) => Self::SamsungPay,
payment_method_data::WalletData::TwintRedirect {} => Self::TwintRedirect,
payment_method_data::WalletData::VippsRedirect {} => Self::VippsRedirect,
payment_method_data::WalletData::TouchNGoRedirect(_) => Self::TouchNGoRedirect,
payment_method_data::WalletData::WeChatPayRedirect(_) => Self::WeChatPayRedirect,
payment_method_data::WalletData::WeChatPayQr(_) => Self::WeChatPayQr,
payment_method_data::WalletData::CashappQr(_) => Self::CashappQr,
payment_method_data::WalletData::SwishQr(_) => Self::SwishQr,
payment_method_data::WalletData::Mifinity(_) => Self::Mifinity,
},
PaymentMethodData::PayLater(pay_later_data) => match pay_later_data {
payment_method_data::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect,
payment_method_data::PayLaterData::KlarnaSdk { .. } => Self::KlarnaSdk,
payment_method_data::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect,
payment_method_data::PayLaterData::AfterpayClearpayRedirect { .. } => {
Self::AfterpayClearpayRedirect
}
payment_method_data::PayLaterData::PayBrightRedirect {} => Self::PayBrightRedirect,
payment_method_data::PayLaterData::WalleyRedirect {} => Self::WalleyRedirect,
payment_method_data::PayLaterData::AlmaRedirect {} => Self::AlmaRedirect,
payment_method_data::PayLaterData::AtomeRedirect {} => Self::AtomeRedirect,
},
PaymentMethodData::BankRedirect(bank_redirect_data) => match bank_redirect_data {
payment_method_data::BankRedirectData::BancontactCard { .. } => {
Self::BancontactCard
}
payment_method_data::BankRedirectData::Bizum {} => Self::Bizum,
payment_method_data::BankRedirectData::Blik { .. } => Self::Blik,
payment_method_data::BankRedirectData::Eft { .. } => Self::Eft,
payment_method_data::BankRedirectData::Eps { .. } => Self::Eps,
payment_method_data::BankRedirectData::Giropay { .. } => Self::Giropay,
payment_method_data::BankRedirectData::Ideal { .. } => Self::Ideal,
payment_method_data::BankRedirectData::Interac { .. } => Self::Interac,
payment_method_data::BankRedirectData::OnlineBankingCzechRepublic { .. } => {
Self::OnlineBankingCzechRepublic
}
payment_method_data::BankRedirectData::OnlineBankingFinland { .. } => {
Self::OnlineBankingFinland
}
payment_method_data::BankRedirectData::OnlineBankingPoland { .. } => {
Self::OnlineBankingPoland
}
payment_method_data::BankRedirectData::OnlineBankingSlovakia { .. } => {
Self::OnlineBankingSlovakia
}
payment_method_data::BankRedirectData::OpenBankingUk { .. } => Self::OpenBankingUk,
payment_method_data::BankRedirectData::Przelewy24 { .. } => Self::Przelewy24,
payment_method_data::BankRedirectData::Sofort { .. } => Self::Sofort,
payment_method_data::BankRedirectData::Trustly { .. } => Self::Trustly,
payment_method_data::BankRedirectData::OnlineBankingFpx { .. } => {
Self::OnlineBankingFpx
}
payment_method_data::BankRedirectData::OnlineBankingThailand { .. } => {
Self::OnlineBankingThailand
}
payment_method_data::BankRedirectData::LocalBankRedirect {} => {
Self::LocalBankRedirect
}
},
PaymentMethodData::BankDebit(bank_debit_data) => match bank_debit_data {
payment_method_data::BankDebitData::AchBankDebit { .. } => Self::AchBankDebit,
payment_method_data::BankDebitData::SepaBankDebit { .. } => Self::SepaBankDebit,
payment_method_data::BankDebitData::BecsBankDebit { .. } => Self::BecsBankDebit,
payment_method_data::BankDebitData::BacsBankDebit { .. } => Self::BacsBankDebit,
},
PaymentMethodData::BankTransfer(bank_transfer_data) => match *bank_transfer_data {
payment_method_data::BankTransferData::AchBankTransfer { .. } => {
Self::AchBankTransfer
}
payment_method_data::BankTransferData::SepaBankTransfer { .. } => {
Self::SepaBankTransfer
}
payment_method_data::BankTransferData::BacsBankTransfer { .. } => {
Self::BacsBankTransfer
}
payment_method_data::BankTransferData::MultibancoBankTransfer { .. } => {
Self::MultibancoBankTransfer
}
payment_method_data::BankTransferData::PermataBankTransfer { .. } => {
Self::PermataBankTransfer
}
payment_method_data::BankTransferData::BcaBankTransfer { .. } => {
Self::BcaBankTransfer
}
payment_method_data::BankTransferData::BniVaBankTransfer { .. } => {
Self::BniVaBankTransfer
}
payment_method_data::BankTransferData::BriVaBankTransfer { .. } => {
Self::BriVaBankTransfer
}
payment_method_data::BankTransferData::CimbVaBankTransfer { .. } => {
Self::CimbVaBankTransfer
}
payment_method_data::BankTransferData::DanamonVaBankTransfer { .. } => {
Self::DanamonVaBankTransfer
}
payment_method_data::BankTransferData::MandiriVaBankTransfer { .. } => {
Self::MandiriVaBankTransfer
}
payment_method_data::BankTransferData::Pix { .. } => Self::Pix,
payment_method_data::BankTransferData::Pse {} => Self::Pse,
payment_method_data::BankTransferData::LocalBankTransfer { .. } => {
Self::LocalBankTransfer
}
payment_method_data::BankTransferData::InstantBankTransfer {} => {
Self::InstantBankTransfer
}
},
PaymentMethodData::Crypto(_) => Self::Crypto,
PaymentMethodData::MandatePayment => Self::MandatePayment,
PaymentMethodData::Reward => Self::Reward,
PaymentMethodData::Upi(_) => Self::Upi,
PaymentMethodData::Voucher(voucher_data) => match voucher_data {
payment_method_data::VoucherData::Boleto(_) => Self::Boleto,
payment_method_data::VoucherData::Efecty => Self::Efecty,
payment_method_data::VoucherData::PagoEfectivo => Self::PagoEfectivo,
payment_method_data::VoucherData::RedCompra => Self::RedCompra,
payment_method_data::VoucherData::RedPagos => Self::RedPagos,
payment_method_data::VoucherData::Alfamart(_) => Self::Alfamart,
payment_method_data::VoucherData::Indomaret(_) => Self::Indomaret,
payment_method_data::VoucherData::Oxxo => Self::Oxxo,
payment_method_data::VoucherData::SevenEleven(_) => Self::SevenEleven,
payment_method_data::VoucherData::Lawson(_) => Self::Lawson,
payment_method_data::VoucherData::MiniStop(_) => Self::MiniStop,
payment_method_data::VoucherData::FamilyMart(_) => Self::FamilyMart,
payment_method_data::VoucherData::Seicomart(_) => Self::Seicomart,
payment_method_data::VoucherData::PayEasy(_) => Self::PayEasy,
},
PaymentMethodData::RealTimePayment(real_time_payment_data) => {
match *real_time_payment_data {
payment_method_data::RealTimePaymentData::DuitNow {} => Self::DuitNow,
payment_method_data::RealTimePaymentData::Fps {} => Self::Fps,
payment_method_data::RealTimePaymentData::PromptPay {} => Self::PromptPay,
payment_method_data::RealTimePaymentData::VietQr {} => Self::VietQr,
}
}
PaymentMethodData::GiftCard(gift_card_data) => match *gift_card_data {
payment_method_data::GiftCardData::Givex(_) => Self::Givex,
payment_method_data::GiftCardData::PaySafeCard {} => Self::PaySafeCar,
},
PaymentMethodData::CardToken(_) => Self::CardToken,
PaymentMethodData::OpenBanking(data) => match data {
payment_method_data::OpenBankingData::OpenBankingPIS {} => Self::OpenBanking,
},
PaymentMethodData::MobilePayment(mobile_payment_data) => match mobile_payment_data {
payment_method_data::MobilePaymentData::DirectCarrierBilling { .. } => {
Self::DirectCarrierBilling
}
},
}
}
}
pub trait ApplePay {
fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error>;
}
impl ApplePay for payment_method_data::ApplePayWalletData {
fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error> {
let token = Secret::new(
String::from_utf8(BASE64_ENGINE.decode(&self.payment_data).change_context(
errors::ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
},
)?)
.change_context(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?,
);
Ok(token)
}
}
pub trait WalletData {
fn get_wallet_token(&self) -> Result<Secret<String>, Error>;
fn get_wallet_token_as_json<T>(&self, wallet_name: String) -> Result<T, Error>
where
T: serde::de::DeserializeOwned;
fn get_encoded_wallet_token(&self) -> Result<String, Error>;
}
impl WalletData for payment_method_data::WalletData {
fn get_wallet_token(&self) -> Result<Secret<String>, Error> {
match self {
Self::GooglePay(data) => Ok(Secret::new(data.tokenization_data.token.clone())),
Self::ApplePay(data) => Ok(data.get_applepay_decoded_payment_data()?),
Self::PaypalSdk(data) => Ok(Secret::new(data.token.clone())),
_ => Err(errors::ConnectorError::InvalidWallet.into()),
}
}
fn get_wallet_token_as_json<T>(&self, wallet_name: String) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
serde_json::from_str::<T>(self.get_wallet_token()?.peek())
.change_context(errors::ConnectorError::InvalidWalletToken { wallet_name })
}
fn get_encoded_wallet_token(&self) -> Result<String, Error> {
match self {
Self::GooglePay(_) => {
let json_token: Value = self.get_wallet_token_as_json("Google Pay".to_owned())?;
let token_as_vec = serde_json::to_vec(&json_token).change_context(
errors::ConnectorError::InvalidWalletToken {
wallet_name: "Google Pay".to_string(),
},
)?;
let encoded_token = BASE64_ENGINE.encode(token_as_vec);
Ok(encoded_token)
}
_ => Err(
errors::ConnectorError::NotImplemented("SELECTED PAYMENT METHOD".to_owned()).into(),
),
}
}
}
pub fn deserialize_xml_to_struct<T: serde::de::DeserializeOwned>(
xml_data: &[u8],
) -> Result<T, errors::ConnectorError> {
let response_str = std::str::from_utf8(xml_data)
.map_err(|e| {
router_env::logger::error!("Error converting response data to UTF-8: {:?}", e);
errors::ConnectorError::ResponseDeserializationFailed
})?
.trim();
let result: T = quick_xml::de::from_str(response_str).map_err(|e| {
router_env::logger::error!("Error deserializing XML response: {:?}", e);
errors::ConnectorError::ResponseDeserializationFailed
})?;
Ok(result)
}
pub fn is_html_response(response: &str) -> bool {
response.starts_with("<html>") || response.starts_with("<!DOCTYPE html>")
}
#[cfg(feature = "payouts")]
pub trait PayoutsData {
fn get_transfer_id(&self) -> Result<String, Error>;
fn get_customer_details(
&self,
) -> Result<hyperswitch_domain_models::router_request_types::CustomerDetails, Error>;
fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error>;
#[cfg(feature = "payouts")]
fn get_payout_type(&self) -> Result<enums::PayoutType, Error>;
}
#[cfg(feature = "payouts")]
impl PayoutsData for hyperswitch_domain_models::router_request_types::PayoutsData {
fn get_transfer_id(&self) -> Result<String, Error> {
self.connector_payout_id
.clone()
.ok_or_else(missing_field_err("transfer_id"))
}
fn get_customer_details(
&self,
) -> Result<hyperswitch_domain_models::router_request_types::CustomerDetails, Error> {
self.customer_details
.clone()
.ok_or_else(missing_field_err("customer_details"))
}
fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error> {
self.vendor_details
.clone()
.ok_or_else(missing_field_err("vendor_details"))
}
#[cfg(feature = "payouts")]
fn get_payout_type(&self) -> Result<enums::PayoutType, Error> {
self.payout_type
.to_owned()
.ok_or_else(missing_field_err("payout_type"))
}
}
pub trait RevokeMandateRequestData {
fn get_connector_mandate_id(&self) -> Result<String, Error>;
}
impl RevokeMandateRequestData for MandateRevokeRequestData {
fn get_connector_mandate_id(&self) -> Result<String, Error> {
self.connector_mandate_id
.clone()
.ok_or_else(missing_field_err("connector_mandate_id"))
}
}
pub trait RecurringMandateData {
fn get_original_payment_amount(&self) -> Result<i64, Error>;
fn get_original_payment_currency(&self) -> Result<enums::Currency, Error>;
}
impl RecurringMandateData for RecurringMandatePaymentData {
fn get_original_payment_amount(&self) -> Result<i64, Error> {
self.original_payment_authorized_amount
.ok_or_else(missing_field_err("original_payment_authorized_amount"))
}
fn get_original_payment_currency(&self) -> Result<enums::Currency, Error> {
self.original_payment_authorized_currency
.ok_or_else(missing_field_err("original_payment_authorized_currency"))
}
}
#[cfg(feature = "payouts")]
impl CardData for api_models::payouts::CardPayout {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding = self.expiry_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
fn get_card_expiry_month_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let exp_month = self
.expiry_month
.peek()
.to_string()
.parse::<u8>()
.map_err(|_| errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_month",
})?;
let month = ::cards::CardExpirationMonth::try_from(exp_month).map_err(|_| {
errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_month",
}
})?;
Ok(Secret::new(month.two_digits()))
}
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.card_number.peek())
}
fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
self.expiry_month.peek(),
delimiter,
year.peek()
)))
}
fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
year.peek(),
delimiter,
self.expiry_month.peek()
))
}
fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
self.expiry_month.peek(),
delimiter,
year.peek()
))
}
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.expiry_year.peek().clone();
if year.len() == 2 {
year = format!("20{}", year);
}
Secret::new(year)
}
fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.expiry_month.clone().expose();
Ok(Secret::new(format!("{year}{month}")))
}
fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> {
self.expiry_month
.peek()
.clone()
.parse::<i8>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> {
self.expiry_year
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.expiry_month.clone().expose();
Ok(Secret::new(format!("{month}{year}")))
}
fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error> {
self.get_expiry_year_4_digit()
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_cardholder_name(&self) -> Result<Secret<String>, Error> {
self.card_holder_name
.clone()
.ok_or_else(missing_field_err("card.card_holder_name"))
}
}
pub trait NetworkTokenData {
fn get_card_issuer(&self) -> Result<CardIssuer, Error>;
fn get_expiry_year_4_digit(&self) -> Secret<String>;
fn get_network_token(&self) -> NetworkTokenNumber;
fn get_network_token_expiry_month(&self) -> Secret<String>;
fn get_network_token_expiry_year(&self) -> Secret<String>;
fn get_cryptogram(&self) -> Option<Secret<String>>;
}
impl NetworkTokenData for payment_method_data::NetworkTokenData {
#[cfg(feature = "v1")]
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.token_number.peek())
}
#[cfg(feature = "v2")]
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.network_token.peek())
}
#[cfg(feature = "v1")]
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.token_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{}", year);
}
Secret::new(year)
}
#[cfg(feature = "v2")]
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.network_token_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{}", year);
}
Secret::new(year)
}
#[cfg(feature = "v1")]
fn get_network_token(&self) -> NetworkTokenNumber {
self.token_number.clone()
}
#[cfg(feature = "v2")]
fn get_network_token(&self) -> NetworkTokenNumber {
self.network_token.clone()
}
#[cfg(feature = "v1")]
fn get_network_token_expiry_month(&self) -> Secret<String> {
self.token_exp_month.clone()
}
#[cfg(feature = "v2")]
fn get_network_token_expiry_month(&self) -> Secret<String> {
self.network_token_exp_month.clone()
}
#[cfg(feature = "v1")]
fn get_network_token_expiry_year(&self) -> Secret<String> {
self.token_exp_year.clone()
}
#[cfg(feature = "v2")]
fn get_network_token_expiry_year(&self) -> Secret<String> {
self.network_token_exp_year.clone()
}
#[cfg(feature = "v1")]
fn get_cryptogram(&self) -> Option<Secret<String>> {
self.token_cryptogram.clone()
}
#[cfg(feature = "v2")]
fn get_cryptogram(&self) -> Option<Secret<String>> {
self.cryptogram.clone()
}
}
pub fn convert_uppercase<'de, D, T>(v: D) -> Result<T, D::Error>
where
D: serde::Deserializer<'de>,
T: FromStr,
<T as FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error,
{
use serde::de::Error;
let output = <&str>::deserialize(v)?;
output.to_uppercase().parse::<T>().map_err(D::Error::custom)
}
pub(crate) fn convert_setup_mandate_router_data_to_authorize_router_data(
data: &SetupMandateRouterData,
) -> PaymentsAuthorizeData {
PaymentsAuthorizeData {
currency: data.request.currency,
payment_method_data: data.request.payment_method_data.clone(),
confirm: data.request.confirm,
statement_descriptor_suffix: data.request.statement_descriptor_suffix.clone(),
mandate_id: data.request.mandate_id.clone(),
setup_future_usage: data.request.setup_future_usage,
off_session: data.request.off_session,
setup_mandate_details: data.request.setup_mandate_details.clone(),
router_return_url: data.request.router_return_url.clone(),
email: data.request.email.clone(),
customer_name: data.request.customer_name.clone(),
amount: 0,
order_tax_amount: Some(MinorUnit::zero()),
minor_amount: MinorUnit::new(0),
statement_descriptor: None,
capture_method: data.request.capture_method,
webhook_url: None,
complete_authorize_url: None,
browser_info: data.request.browser_info.clone(),
order_details: None,
order_category: None,
session_token: None,
enrolled_for_3ds: true,
related_transaction_id: None,
payment_experience: None,
payment_method_type: None,
customer_id: None,
surcharge_details: None,
request_extended_authorization: None,
request_incremental_authorization: data.request.request_incremental_authorization,
metadata: None,
authentication_data: None,
customer_acceptance: data.request.customer_acceptance.clone(),
split_payments: None, // TODO: allow charges on mandates?
merchant_order_reference_id: None,
integrity_object: None,
additional_payment_method_data: None,
shipping_cost: data.request.shipping_cost,
merchant_account_id: None,
merchant_config_currency: None,
}
}
pub(crate) fn convert_payment_authorize_router_response<F1, F2, T1, T2>(
item: (&ConnectorRouterData<F1, T1, PaymentsResponseData>, T2),
) -> ConnectorRouterData<F2, T2, PaymentsResponseData> {
let data = item.0;
let request = item.1;
ConnectorRouterData {
flow: PhantomData,
request,
merchant_id: data.merchant_id.clone(),
connector: data.connector.clone(),
attempt_id: data.attempt_id.clone(),
tenant_id: data.tenant_id.clone(),
status: data.status,
payment_method: data.payment_method,
connector_auth_type: data.connector_auth_type.clone(),
description: data.description.clone(),
address: data.address.clone(),
auth_type: data.auth_type,
connector_meta_data: data.connector_meta_data.clone(),
connector_wallets_details: data.connector_wallets_details.clone(),
amount_captured: data.amount_captured,
minor_amount_captured: data.minor_amount_captured,
access_token: data.access_token.clone(),
response: data.response.clone(),
payment_id: data.payment_id.clone(),
session_token: data.session_token.clone(),
reference_id: data.reference_id.clone(),
customer_id: data.customer_id.clone(),
payment_method_token: None,
preprocessing_id: None,
connector_customer: data.connector_customer.clone(),
recurring_mandate_payment_data: data.recurring_mandate_payment_data.clone(),
connector_request_reference_id: data.connector_request_reference_id.clone(),
#[cfg(feature = "payouts")]
payout_method_data: data.payout_method_data.clone(),
#[cfg(feature = "payouts")]
quote_id: data.quote_id.clone(),
test_mode: data.test_mode,
payment_method_status: None,
payment_method_balance: data.payment_method_balance.clone(),
connector_api_version: data.connector_api_version.clone(),
connector_http_status_code: data.connector_http_status_code,
external_latency: data.external_latency,
apple_pay_flow: data.apple_pay_flow.clone(),
frm_metadata: data.frm_metadata.clone(),
dispute_id: data.dispute_id.clone(),
refund_id: data.refund_id.clone(),
connector_response: data.connector_response.clone(),
integrity_check: Ok(()),
additional_merchant_data: data.additional_merchant_data.clone(),
header_payload: data.header_payload.clone(),
connector_mandate_request_reference_id: data.connector_mandate_request_reference_id.clone(),
authentication_id: data.authentication_id.clone(),
psd2_sca_exemption_type: data.psd2_sca_exemption_type,
}
}
pub fn generate_12_digit_number() -> u64 {
let mut rng = rand::thread_rng();
rng.gen_range(100_000_000_000..=999_999_999_999)
}
/// Normalizes a string by converting to lowercase, performing NFKD normalization(https://unicode.org/reports/tr15/#Description_Norm),and removing special characters and spaces.
pub fn normalize_string(value: String) -> Result<String, regex::Error> {
let nfkd_value = value.nfkd().collect::<String>();
let lowercase_value = nfkd_value.to_lowercase();
static REGEX: std::sync::LazyLock<Result<Regex, regex::Error>> =
std::sync::LazyLock::new(|| Regex::new(r"[^a-z0-9]"));
let regex = REGEX.as_ref().map_err(|e| e.clone())?;
let normalized = regex.replace_all(&lowercase_value, "").to_string();
Ok(normalized)
}
| 68,325 | 2,071 |
hyperswitch | crates/hyperswitch_connectors/src/default_implementations_v2.rs | .rs | use hyperswitch_domain_models::{
router_data::AccessToken,
router_data_v2::{
flow_common_types::{
BillingConnectorPaymentsSyncFlowData, DisputesFlowData, MandateRevokeFlowData,
PaymentFlowData, RefundFlowData, RevenueRecoveryRecordBackData,
WebhookSourceVerifyData,
},
AccessTokenFlowData, ExternalAuthenticationFlowData, FilesFlowData,
},
router_flow_types::{
authentication::{
Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall,
},
dispute::{Accept, Defend, Evidence},
files::{Retrieve, Upload},
mandate_revoke::MandateRevoke,
payments::{
Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize,
CreateConnectorCustomer, IncrementalAuthorization, PSync, PaymentMethodToken,
PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session,
SetupMandate, Void,
},
refunds::{Execute, RSync},
revenue_recovery::{BillingConnectorPaymentsSync, RecoveryRecordBack},
webhooks::VerifyWebhookSource,
AccessTokenAuth,
},
router_request_types::{
authentication,
revenue_recovery::{BillingConnectorPaymentsSyncRequest, RevenueRecoveryRecordBackRequest},
AcceptDisputeRequestData, AccessTokenRequestData, AuthorizeSessionTokenData,
CompleteAuthorizeData, ConnectorCustomerData, DefendDisputeRequestData,
MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsApproveData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData,
PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData,
PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, RefundsData,
RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData,
SubmitEvidenceRequestData, UploadFileRequestData, VerifyWebhookSourceRequestData,
},
router_response_types::{
revenue_recovery::{
BillingConnectorPaymentsSyncResponse, RevenueRecoveryRecordBackResponse,
},
AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse,
MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData, RetrieveFileResponse,
SubmitEvidenceResponse, TaxCalculationResponseData, UploadFileResponse,
VerifyWebhookSourceResponseData,
},
};
#[cfg(feature = "frm")]
use hyperswitch_domain_models::{
router_data_v2::FrmFlowData,
router_flow_types::fraud_check::{Checkout, Fulfillment, RecordReturn, Sale, Transaction},
router_request_types::fraud_check::{
FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData,
FraudCheckSaleData, FraudCheckTransactionData,
},
router_response_types::fraud_check::FraudCheckResponseData,
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_data_v2::PayoutFlowData,
router_flow_types::payouts::{
PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount,
PoSync,
},
router_request_types::PayoutsData,
router_response_types::PayoutsResponseData,
};
#[cfg(feature = "frm")]
use hyperswitch_interfaces::api::fraud_check_v2::{
FraudCheckCheckoutV2, FraudCheckFulfillmentV2, FraudCheckRecordReturnV2, FraudCheckSaleV2,
FraudCheckTransactionV2, FraudCheckV2,
};
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::api::payouts_v2::{
PayoutCancelV2, PayoutCreateV2, PayoutEligibilityV2, PayoutFulfillV2, PayoutQuoteV2,
PayoutRecipientAccountV2, PayoutRecipientV2, PayoutSyncV2,
};
use hyperswitch_interfaces::{
api::{
authentication_v2::{
ConnectorAuthenticationV2, ConnectorPostAuthenticationV2, ConnectorPreAuthenticationV2,
ConnectorPreAuthenticationVersionCallV2, ExternalAuthenticationV2,
},
disputes_v2::{AcceptDisputeV2, DefendDisputeV2, DisputeV2, SubmitEvidenceV2},
files_v2::{FileUploadV2, RetrieveFileV2, UploadFileV2},
payments_v2::{
ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2,
PaymentAuthorizeV2, PaymentCaptureV2, PaymentIncrementalAuthorizationV2,
PaymentPostSessionTokensV2, PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2,
PaymentSyncV2, PaymentTokenV2, PaymentV2, PaymentVoidV2, PaymentsCompleteAuthorizeV2,
PaymentsPostProcessingV2, PaymentsPreProcessingV2, TaxCalculationV2,
},
refunds_v2::{RefundExecuteV2, RefundSyncV2, RefundV2},
revenue_recovery_v2::{
BillingConnectorPaymentsSyncIntegrationV2, RevenueRecoveryRecordBackV2,
RevenueRecoveryV2,
},
ConnectorAccessTokenV2, ConnectorMandateRevokeV2, ConnectorVerifyWebhookSourceV2,
},
connector_integration_v2::ConnectorIntegrationV2,
};
use crate::connectors;
macro_rules! default_imp_for_new_connector_integration_payment {
($($path:ident::$connector:ident),*) => {
$(
impl PaymentV2 for $path::$connector{}
impl PaymentAuthorizeV2 for $path::$connector{}
impl PaymentAuthorizeSessionTokenV2 for $path::$connector{}
impl PaymentSyncV2 for $path::$connector{}
impl PaymentVoidV2 for $path::$connector{}
impl PaymentApproveV2 for $path::$connector{}
impl PaymentRejectV2 for $path::$connector{}
impl PaymentCaptureV2 for $path::$connector{}
impl PaymentSessionV2 for $path::$connector{}
impl MandateSetupV2 for $path::$connector{}
impl PaymentIncrementalAuthorizationV2 for $path::$connector{}
impl PaymentsCompleteAuthorizeV2 for $path::$connector{}
impl PaymentTokenV2 for $path::$connector{}
impl ConnectorCustomerV2 for $path::$connector{}
impl PaymentsPreProcessingV2 for $path::$connector{}
impl PaymentsPostProcessingV2 for $path::$connector{}
impl TaxCalculationV2 for $path::$connector{}
impl PaymentSessionUpdateV2 for $path::$connector{}
impl PaymentPostSessionTokensV2 for $path::$connector{}
impl
ConnectorIntegrationV2<Authorize,PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData>
for $path::$connector{}
impl
ConnectorIntegrationV2<PSync,PaymentFlowData, PaymentsSyncData, PaymentsResponseData>
for $path::$connector{}
impl
ConnectorIntegrationV2<Void, PaymentFlowData, PaymentsCancelData, PaymentsResponseData>
for $path::$connector{}
impl
ConnectorIntegrationV2<Approve,PaymentFlowData, PaymentsApproveData, PaymentsResponseData>
for $path::$connector{}
impl
ConnectorIntegrationV2<Reject,PaymentFlowData, PaymentsRejectData, PaymentsResponseData>
for $path::$connector{}
impl
ConnectorIntegrationV2<Capture,PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>
for $path::$connector{}
impl
ConnectorIntegrationV2<Session,PaymentFlowData, PaymentsSessionData, PaymentsResponseData>
for $path::$connector{}
impl
ConnectorIntegrationV2<SetupMandate,PaymentFlowData, SetupMandateRequestData, PaymentsResponseData>
for $path::$connector{}
impl
ConnectorIntegrationV2<
IncrementalAuthorization,
PaymentFlowData,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
>
for $path::$connector{}
impl
ConnectorIntegrationV2<
CompleteAuthorize,
PaymentFlowData,
CompleteAuthorizeData,
PaymentsResponseData,
> for $path::$connector{}
impl
ConnectorIntegrationV2<
PaymentMethodToken,
PaymentFlowData,
PaymentMethodTokenizationData,
PaymentsResponseData,
> for $path::$connector{}
impl
ConnectorIntegrationV2<
CreateConnectorCustomer,
PaymentFlowData,
ConnectorCustomerData,
PaymentsResponseData,
> for $path::$connector{}
impl ConnectorIntegrationV2<
PreProcessing,
PaymentFlowData,
PaymentsPreProcessingData,
PaymentsResponseData,
> for $path::$connector{}
impl ConnectorIntegrationV2<
PostProcessing,
PaymentFlowData,
PaymentsPostProcessingData,
PaymentsResponseData,
> for $path::$connector{}
impl
ConnectorIntegrationV2<
AuthorizeSessionToken,
PaymentFlowData,
AuthorizeSessionTokenData,
PaymentsResponseData
> for $path::$connector{}
impl ConnectorIntegrationV2<
CalculateTax,
PaymentFlowData,
PaymentsTaxCalculationData,
TaxCalculationResponseData,
> for $path::$connector{}
impl ConnectorIntegrationV2<
SdkSessionUpdate,
PaymentFlowData,
SdkPaymentsSessionUpdateData,
PaymentsResponseData,
> for $path::$connector{}
impl
ConnectorIntegrationV2<
PostSessionTokens,
PaymentFlowData,
PaymentsPostSessionTokensData,
PaymentsResponseData,
> for $path::$connector{}
)*
};
}
default_imp_for_new_connector_integration_payment!(
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
macro_rules! default_imp_for_new_connector_integration_refund {
($($path:ident::$connector:ident),*) => {
$(
impl RefundV2 for $path::$connector{}
impl RefundExecuteV2 for $path::$connector{}
impl RefundSyncV2 for $path::$connector{}
impl
ConnectorIntegrationV2<Execute, RefundFlowData, RefundsData, RefundsResponseData>
for $path::$connector{}
impl
ConnectorIntegrationV2<RSync, RefundFlowData, RefundsData, RefundsResponseData>
for $path::$connector{}
)*
};
}
default_imp_for_new_connector_integration_refund!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Wellsfargo,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
macro_rules! default_imp_for_new_connector_integration_connector_access_token {
($($path:ident::$connector:ident),*) => {
$(
impl ConnectorAccessTokenV2 for $path::$connector{}
impl
ConnectorIntegrationV2<AccessTokenAuth, AccessTokenFlowData, AccessTokenRequestData, AccessToken>
for $path::$connector{}
)*
};
}
default_imp_for_new_connector_integration_connector_access_token!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
macro_rules! default_imp_for_new_connector_integration_accept_dispute {
($($path:ident::$connector:ident),*) => {
$(
impl DisputeV2 for $path::$connector {}
impl AcceptDisputeV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
Accept,
DisputesFlowData,
AcceptDisputeRequestData,
AcceptDisputeResponse,
> for $path::$connector
{}
)*
};
}
default_imp_for_new_connector_integration_accept_dispute!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
macro_rules! default_imp_for_new_connector_integration_submit_evidence {
($($path:ident::$connector:ident),*) => {
$(
impl SubmitEvidenceV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
Evidence,
DisputesFlowData,
SubmitEvidenceRequestData,
SubmitEvidenceResponse,
> for $path::$connector
{}
)*
};
}
default_imp_for_new_connector_integration_submit_evidence!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
macro_rules! default_imp_for_new_connector_integration_defend_dispute {
($($path:ident::$connector:ident),*) => {
$(
impl DefendDisputeV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
Defend,
DisputesFlowData,
DefendDisputeRequestData,
DefendDisputeResponse,
> for $path::$connector
{}
)*
};
}
default_imp_for_new_connector_integration_defend_dispute!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
macro_rules! default_imp_for_new_connector_integration_file_upload {
($($path:ident::$connector:ident),*) => {
$(
impl FileUploadV2 for $path::$connector {}
impl UploadFileV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
Upload,
FilesFlowData,
UploadFileRequestData,
UploadFileResponse,
> for $path::$connector
{}
impl RetrieveFileV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
Retrieve,
FilesFlowData,
RetrieveFileRequestData,
RetrieveFileResponse,
> for $path::$connector
{}
)*
};
}
default_imp_for_new_connector_integration_file_upload!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_create {
($($path:ident::$connector:ident),*) => {
$(
impl PayoutCreateV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
PoCreate,
PayoutFlowData,
PayoutsData,
PayoutsResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_create!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_eligibility {
($($path:ident::$connector:ident),*) => {
$(
impl PayoutEligibilityV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
PoEligibility,
PayoutFlowData,
PayoutsData,
PayoutsResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_fulfill {
($($path:ident::$connector:ident),*) => {
$(
impl PayoutFulfillV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
PoFulfill,
PayoutFlowData,
PayoutsData,
PayoutsResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_cancel {
($($path:ident::$connector:ident),*) => {
$(
impl PayoutCancelV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
PoCancel,
PayoutFlowData,
PayoutsData,
PayoutsResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_quote {
($($path:ident::$connector:ident),*) => {
$(
impl PayoutQuoteV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
PoQuote,
PayoutFlowData,
PayoutsData,
PayoutsResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_quote!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_recipient {
($($path:ident::$connector:ident),*) => {
$(
impl PayoutRecipientV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
PoRecipient,
PayoutFlowData,
PayoutsData,
PayoutsResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_sync {
($($path:ident::$connector:ident),*) => {
$(
impl PayoutSyncV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
PoSync,
PayoutFlowData,
PayoutsData,
PayoutsResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_sync!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account {
($($path:ident::$connector:ident),*) => {
$(
impl PayoutRecipientAccountV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
PoRecipientAccount,
PayoutFlowData,
PayoutsData,
PayoutsResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
macro_rules! default_imp_for_new_connector_integration_webhook_source_verification {
($($path:ident::$connector:ident),*) => {
$(
impl ConnectorVerifyWebhookSourceV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
VerifyWebhookSource,
WebhookSourceVerifyData,
VerifyWebhookSourceRequestData,
VerifyWebhookSourceResponseData,
> for $path::$connector
{}
)*
};
}
default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_new_connector_integration_frm_sale {
($($path:ident::$connector:ident),*) => {
$(
impl FraudCheckSaleV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
Sale,
FrmFlowData,
FraudCheckSaleData,
FraudCheckResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "frm")]
default_imp_for_new_connector_integration_frm_sale!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_new_connector_integration_frm_checkout {
($($path:ident::$connector:ident),*) => {
$(
impl FraudCheckCheckoutV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
Checkout,
FrmFlowData,
FraudCheckCheckoutData,
FraudCheckResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "frm")]
default_imp_for_new_connector_integration_frm_checkout!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_new_connector_integration_frm_transaction {
($($path:ident::$connector:ident),*) => {
$(
impl FraudCheckTransactionV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
Transaction,
FrmFlowData,
FraudCheckTransactionData,
FraudCheckResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "frm")]
default_imp_for_new_connector_integration_frm_transaction!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_new_connector_integration_frm_fulfillment {
($($path:ident::$connector:ident),*) => {
$(
impl FraudCheckFulfillmentV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
Fulfillment,
FrmFlowData,
FraudCheckFulfillmentData,
FraudCheckResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "frm")]
default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_new_connector_integration_frm_record_return {
($($path:ident::$connector:ident),*) => {
$(
impl FraudCheckRecordReturnV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
RecordReturn,
FrmFlowData,
FraudCheckRecordReturnData,
FraudCheckResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "frm")]
default_imp_for_new_connector_integration_frm_record_return!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
macro_rules! default_imp_for_new_connector_integration_revoking_mandates {
($($path:ident::$connector:ident),*) => {
$( impl ConnectorMandateRevokeV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
MandateRevoke,
MandateRevokeFlowData,
MandateRevokeRequestData,
MandateRevokeResponseData,
> for $path::$connector
{}
)*
};
}
default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_new_connector_integration_frm {
($($path:ident::$connector:ident),*) => {
$(
impl FraudCheckV2 for $path::$connector {}
)*
};
}
#[cfg(feature = "frm")]
default_imp_for_new_connector_integration_frm!(
connectors::Airwallex,
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Boku,
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Globepay,
connectors::Hipay,
connectors::Gocardless,
connectors::Helcim,
connectors::Inespay,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Nomupay,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Paybox,
connectors::Payeezy,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mollie,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
macro_rules! default_imp_for_new_connector_integration_connector_authentication {
($($path:ident::$connector:ident),*) => {
$( impl ExternalAuthenticationV2 for $path::$connector {}
impl ConnectorAuthenticationV2 for $path::$connector {}
impl ConnectorPreAuthenticationV2 for $path::$connector {}
impl ConnectorPreAuthenticationVersionCallV2 for $path::$connector {}
impl ConnectorPostAuthenticationV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
Authentication,
ExternalAuthenticationFlowData,
authentication::ConnectorAuthenticationRequestData,
AuthenticationResponseData,
> for $path::$connector
{}
impl
ConnectorIntegrationV2<
PreAuthentication,
ExternalAuthenticationFlowData,
authentication::PreAuthNRequestData,
AuthenticationResponseData,
> for $path::$connector
{}
impl
ConnectorIntegrationV2<
PreAuthenticationVersionCall,
ExternalAuthenticationFlowData,
authentication::PreAuthNRequestData,
AuthenticationResponseData,
> for $path::$connector
{}
impl
ConnectorIntegrationV2<
PostAuthentication,
ExternalAuthenticationFlowData,
authentication::ConnectorPostAuthenticationRequestData,
AuthenticationResponseData,
> for $path::$connector
{}
)*
};
}
default_imp_for_new_connector_integration_connector_authentication!(
connectors::Airwallex,
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Boku,
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Globepay,
connectors::Gocardless,
connectors::Helcim,
connectors::Hipay,
connectors::Inespay,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Nomupay,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Paybox,
connectors::Payeezy,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mollie,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
macro_rules! default_imp_for_new_connector_integration_revenue_recovery {
($($path:ident::$connector:ident),*) => {
$( impl RevenueRecoveryV2 for $path::$connector {}
impl BillingConnectorPaymentsSyncIntegrationV2 for $path::$connector {}
impl RevenueRecoveryRecordBackV2 for $path::$connector {}
impl
ConnectorIntegrationV2<
RecoveryRecordBack,
RevenueRecoveryRecordBackData,
RevenueRecoveryRecordBackRequest,
RevenueRecoveryRecordBackResponse,
> for $path::$connector
{}
impl
ConnectorIntegrationV2<
BillingConnectorPaymentsSync,
BillingConnectorPaymentsSyncFlowData,
BillingConnectorPaymentsSyncRequest,
BillingConnectorPaymentsSyncResponse,
> for $path::$connector
{}
)*
};
}
default_imp_for_new_connector_integration_revenue_recovery!(
connectors::Airwallex,
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Boku,
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Globepay,
connectors::Gocardless,
connectors::Helcim,
connectors::Hipay,
connectors::Inespay,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Nomupay,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Paybox,
connectors::Payeezy,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mollie,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
| 18,725 | 2,072 |
hyperswitch | crates/hyperswitch_connectors/src/types.rs | .rs | #[cfg(feature = "payouts")]
use hyperswitch_domain_models::types::{PayoutsData, PayoutsResponseData};
use hyperswitch_domain_models::{
router_data::{AccessToken, RouterData},
router_flow_types::{
Accept, AccessTokenAuth, Authorize, Capture, Defend, Evidence, PSync, PreProcessing,
Session, Upload, Void,
},
router_request_types::{
AcceptDisputeRequestData, AccessTokenRequestData, DefendDisputeRequestData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData,
PaymentsSessionData, PaymentsSyncData, RefundsData, SubmitEvidenceRequestData,
UploadFileRequestData,
},
router_response_types::{
AcceptDisputeResponse, DefendDisputeResponse, PaymentsResponseData, RefundsResponseData,
SubmitEvidenceResponse, UploadFileResponse,
},
};
pub(crate) type PaymentsSyncResponseRouterData<R> =
ResponseRouterData<PSync, R, PaymentsSyncData, PaymentsResponseData>;
pub(crate) type PaymentsResponseRouterData<R> =
ResponseRouterData<Authorize, R, PaymentsAuthorizeData, PaymentsResponseData>;
pub(crate) type PaymentsCaptureResponseRouterData<R> =
ResponseRouterData<Capture, R, PaymentsCaptureData, PaymentsResponseData>;
pub(crate) type RefundsResponseRouterData<F, R> =
ResponseRouterData<F, R, RefundsData, RefundsResponseData>;
pub(crate) type RefreshTokenRouterData =
RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>;
pub(crate) type PaymentsCancelResponseRouterData<R> =
ResponseRouterData<Void, R, PaymentsCancelData, PaymentsResponseData>;
pub(crate) type PaymentsPreprocessingResponseRouterData<R> =
ResponseRouterData<PreProcessing, R, PaymentsPreProcessingData, PaymentsResponseData>;
pub(crate) type PaymentsSessionResponseRouterData<R> =
ResponseRouterData<Session, R, PaymentsSessionData, PaymentsResponseData>;
pub(crate) type AcceptDisputeRouterData =
RouterData<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>;
pub(crate) type SubmitEvidenceRouterData =
RouterData<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>;
pub(crate) type UploadFileRouterData =
RouterData<Upload, UploadFileRequestData, UploadFileResponse>;
pub(crate) type DefendDisputeRouterData =
RouterData<Defend, DefendDisputeRequestData, DefendDisputeResponse>;
#[cfg(feature = "payouts")]
pub type PayoutsResponseRouterData<F, R> =
ResponseRouterData<F, R, PayoutsData, PayoutsResponseData>;
// TODO: Remove `ResponseRouterData` from router crate after all the related type aliases are moved to this crate.
pub struct ResponseRouterData<Flow, R, Request, Response> {
pub response: R,
pub data: RouterData<Flow, Request, Response>,
pub http_code: u16,
}
| 628 | 2,073 |
hyperswitch | crates/hyperswitch_connectors/src/lib.rs | .rs | //! Hyperswitch connectors
pub mod connectors;
pub mod constants;
pub mod default_implementations;
pub mod default_implementations_v2;
pub mod metrics;
pub mod types;
pub mod utils;
| 42 | 2,074 |
hyperswitch | crates/hyperswitch_connectors/src/connectors.rs | .rs | pub mod aci;
pub mod adyen;
pub mod airwallex;
pub mod amazonpay;
pub mod authorizedotnet;
pub mod bambora;
pub mod bamboraapac;
pub mod bankofamerica;
pub mod billwerk;
pub mod bitpay;
pub mod bluesnap;
pub mod boku;
pub mod braintree;
pub mod cashtocode;
pub mod chargebee;
pub mod checkout;
pub mod coinbase;
pub mod coingate;
pub mod cryptopay;
pub mod ctp_mastercard;
pub mod cybersource;
pub mod datatrans;
pub mod deutschebank;
pub mod digitalvirgo;
pub mod dlocal;
pub mod elavon;
pub mod facilitapay;
pub mod fiserv;
pub mod fiservemea;
pub mod fiuu;
pub mod forte;
pub mod getnet;
pub mod globalpay;
pub mod globepay;
pub mod gocardless;
pub mod helcim;
pub mod hipay;
pub mod iatapay;
pub mod inespay;
pub mod itaubank;
pub mod jpmorgan;
pub mod juspaythreedsserver;
pub mod klarna;
pub mod mifinity;
pub mod mollie;
pub mod moneris;
pub mod multisafepay;
pub mod nexinets;
pub mod nexixpay;
pub mod nomupay;
pub mod noon;
pub mod novalnet;
pub mod nuvei;
pub mod opayo;
pub mod opennode;
pub mod paybox;
pub mod payeezy;
pub mod payme;
pub mod paypal;
pub mod paystack;
pub mod payu;
pub mod placetopay;
pub mod powertranz;
pub mod prophetpay;
pub mod rapyd;
pub mod razorpay;
pub mod recurly;
pub mod redsys;
pub mod shift4;
pub mod square;
pub mod stax;
pub mod stripebilling;
pub mod taxjar;
pub mod thunes;
pub mod trustpay;
pub mod tsys;
pub mod unified_authentication_service;
pub mod volt;
pub mod wellsfargo;
pub mod worldline;
pub mod worldpay;
pub mod xendit;
pub mod zen;
pub mod zsl;
pub use self::{
aci::Aci, adyen::Adyen, airwallex::Airwallex, amazonpay::Amazonpay,
authorizedotnet::Authorizedotnet, bambora::Bambora, bamboraapac::Bamboraapac,
bankofamerica::Bankofamerica, billwerk::Billwerk, bitpay::Bitpay, bluesnap::Bluesnap,
boku::Boku, braintree::Braintree, cashtocode::Cashtocode, chargebee::Chargebee,
checkout::Checkout, coinbase::Coinbase, coingate::Coingate, cryptopay::Cryptopay,
ctp_mastercard::CtpMastercard, cybersource::Cybersource, datatrans::Datatrans,
deutschebank::Deutschebank, digitalvirgo::Digitalvirgo, dlocal::Dlocal, elavon::Elavon,
facilitapay::Facilitapay, fiserv::Fiserv, fiservemea::Fiservemea, fiuu::Fiuu, forte::Forte,
getnet::Getnet, globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless,
helcim::Helcim, hipay::Hipay, iatapay::Iatapay, inespay::Inespay, itaubank::Itaubank,
jpmorgan::Jpmorgan, juspaythreedsserver::Juspaythreedsserver, klarna::Klarna,
mifinity::Mifinity, mollie::Mollie, moneris::Moneris, multisafepay::Multisafepay,
nexinets::Nexinets, nexixpay::Nexixpay, nomupay::Nomupay, noon::Noon, novalnet::Novalnet,
nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme,
paypal::Paypal, paystack::Paystack, payu::Payu, placetopay::Placetopay, powertranz::Powertranz,
prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys,
shift4::Shift4, square::Square, stax::Stax, stripebilling::Stripebilling, taxjar::Taxjar,
thunes::Thunes, trustpay::Trustpay, tsys::Tsys,
unified_authentication_service::UnifiedAuthenticationService, volt::Volt,
wellsfargo::Wellsfargo, worldline::Worldline, worldpay::Worldpay, xendit::Xendit, zen::Zen,
zsl::Zsl,
};
| 1,092 | 2,075 |
hyperswitch | crates/hyperswitch_connectors/src/default_implementations.rs | .rs | // impl api::PaymentIncrementalAuthorization for Helcim {}
// impl api::ConnectorCustomer for Helcim {}
// impl api::PaymentsPreProcessing for Helcim {}
// impl api::PaymentReject for Helcim {}
// impl api::PaymentApprove for Helcim {}
use common_utils::errors::CustomResult;
#[cfg(feature = "frm")]
use hyperswitch_domain_models::{
router_flow_types::fraud_check::{Checkout, Fulfillment, RecordReturn, Sale, Transaction},
router_request_types::fraud_check::{
FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData,
FraudCheckSaleData, FraudCheckTransactionData,
},
router_response_types::fraud_check::FraudCheckResponseData,
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::payouts::{
PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount,
PoSync,
},
router_request_types::PayoutsData,
router_response_types::PayoutsResponseData,
};
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
use hyperswitch_domain_models::{
router_flow_types::revenue_recovery as recovery_router_flows,
router_request_types::revenue_recovery as recovery_request,
router_response_types::revenue_recovery as recovery_response,
};
use hyperswitch_domain_models::{
router_flow_types::{
authentication::{
Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall,
},
dispute::{Accept, Defend, Evidence},
files::{Retrieve, Upload},
mandate_revoke::MandateRevoke,
payments::{
Approve, AuthorizeSessionToken, CalculateTax, CompleteAuthorize,
CreateConnectorCustomer, IncrementalAuthorization, PostProcessing, PostSessionTokens,
PreProcessing, Reject, SdkSessionUpdate,
},
webhooks::VerifyWebhookSource,
Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate,
},
router_request_types::{
authentication,
unified_authentication_service::{
UasAuthenticationRequestData, UasAuthenticationResponseData,
UasConfirmationRequestData, UasPostAuthenticationRequestData,
UasPreAuthenticationRequestData,
},
AcceptDisputeRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData,
ConnectorCustomerData, DefendDisputeRequestData, MandateRevokeRequestData,
PaymentsApproveData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData,
PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData,
PaymentsTaxCalculationData, RetrieveFileRequestData, SdkPaymentsSessionUpdateData,
SubmitEvidenceRequestData, UploadFileRequestData, VerifyWebhookSourceRequestData,
},
router_response_types::{
AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse,
MandateRevokeResponseData, PaymentsResponseData, RetrieveFileResponse,
SubmitEvidenceResponse, TaxCalculationResponseData, UploadFileResponse,
VerifyWebhookSourceResponseData,
},
};
#[cfg(feature = "frm")]
use hyperswitch_interfaces::api::fraud_check::{
FraudCheck, FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, FraudCheckSale,
FraudCheckTransaction,
};
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::api::payouts::{
PayoutCancel, PayoutCreate, PayoutEligibility, PayoutFulfill, PayoutQuote, PayoutRecipient,
PayoutRecipientAccount, PayoutSync,
};
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
use hyperswitch_interfaces::api::revenue_recovery as recovery_traits;
use hyperswitch_interfaces::{
api::{
self,
authentication::{
ConnectorAuthentication, ConnectorPostAuthentication, ConnectorPreAuthentication,
ConnectorPreAuthenticationVersionCall, ExternalAuthentication,
},
disputes::{AcceptDispute, DefendDispute, Dispute, SubmitEvidence},
files::{FileUpload, RetrieveFile, UploadFile},
payments::{
ConnectorCustomer, PaymentApprove, PaymentAuthorizeSessionToken,
PaymentIncrementalAuthorization, PaymentPostSessionTokens, PaymentReject,
PaymentSessionUpdate, PaymentsCompleteAuthorize, PaymentsPostProcessing,
PaymentsPreProcessing, TaxCalculation,
},
revenue_recovery::RevenueRecovery,
ConnectorIntegration, ConnectorMandateRevoke, ConnectorRedirectResponse,
ConnectorTransactionId, UasAuthentication, UasAuthenticationConfirmation,
UasPostAuthentication, UasPreAuthentication, UnifiedAuthenticationService,
},
errors::ConnectorError,
};
macro_rules! default_imp_for_authorize_session_token {
($($path:ident::$connector:ident),*) => {
$( impl PaymentAuthorizeSessionToken for $path::$connector {}
impl
ConnectorIntegration<
AuthorizeSessionToken,
AuthorizeSessionTokenData,
PaymentsResponseData
> for $path::$connector
{}
)*
};
}
default_imp_for_authorize_session_token!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Stripebilling,
connectors::Taxjar,
connectors::UnifiedAuthenticationService,
connectors::Volt,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
macro_rules! default_imp_for_calculate_tax {
($($path:ident::$connector:ident),*) => {
$( impl TaxCalculation for $path::$connector {}
impl
ConnectorIntegration<
CalculateTax,
PaymentsTaxCalculationData,
TaxCalculationResponseData,
> for $path::$connector
{}
)*
};
}
default_imp_for_calculate_tax!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Paybox,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nuvei,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Volt,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
macro_rules! default_imp_for_session_update {
($($path:ident::$connector:ident),*) => {
$( impl PaymentSessionUpdate for $path::$connector {}
impl
ConnectorIntegration<
SdkSessionUpdate,
SdkPaymentsSessionUpdateData,
PaymentsResponseData,
> for $path::$connector
{}
)*
};
}
default_imp_for_session_update!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Forte,
connectors::Getnet,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::UnifiedAuthenticationService,
connectors::Fiuu,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::Deutschebank,
connectors::Volt,
connectors::CtpMastercard
);
macro_rules! default_imp_for_post_session_tokens {
($($path:ident::$connector:ident),*) => {
$( impl PaymentPostSessionTokens for $path::$connector {}
impl
ConnectorIntegration<
PostSessionTokens,
PaymentsPostSessionTokensData,
PaymentsResponseData,
> for $path::$connector
{}
)*
};
}
default_imp_for_post_session_tokens!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Billwerk,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Forte,
connectors::Getnet,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Square,
connectors::Stax,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Fiuu,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Deutschebank,
connectors::Volt,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
use crate::connectors;
macro_rules! default_imp_for_complete_authorize {
($($path:ident::$connector:ident),*) => {
$(
impl PaymentsCompleteAuthorize for $path::$connector {}
impl
ConnectorIntegration<
CompleteAuthorize,
CompleteAuthorizeData,
PaymentsResponseData,
> for $path::$connector
{}
)*
};
}
default_imp_for_complete_authorize!(
connectors::Aci,
connectors::Adyen,
connectors::Amazonpay,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Datatrans,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Mifinity,
connectors::Moneris,
connectors::Multisafepay,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Opayo,
connectors::Opennode,
connectors::Payeezy,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Wellsfargo,
connectors::Worldline,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
macro_rules! default_imp_for_incremental_authorization {
($($path:ident::$connector:ident),*) => {
$(
impl PaymentIncrementalAuthorization for $path::$connector {}
impl
ConnectorIntegration<
IncrementalAuthorization,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
> for $path::$connector
{}
)*
};
}
default_imp_for_incremental_authorization!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
macro_rules! default_imp_for_create_customer {
($($path:ident::$connector:ident),*) => {
$(
impl ConnectorCustomer for $path::$connector {}
impl
ConnectorIntegration<
CreateConnectorCustomer,
ConnectorCustomerData,
PaymentsResponseData,
> for $path::$connector
{}
)*
};
}
default_imp_for_create_customer!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
macro_rules! default_imp_for_connector_redirect_response {
($($path:ident::$connector:ident),*) => {
$(
impl ConnectorRedirectResponse for $path::$connector {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
_action: common_enums::enums::PaymentAction
) -> CustomResult<common_enums::enums::CallConnectorAction, ConnectorError> {
Ok(common_enums::enums::CallConnectorAction::Trigger)
}
}
)*
};
}
default_imp_for_connector_redirect_response!(
connectors::Aci,
connectors::Adyen,
connectors::Amazonpay,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Mifinity,
connectors::Moneris,
connectors::Multisafepay,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Payeezy,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Wellsfargo,
connectors::Worldline,
connectors::Volt,
connectors::Zsl,
connectors::CtpMastercard
);
macro_rules! default_imp_for_pre_processing_steps{
($($path:ident::$connector:ident),*)=> {
$(
impl PaymentsPreProcessing for $path::$connector {}
impl
ConnectorIntegration<
PreProcessing,
PaymentsPreProcessingData,
PaymentsResponseData,
> for $path::$connector
{}
)*
};
}
default_imp_for_pre_processing_steps!(
connectors::Aci,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Opayo,
connectors::Opennode,
connectors::Paybox,
connectors::Payeezy,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
macro_rules! default_imp_for_post_processing_steps{
($($path:ident::$connector:ident),*)=> {
$(
impl PaymentsPostProcessing for $path::$connector {}
impl
ConnectorIntegration<
PostProcessing,
PaymentsPostProcessingData,
PaymentsResponseData,
> for $path::$connector
{}
)*
};
}
default_imp_for_post_processing_steps!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
macro_rules! default_imp_for_approve {
($($path:ident::$connector:ident),*) => {
$(
impl PaymentApprove for $path::$connector {}
impl
ConnectorIntegration<
Approve,
PaymentsApproveData,
PaymentsResponseData,
> for $path::$connector
{}
)*
};
}
default_imp_for_approve!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
macro_rules! default_imp_for_reject {
($($path:ident::$connector:ident),*) => {
$(
impl PaymentReject for $path::$connector {}
impl
ConnectorIntegration<
Reject,
PaymentsRejectData,
PaymentsResponseData,
> for $path::$connector
{}
)*
};
}
default_imp_for_reject!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
macro_rules! default_imp_for_webhook_source_verification {
($($path:ident::$connector:ident),*) => {
$(
impl api::ConnectorVerifyWebhookSource for $path::$connector {}
impl
ConnectorIntegration<
VerifyWebhookSource,
VerifyWebhookSourceRequestData,
VerifyWebhookSourceResponseData,
> for $path::$connector
{}
)*
};
}
default_imp_for_webhook_source_verification!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
macro_rules! default_imp_for_accept_dispute {
($($path:ident::$connector:ident),*) => {
$(
impl Dispute for $path::$connector {}
impl AcceptDispute for $path::$connector {}
impl
ConnectorIntegration<
Accept,
AcceptDisputeRequestData,
AcceptDisputeResponse,
> for $path::$connector
{}
)*
};
}
default_imp_for_accept_dispute!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
macro_rules! default_imp_for_submit_evidence {
($($path:ident::$connector:ident),*) => {
$(
impl SubmitEvidence for $path::$connector {}
impl
ConnectorIntegration<
Evidence,
SubmitEvidenceRequestData,
SubmitEvidenceResponse,
> for $path::$connector
{}
)*
};
}
default_imp_for_submit_evidence!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
macro_rules! default_imp_for_defend_dispute {
($($path:ident::$connector:ident),*) => {
$(
impl DefendDispute for $path::$connector {}
impl
ConnectorIntegration<
Defend,
DefendDisputeRequestData,
DefendDisputeResponse,
> for $path::$connector
{}
)*
};
}
default_imp_for_defend_dispute!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Helcim,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
macro_rules! default_imp_for_file_upload {
($($path:ident::$connector:ident),*) => {
$(
impl FileUpload for $path::$connector {}
impl UploadFile for $path::$connector {}
impl
ConnectorIntegration<
Upload,
UploadFileRequestData,
UploadFileResponse,
> for $path::$connector
{}
impl RetrieveFile for $path::$connector {}
impl
ConnectorIntegration<
Retrieve,
RetrieveFileRequestData,
RetrieveFileResponse,
> for $path::$connector
{}
)*
};
}
default_imp_for_file_upload!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
macro_rules! default_imp_for_payouts {
($($path:ident::$connector:ident),*) => {
$(
impl api::Payouts for $path::$connector {}
)*
};
}
default_imp_for_payouts!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Cryptopay,
connectors::Datatrans,
connectors::Coinbase,
connectors::Coingate,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Paybox,
connectors::Noon,
connectors::Novalnet,
connectors::Nuvei,
connectors::Payeezy,
connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Square,
connectors::Stax,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Volt,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_create {
($($path:ident::$connector:ident),*) => {
$(
impl PayoutCreate for $path::$connector {}
impl
ConnectorIntegration<
PoCreate,
PayoutsData,
PayoutsResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "payouts")]
default_imp_for_payouts_create!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_retrieve {
($($path:ident::$connector:ident),*) => {
$(
impl PayoutSync for $path::$connector {}
impl
ConnectorIntegration<
PoSync,
PayoutsData,
PayoutsResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "payouts")]
default_imp_for_payouts_retrieve!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_eligibility {
($($path:ident::$connector:ident),*) => {
$(
impl PayoutEligibility for $path::$connector {}
impl
ConnectorIntegration<
PoEligibility,
PayoutsData,
PayoutsResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "payouts")]
default_imp_for_payouts_eligibility!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_fulfill {
($($path:ident::$connector:ident),*) => {
$(
impl PayoutFulfill for $path::$connector {}
impl
ConnectorIntegration<
PoFulfill,
PayoutsData,
PayoutsResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "payouts")]
default_imp_for_payouts_fulfill!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_cancel {
($($path:ident::$connector:ident),*) => {
$(
impl PayoutCancel for $path::$connector {}
impl
ConnectorIntegration<
PoCancel,
PayoutsData,
PayoutsResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "payouts")]
default_imp_for_payouts_cancel!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_quote {
($($path:ident::$connector:ident),*) => {
$(
impl PayoutQuote for $path::$connector {}
impl
ConnectorIntegration<
PoQuote,
PayoutsData,
PayoutsResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "payouts")]
default_imp_for_payouts_quote!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_recipient {
($($path:ident::$connector:ident),*) => {
$(
impl PayoutRecipient for $path::$connector {}
impl
ConnectorIntegration<
PoRecipient,
PayoutsData,
PayoutsResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "payouts")]
default_imp_for_payouts_recipient!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_recipient_account {
($($path:ident::$connector:ident),*) => {
$(
impl PayoutRecipientAccount for $path::$connector {}
impl
ConnectorIntegration<
PoRecipientAccount,
PayoutsData,
PayoutsResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "payouts")]
default_imp_for_payouts_recipient_account!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_frm_sale {
($($path:ident::$connector:ident),*) => {
$(
impl FraudCheckSale for $path::$connector {}
impl
ConnectorIntegration<
Sale,
FraudCheckSaleData,
FraudCheckResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "frm")]
default_imp_for_frm_sale!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_frm_checkout {
($($path:ident::$connector:ident),*) => {
$(
impl FraudCheckCheckout for $path::$connector {}
impl
ConnectorIntegration<
Checkout,
FraudCheckCheckoutData,
FraudCheckResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "frm")]
default_imp_for_frm_checkout!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_frm_transaction {
($($path:ident::$connector:ident),*) => {
$(
impl FraudCheckTransaction for $path::$connector {}
impl
ConnectorIntegration<
Transaction,
FraudCheckTransactionData,
FraudCheckResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "frm")]
default_imp_for_frm_transaction!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_frm_fulfillment {
($($path:ident::$connector:ident),*) => {
$(
impl FraudCheckFulfillment for $path::$connector {}
impl
ConnectorIntegration<
Fulfillment,
FraudCheckFulfillmentData,
FraudCheckResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "frm")]
default_imp_for_frm_fulfillment!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_frm_record_return {
($($path:ident::$connector:ident),*) => {
$(
impl FraudCheckRecordReturn for $path::$connector {}
impl
ConnectorIntegration<
RecordReturn,
FraudCheckRecordReturnData,
FraudCheckResponseData,
> for $path::$connector
{}
)*
};
}
#[cfg(feature = "frm")]
default_imp_for_frm_record_return!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
macro_rules! default_imp_for_revoking_mandates {
($($path:ident::$connector:ident),*) => {
$( impl ConnectorMandateRevoke for $path::$connector {}
impl
ConnectorIntegration<
MandateRevoke,
MandateRevokeRequestData,
MandateRevokeResponseData,
> for $path::$connector
{}
)*
};
}
default_imp_for_revoking_mandates!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::CtpMastercard
);
macro_rules! default_imp_for_uas_pre_authentication {
($($path:ident::$connector:ident),*) => {
$( impl UnifiedAuthenticationService for $path::$connector {}
impl UasPreAuthentication for $path::$connector {}
impl
ConnectorIntegration<
PreAuthenticate,
UasPreAuthenticationRequestData,
UasAuthenticationResponseData
> for $path::$connector
{}
)*
};
}
default_imp_for_uas_pre_authentication!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bluesnap,
connectors::Bitpay,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Paybox,
connectors::Placetopay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
macro_rules! default_imp_for_uas_post_authentication {
($($path:ident::$connector:ident),*) => {
$( impl UasPostAuthentication for $path::$connector {}
impl
ConnectorIntegration<
PostAuthenticate,
UasPostAuthenticationRequestData,
UasAuthenticationResponseData
> for $path::$connector
{}
)*
};
}
default_imp_for_uas_post_authentication!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Payeezy,
connectors::Payme,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Paybox,
connectors::Placetopay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
macro_rules! default_imp_for_uas_authentication_confirmation {
($($path:ident::$connector:ident),*) => {
$( impl UasAuthenticationConfirmation for $path::$connector {}
impl
ConnectorIntegration<
AuthenticationConfirmation,
UasConfirmationRequestData,
UasAuthenticationResponseData
> for $path::$connector
{}
)*
};
}
default_imp_for_uas_authentication_confirmation!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bluesnap,
connectors::Bitpay,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Opayo,
connectors::Opennode,
connectors::Nuvei,
connectors::Payeezy,
connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Paybox,
connectors::Paypal,
connectors::Placetopay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
macro_rules! default_imp_for_connector_request_id {
($($path:ident::$connector:ident),*) => {
$(
impl ConnectorTransactionId for $path::$connector {}
)*
};
}
default_imp_for_connector_request_id!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Authorizedotnet,
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bluesnap,
connectors::Bitpay,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Novalnet,
connectors::Noon,
connectors::Nexixpay,
connectors::Nuvei,
connectors::Opayo,
connectors::Opennode,
connectors::Payeezy,
connectors::Paystack,
connectors::Payu,
connectors::Payme,
connectors::Paypal,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Paybox,
connectors::Placetopay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_fraud_check {
($($path:ident::$connector:ident),*) => {
$(
impl FraudCheck for $path::$connector {}
)*
};
}
#[cfg(feature = "frm")]
default_imp_for_fraud_check!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bluesnap,
connectors::Bitpay,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Helcim,
connectors::Hipay,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Novalnet,
connectors::Noon,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Nuvei,
connectors::Opayo,
connectors::Payeezy,
connectors::Paystack,
connectors::Paypal,
connectors::Payu,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Opennode,
connectors::Paybox,
connectors::Payme,
connectors::Placetopay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
macro_rules! default_imp_for_connector_authentication {
($($path:ident::$connector:ident),*) => {
$( impl ExternalAuthentication for $path::$connector {}
impl ConnectorAuthentication for $path::$connector {}
impl ConnectorPreAuthentication for $path::$connector {}
impl ConnectorPreAuthenticationVersionCall for $path::$connector {}
impl ConnectorPostAuthentication for $path::$connector {}
impl
ConnectorIntegration<
Authentication,
authentication::ConnectorAuthenticationRequestData,
AuthenticationResponseData,
> for $path::$connector
{}
impl
ConnectorIntegration<
PreAuthentication,
authentication::PreAuthNRequestData,
AuthenticationResponseData,
> for $path::$connector
{}
impl
ConnectorIntegration<
PreAuthenticationVersionCall,
authentication::PreAuthNRequestData,
AuthenticationResponseData,
> for $path::$connector
{}
impl
ConnectorIntegration<
PostAuthentication,
authentication::ConnectorPostAuthenticationRequestData,
AuthenticationResponseData,
> for $path::$connector
{}
)*
};
}
default_imp_for_connector_authentication!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bluesnap,
connectors::Bitpay,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Nuvei,
connectors::Opayo,
connectors::Opennode,
connectors::Payeezy,
connectors::Paystack,
connectors::Payu,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Paybox,
connectors::Payme,
connectors::Paypal,
connectors::Placetopay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
macro_rules! default_imp_for_uas_authentication {
($($path:ident::$connector:ident),*) => {
$( impl UasAuthentication for $path::$connector {}
impl
ConnectorIntegration<
Authenticate,
UasAuthenticationRequestData,
UasAuthenticationResponseData
> for $path::$connector
{}
)*
};
}
default_imp_for_uas_authentication!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Helcim,
connectors::Hipay,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Nuvei,
connectors::Payeezy,
connectors::Paypal,
connectors::Paystack,
connectors::Payu,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Noon,
connectors::Opayo,
connectors::Opennode,
connectors::Paybox,
connectors::Payme,
connectors::Placetopay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::Wellsfargo,
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
macro_rules! default_imp_for_revenue_recovery {
($($path:ident::$connector:ident),*) => {
$( impl RevenueRecovery for $path::$connector {}
)*
};
}
default_imp_for_revenue_recovery! {
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bluesnap,
connectors::Bitpay,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Checkout,
connectors::Chargebee,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Hipay,
connectors::Helcim,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Nuvei,
connectors::Opayo,
connectors::Opennode,
connectors::Payeezy,
connectors::Paystack,
connectors::Payu,
connectors::Paypal,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Paybox,
connectors::Payme,
connectors::Placetopay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Recurly,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
macro_rules! default_imp_for_billing_connector_payment_sync {
($($path:ident::$connector:ident),*) => {
$( impl recovery_traits::BillingConnectorPaymentsSyncIntegration for $path::$connector {}
impl
ConnectorIntegration<
recovery_router_flows::BillingConnectorPaymentsSync,
recovery_request::BillingConnectorPaymentsSyncRequest,
recovery_response::BillingConnectorPaymentsSyncResponse
> for $path::$connector
{}
)*
};
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
default_imp_for_billing_connector_payment_sync!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bluesnap,
connectors::Bitpay,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Helcim,
connectors::Hipay,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Juspaythreedsserver,
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Nuvei,
connectors::Opayo,
connectors::Opennode,
connectors::Payeezy,
connectors::Paystack,
connectors::Payu,
connectors::Paypal,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Paybox,
connectors::Payme,
connectors::Placetopay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
macro_rules! default_imp_for_revenue_recovery_record_back {
($($path:ident::$connector:ident),*) => {
$( impl recovery_traits::RevenueRecoveryRecordBack for $path::$connector {}
impl
ConnectorIntegration<
recovery_router_flows::RecoveryRecordBack,
recovery_request::RevenueRecoveryRecordBackRequest,
recovery_response::RevenueRecoveryRecordBackResponse
> for $path::$connector
{}
)*
};
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
default_imp_for_revenue_recovery_record_back!(
connectors::Aci,
connectors::Adyen,
connectors::Airwallex,
connectors::Amazonpay,
connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bluesnap,
connectors::Bitpay,
connectors::Braintree,
connectors::Boku,
connectors::Cashtocode,
connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
connectors::CtpMastercard,
connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
connectors::Dlocal,
connectors::Elavon,
connectors::Facilitapay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
connectors::Forte,
connectors::Getnet,
connectors::Globalpay,
connectors::Globepay,
connectors::Gocardless,
connectors::Helcim,
connectors::Hipay,
connectors::Iatapay,
connectors::Inespay,
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Juspaythreedsserver,
connectors::Klarna,
connectors::Nomupay,
connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Nuvei,
connectors::Opayo,
connectors::Opennode,
connectors::Payeezy,
connectors::Paystack,
connectors::Payu,
connectors::Paypal,
connectors::Powertranz,
connectors::Prophetpay,
connectors::Mifinity,
connectors::Mollie,
connectors::Moneris,
connectors::Multisafepay,
connectors::Paybox,
connectors::Payme,
connectors::Placetopay,
connectors::Rapyd,
connectors::Razorpay,
connectors::Redsys,
connectors::Shift4,
connectors::Stax,
connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
| 28,210 | 2,076 |
hyperswitch | crates/hyperswitch_connectors/src/constants.rs | .rs | /// Header Constants
pub(crate) mod headers {
pub(crate) const ACCEPT: &str = "Accept";
pub(crate) const API_KEY: &str = "API-KEY";
pub(crate) const APIKEY: &str = "apikey";
pub(crate) const API_TOKEN: &str = "Api-Token";
pub(crate) const AUTHORIZATION: &str = "Authorization";
pub(crate) const CONTENT_TYPE: &str = "Content-Type";
pub(crate) const DATE: &str = "Date";
pub(crate) const IDEMPOTENCY_KEY: &str = "Idempotency-Key";
pub(crate) const MESSAGE_SIGNATURE: &str = "Message-Signature";
pub(crate) const MERCHANT_ID: &str = "Merchant-ID";
pub(crate) const REQUEST_ID: &str = "request-id";
pub(crate) const NONCE: &str = "nonce";
pub(crate) const TIMESTAMP: &str = "Timestamp";
pub(crate) const TOKEN: &str = "token";
pub(crate) const X_ACCEPT_VERSION: &str = "X-Accept-Version";
pub(crate) const X_CC_API_KEY: &str = "X-CC-Api-Key";
pub(crate) const X_CC_VERSION: &str = "X-CC-Version";
pub(crate) const X_DATE: &str = "X-Date";
pub(crate) const X_LOGIN: &str = "X-Login";
pub(crate) const X_NN_ACCESS_KEY: &str = "X-NN-Access-Key";
pub(crate) const X_TRANS_KEY: &str = "X-Trans-Key";
pub(crate) const X_RANDOM_VALUE: &str = "X-RandomValue";
pub(crate) const X_REQUEST_DATE: &str = "X-RequestDate";
pub(crate) const X_VERSION: &str = "X-Version";
pub(crate) const X_API_KEY: &str = "X-Api-Key";
pub(crate) const CORRELATION_ID: &str = "Correlation-Id";
pub(crate) const WP_API_VERSION: &str = "WP-Api-Version";
pub(crate) const SOURCE: &str = "Source";
pub(crate) const USER_AGENT: &str = "User-Agent";
pub(crate) const KEY: &str = "key";
pub(crate) const X_SIGNATURE: &str = "X-Signature";
pub(crate) const SOAP_ACTION: &str = "SOAPAction";
}
/// Unsupported response type error message
pub const UNSUPPORTED_ERROR_MESSAGE: &str = "Unsupported response type";
/// Error message for Authentication Error from the connector
pub const CONNECTOR_UNAUTHORIZED_ERROR: &str = "Authentication Error from the connector";
/// Error message when Refund request has been voided.
pub const REFUND_VOIDED: &str = "Refund request has been voided.";
pub const LOW_BALANCE_ERROR_MESSAGE: &str = "Insufficient balance in the payment method";
pub const DUIT_NOW_BRAND_COLOR: &str = "#ED2E67";
pub const DUIT_NOW_BRAND_TEXT: &str = "MALAYSIA NATIONAL QR";
pub(crate) const CANNOT_CONTINUE_AUTH: &str =
"Cannot continue with Authorization due to failed Liability Shift.";
#[cfg(feature = "payouts")]
pub(crate) const DEFAULT_NOTIFICATION_SCRIPT_LANGUAGE: &str = "en-US";
| 717 | 2,077 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/fiserv.rs | .rs | pub mod transformers;
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::{
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, 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::{construct_not_implemented_error_report, 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 fiserv::ErrorResponse { error, details } = response;
Ok(error
.or(details)
.and_then(|error_details| {
error_details.first().map(|first_error| ErrorResponse {
code: first_error
.code
.to_owned()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: first_error.message.to_owned(),
reason: first_error.field.to_owned(),
status_code: res.status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
})
.unwrap_or(ErrorResponse {
code: consts::NO_ERROR_CODE.to_string(),
message: consts::NO_ERROR_MESSAGE.to_string(),
reason: None,
status_code: res.status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}))
}
}
impl ConnectorValidation for Fiserv {
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_implemented_error_report(capture_method, self.id()),
),
}
}
}
impl api::ConnectorAccessToken for Fiserv {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Fiserv {
// Not Implemented (R)
}
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)?;
event_builder.map(|i| i.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::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)?;
event_builder.map(|i| i.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_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> {
Ok(format!(
"{}ch/payments/v1/charges",
connectors.fiserv.base_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)?;
event_builder.map(|i| i.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::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)?;
event_builder.map(|i| i.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)
}
}
#[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)?;
event_builder.map(|i| i.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)
}
}
#[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<'_>,
) -> 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))
}
}
impl ConnectorSpecifications for Fiserv {}
| 6,075 | 2,078 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/checkout.rs | .rs | pub mod transformers;
use common_enums::{enums, CallConnectorAction, PaymentAction};
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
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},
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, DefendDisputeResponse, PaymentsResponseData, RefundsResponseData,
RetrieveFileResponse, SubmitEvidenceResponse, UploadFileResponse,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundsRouterData, 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,
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, ConnectorErrorType, RefundsRequestData},
};
#[derive(Clone)]
pub struct Checkout {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Checkout {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
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,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl ConnectorValidation for Checkout {
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
{
// Issue: #173
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Checkout".to_string())
.into(),
)
}
}
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> {
let connector_req = transformers::construct_file_upload_request(req.clone())?;
Ok(RequestContent::FormData(connector_req))
}
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<'_>,
) -> 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<'_>,
) -> CustomResult<DisputePayload, errors::ConnectorError> {
let dispute_details: checkout::CheckoutDisputeWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(DisputePayload {
amount: dispute_details.data.amount.to_string(),
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,
}
}
}
impl ConnectorSpecifications for Checkout {}
| 11,639 | 2,079 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/bluesnap.rs | .rs | pub mod transformers;
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, 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},
CompleteAuthorize,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, ResponseId, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
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},
};
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,
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,
to_currency_lower_unit, 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),
}
impl Bluesnap {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
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,
network_advice_code: None,
network_decline_code: None,
network_error_message: 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,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
},
bluesnap::BluesnapErrors::General(error_response) => {
let (error_res, attempt_status) = if res.status_code == 403
&& error_response.contains(BLUESNAP_TRANSACTION_NOT_FOUND)
{
(
format!(
"{} in bluesnap dashboard",
REQUEST_TIMEOUT_PAYMENT_NOT_FOUND
),
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,
network_advice_code: None,
network_decline_code: None,
network_error_message: 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,
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<'_>,
) -> 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<'_>,
) -> CustomResult<DisputePayload, errors::ConnectorError> {
let dispute_details: bluesnap::BluesnapDisputeWebhookBody =
serde_urlencoded::from_bytes(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(DisputePayload {
amount: to_currency_lower_unit(
dispute_details.invoice_charge_amount.abs().to_string(),
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()?
))
}
impl ConnectorSpecifications for Bluesnap {}
| 12,000 | 2,080 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/payu.rs | .rs | pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::IncomingWebhookEvent;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::ByteSliceExt,
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,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{
PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, PaymentsVoidType,
RefreshTokenType, RefundExecuteType, RefundSyncType, Response,
},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::{Mask, PeekInterface};
use transformers as payu;
use crate::{
constants::headers,
types::{RefreshTokenRouterData, ResponseRouterData},
utils,
};
#[derive(Clone)]
pub struct Payu {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Payu {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Payu
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 headers = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let access_token = req
.access_token
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_header = (
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", access_token.token.peek()).into_masked(),
);
headers.push(auth_header);
Ok(headers)
}
}
impl ConnectorCommon for Payu {
fn id(&self) -> &'static str {
"payu"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.payu.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = payu::PayuAuthType::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: payu::PayuErrorResponse = res
.response
.parse_struct("Payu 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.status.status_code,
message: response.status.status_desc,
reason: response.status.code_literal,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl ConnectorValidation for Payu {}
impl api::Payment for Payu {}
impl api::MandateSetup for Payu {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Payu {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Payu".to_string())
.into(),
)
}
}
impl api::PaymentToken for Payu {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Payu
{
// Not Implemented (R)
}
impl api::PaymentVoid for Payu {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Payu {
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;
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"api/v2_1/orders/",
connector_payment_id
))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Delete)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(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: payu::PayuPaymentsCancelResponse = res
.response
.parse_struct("PaymentCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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 Payu {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Payu {
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"pl/standard/user/oauth/authorize"
))
}
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![(
headers::CONTENT_TYPE.to_string(),
RefreshTokenType::get_content_type(self).to_string().into(),
)])
}
fn get_request_body(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = payu::PayuAuthUpdateRequest::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(RefreshTokenType::get_headers(self, req, connectors)?)
.url(&RefreshTokenType::get_url(self, req, connectors)?)
.set_body(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: payu::PayuAuthUpdateResponse = res
.response
.parse_struct("payu PayuAuthUpdateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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: payu::PayuAccessTokenErrorResponse = res
.response
.parse_struct("Payu AccessTokenErrorResponse")
.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,
message: response.error_description,
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl api::PaymentSync for Payu {}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Payu {
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!(
"{}{}{}",
self.base_url(connectors),
"api/v2_1/orders/",
connector_payment_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)?)
.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: payu::PayuPaymentsSyncResponse = res
.response
.parse_struct("payu OrderResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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::PaymentCapture for Payu {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Payu {
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),
"api/v2_1/orders/",
req.request.connector_transaction_id,
"/status"
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = payu::PayuPaymentsCaptureRequest::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(&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: payu::PayuPaymentsCaptureResponse = res
.response
.parse_struct("payu CaptureResponse")
.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 api::PaymentSession for Payu {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Payu {
//TODO: implement sessions flow
}
impl api::PaymentAuthorize for Payu {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Payu {
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_1/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 = payu::PayuRouterData::try_from((amount, req))?;
let connector_req = payu::PayuPaymentsRequest::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: payu::PayuPaymentsResponse = res
.response
.parse_struct("PayuPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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 Payu {}
impl api::RefundExecute for Payu {}
impl api::RefundSync for Payu {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Payu {
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),
"api/v2_1/orders/",
req.request.connector_transaction_id,
"/refund"
))
}
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 = payu::PayuRouterData::try_from((amount, req))?;
let connector_req = payu::PayuRefundRequest::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: payu::RefundResponse = res
.response
.parse_struct("payu 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 Payu {
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!(
"{}{}{}{}",
self.base_url(connectors),
"api/v2_1/orders/",
req.request.connector_transaction_id,
"/refunds"
))
}
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: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: payu::RefundSyncResponse =
res.response
.parse_struct("payu 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 Payu {
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<'_>,
) -> 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 PAYU_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 payu_supported_payment_methods = SupportedPaymentMethods::new();
payu_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(),
}
}),
),
},
);
payu_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(),
}
}),
),
},
);
payu_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,
},
);
payu_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,
},
);
payu_supported_payment_methods
});
static PAYU_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Payu",
description:
"PayU is a global fintech company providing online payment solutions, including card processing, UPI, wallets, and BNPL services across multiple markets ",
connector_type: enums::PaymentConnectorCategory::PaymentGateway,
};
static PAYU_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Payu {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&PAYU_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*PAYU_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&PAYU_SUPPORTED_WEBHOOK_FLOWS)
}
}
| 6,534 | 2,081 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/bitpay.rs | .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,
network_advice_code: None,
network_decline_code: None,
network_error_message: 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<'_>,
) -> 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::PaymentConnectorCategory::AlternativePaymentMethod,
};
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)
}
}
| 3,496 | 2,082 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/iatapay.rs | .rs | pub mod transformers;
use api_models::{enums, webhooks::IncomingWebhookEvent};
use base64::Engine;
use common_utils::{
consts::BASE64_ENGINE,
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, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
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},
};
use lazy_static::lazy_static;
use masking::{Mask, PeekInterface};
use transformers::{self as iatapay, IatapayPaymentsResponse};
use crate::{
constants::{headers, CONNECTOR_UNAUTHORIZED_ERROR},
types::{RefreshTokenRouterData, ResponseRouterData},
utils::{base64_decode, convert_amount, get_header_key_value},
};
#[derive(Clone)]
pub struct Iatapay {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Iatapay {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Iatapay {}
impl api::PaymentSession for Iatapay {}
impl api::ConnectorAccessToken for Iatapay {}
impl api::MandateSetup for Iatapay {}
impl api::PaymentAuthorize for Iatapay {}
impl api::PaymentSync for Iatapay {}
impl api::PaymentCapture for Iatapay {}
impl api::PaymentVoid for Iatapay {}
impl api::Refund for Iatapay {}
impl api::RefundExecute for Iatapay {}
impl api::RefundSync for Iatapay {}
impl api::PaymentToken for Iatapay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Iatapay
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Iatapay
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 headers = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let access_token = req
.access_token
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_header = (
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", access_token.token.peek()).into_masked(),
);
headers.push(auth_header);
Ok(headers)
}
}
impl ConnectorCommon for Iatapay {
fn id(&self) -> &'static str {
"iatapay"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.iatapay.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = iatapay::IatapayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.client_id.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response_error_message = if res.response.is_empty() && res.status_code == 401 {
ErrorResponse {
status_code: res.status_code,
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: Some(CONNECTOR_UNAUTHORIZED_ERROR.to_string()),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}
} else {
let response: iatapay::IatapayErrorResponse = res
.response
.parse_struct("IatapayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
ErrorResponse {
status_code: res.status_code,
code: response.error,
message: response.message.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: response.reason,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}
};
Ok(response_error_message)
}
}
impl ConnectorValidation for Iatapay {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Iatapay {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Iatapay {
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "/oauth/token"))
}
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> {
let auth: iatapay::IatapayAuthType =
iatapay::IatapayAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_id = format!("{}:{}", auth.client_id.peek(), auth.client_secret.peek());
let auth_val: String = format!("Basic {}", BASE64_ENGINE.encode(auth_id));
Ok(vec![
(
headers::CONTENT_TYPE.to_string(),
types::RefreshTokenType::get_content_type(self)
.to_string()
.into(),
),
(headers::AUTHORIZATION.to_string(), auth_val.into_masked()),
])
}
fn get_request_body(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = iatapay::IatapayAuthUpdateRequest::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: iatapay::IatapayAuthUpdateResponse = res
.response
.parse_struct("iatapay IatapayAuthUpdateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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: iatapay::IatapayAccessTokenErrorResponse = res
.response
.parse_struct("Iatapay AccessTokenErrorResponse")
.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.clone(),
message: response.path.unwrap_or(response.error),
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Iatapay {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Iatapay".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Iatapay {
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 = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = iatapay::IatapayRouterData::try_from((amount, req))?;
let connector_req = iatapay::IatapayPaymentsRequest::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: IatapayPaymentsResponse = res
.response
.parse_struct("Iatapay 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 Iatapay {
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: iatapay::IatapayAuthType =
iatapay::IatapayAuthType::try_from(&req.connector_auth_type)?;
let merchant_id = auth.merchant_id.peek();
Ok(format!(
"{}/merchants/{merchant_id}/payments/{}",
self.base_url(connectors),
req.connector_request_reference_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: IatapayPaymentsResponse = res
.response
.parse_struct("iatapay 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 Iatapay {
fn build_request(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Iatapay".to_string(),
}
.into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Iatapay {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Iatapay {
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),
"/payments/",
req.request.connector_transaction_id,
"/refund"
))
}
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 = iatapay::IatapayRouterData::try_from((refund_amount, req))?;
let connector_req = iatapay::IatapayRefundRequest::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: iatapay::RefundResponse = res
.response
.parse_struct("iatapay 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)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Iatapay {
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!(
"{}{}{}",
self.base_url(connectors),
"/refunds/",
match req.request.connector_refund_id.clone() {
Some(val) => val,
None => req.request.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: iatapay::RefundResponse = res
.response
.parse_struct("iatapay 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 IncomingWebhook for Iatapay {
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 base64_signature = get_header_key_value("Authorization", request.headers)?;
let base64_signature = base64_signature.replace("IATAPAY-HMAC-SHA256 ", "");
base64_decode(base64_signature)
}
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 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: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif: iatapay::IatapayWebhookResponse = request
.body
.parse_struct("IatapayWebhookResponse")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
match notif {
iatapay::IatapayWebhookResponse::IatapayPaymentWebhookBody(wh_body) => {
match wh_body.merchant_payment_id {
Some(merchant_payment_id) => {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::PaymentAttemptId(
merchant_payment_id,
),
))
}
None => Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
wh_body.iata_payment_id,
),
)),
}
}
iatapay::IatapayWebhookResponse::IatapayRefundWebhookBody(wh_body) => {
match wh_body.merchant_refund_id {
Some(merchant_refund_id) => {
Ok(api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::RefundId(merchant_refund_id),
))
}
None => Ok(api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(
wh_body.iata_refund_id,
),
)),
}
}
}
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let notif: iatapay::IatapayWebhookResponse = request
.body
.parse_struct("IatapayWebhookResponse")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
IncomingWebhookEvent::try_from(notif)
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif: iatapay::IatapayWebhookResponse = request
.body
.parse_struct("IatapayWebhookResponse")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
match notif {
iatapay::IatapayWebhookResponse::IatapayPaymentWebhookBody(wh_body) => {
Ok(Box::new(wh_body))
}
iatapay::IatapayWebhookResponse::IatapayRefundWebhookBody(refund_wh_body) => {
Ok(Box::new(refund_wh_body))
}
}
}
}
lazy_static! {
static ref IATAPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Iatapay",
description:
"IATA Pay is a payment method for travellers to pay for air tickets purchased online by directly debiting their bank account.",
connector_type: enums::PaymentConnectorCategory::PaymentGateway,
};
static ref IATAPAY_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic
];
let mut iatapay_supported_payment_methods = SupportedPaymentMethods::new();
iatapay_supported_payment_methods.add(
enums::PaymentMethod::Upi,
enums::PaymentMethodType::UpiCollect,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None
}
);
iatapay_supported_payment_methods.add(
enums::PaymentMethod::Upi,
enums::PaymentMethodType::UpiIntent,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None
}
);
iatapay_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Ideal,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None
}
);
iatapay_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::LocalBankRedirect,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None
}
);
iatapay_supported_payment_methods.add(
enums::PaymentMethod::RealTimePayment,
enums::PaymentMethodType::DuitNow,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None
}
);
iatapay_supported_payment_methods.add(
enums::PaymentMethod::RealTimePayment,
enums::PaymentMethodType::Fps,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None
}
);
iatapay_supported_payment_methods.add(
enums::PaymentMethod::RealTimePayment,
enums::PaymentMethodType::PromptPay,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None
}
);
iatapay_supported_payment_methods.add(
enums::PaymentMethod::RealTimePayment,
enums::PaymentMethodType::VietQr,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None
}
);
iatapay_supported_payment_methods
};
static ref IATAPAY_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> =
vec![enums::EventClass::Payments, enums::EventClass::Refunds,];
}
impl ConnectorSpecifications for Iatapay {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*IATAPAY_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*IATAPAY_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*IATAPAY_SUPPORTED_WEBHOOK_FLOWS)
}
}
| 6,857 | 2,083 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/ctp_mastercard.rs | .rs | use common_utils::errors::CustomResult;
use error_stack::report;
use hyperswitch_domain_models::{
router_data::{AccessToken, 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},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors, webhooks,
};
use crate::constants::headers;
#[derive(Clone)]
pub struct CtpMastercard;
impl api::Payment for CtpMastercard {}
impl api::PaymentSession for CtpMastercard {}
impl api::ConnectorAccessToken for CtpMastercard {}
impl api::MandateSetup for CtpMastercard {}
impl api::PaymentAuthorize for CtpMastercard {}
impl api::PaymentSync for CtpMastercard {}
impl api::PaymentCapture for CtpMastercard {}
impl api::PaymentVoid for CtpMastercard {}
impl api::Refund for CtpMastercard {}
impl api::RefundExecute for CtpMastercard {}
impl api::RefundSync for CtpMastercard {}
impl api::PaymentToken for CtpMastercard {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for CtpMastercard
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for CtpMastercard
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 CtpMastercard {
fn id(&self) -> &'static str {
"ctp_mastercard"
}
fn base_url<'a>(&self, _connectors: &'a Connectors) -> &'a str {
""
}
}
impl ConnectorValidation for CtpMastercard {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for CtpMastercard {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for CtpMastercard {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for CtpMastercard
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for CtpMastercard
{
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for CtpMastercard {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for CtpMastercard {}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for CtpMastercard {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for CtpMastercard {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for CtpMastercard {}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for CtpMastercard {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
impl ConnectorSpecifications for CtpMastercard {}
| 1,012 | 2,084 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/opennode.rs | .rs | pub mod transformers;
use std::fmt::Debug;
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
};
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::{PaymentsResponseData, RefundsResponseData},
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::{self, IncomingWebhook},
};
use masking::{Mask, Maskable};
use transformers as opennode;
use self::opennode::OpennodeWebhookDetails;
use crate::{constants::headers, types::ResponseRouterData};
#[derive(Debug, Clone)]
pub struct Opennode;
impl api::Payment for Opennode {}
impl api::PaymentSession for Opennode {}
impl api::PaymentToken for Opennode {}
impl api::ConnectorAccessToken for Opennode {}
impl api::MandateSetup for Opennode {}
impl api::PaymentAuthorize for Opennode {}
impl api::PaymentSync for Opennode {}
impl api::PaymentCapture for Opennode {}
impl api::PaymentVoid for Opennode {}
impl api::Refund for Opennode {}
impl api::RefundExecute for Opennode {}
impl api::RefundSync for Opennode {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Opennode
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.common_get_content_type().to_string().into(),
),
(
headers::ACCEPT.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 Opennode {
fn id(&self) -> &'static str {
"opennode"
}
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.opennode.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = opennode::OpennodeAuthType::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: opennode::OpennodeErrorResponse = res
.response
.parse_struct("OpennodeErrorResponse")
.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: consts::NO_ERROR_CODE.to_string(),
message: response.message,
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl ConnectorValidation for Opennode {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Opennode
{
// Not Implemented (R)
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Opennode {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Opennode {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Opennode
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Opennode".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Opennode {
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!("{}/v1/charges", self.base_url(_connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = opennode::OpennodeRouterData::try_from((
&self.get_currency_unit(),
req.request.currency,
req.request.amount,
req,
))?;
let connector_req = opennode::OpennodePaymentsRequest::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: opennode::OpennodePaymentsResponse = res
.response
.parse_struct("Opennode 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 Opennode {
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 connector_id = _req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/v2/charge/{}",
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: opennode::OpennodePaymentsResponse = res
.response
.parse_struct("opennode 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 Opennode {
fn build_request(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Opennode".to_string(),
}
.into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Opennode {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Opennode {
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 Opennode {
// default implementation of build_request method will be executed
}
#[async_trait::async_trait]
impl IncomingWebhook for Opennode {
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 = serde_urlencoded::from_bytes::<OpennodeWebhookDetails>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let base64_signature = notif.hashed_order;
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::ParsingFailed)?;
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 = serde_urlencoded::from_bytes::<OpennodeWebhookDetails>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(notif.id),
))
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif = serde_urlencoded::from_bytes::<OpennodeWebhookDetails>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
match notif.status {
opennode::OpennodePaymentStatus::Paid => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
opennode::OpennodePaymentStatus::Underpaid
| opennode::OpennodePaymentStatus::Expired => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired)
}
opennode::OpennodePaymentStatus::Processing => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)
}
_ => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported),
}
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif = serde_urlencoded::from_bytes::<OpennodeWebhookDetails>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Box::new(notif.status))
}
}
impl ConnectorSpecifications for Opennode {}
| 3,415 | 2,085 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/globepay.rs | .rs | pub mod transformers;
use common_utils::{
crypto::{self, GenerateDigest},
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, 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::{PaymentsResponseData, RefundsResponseData},
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::{PaymentsAuthorizeType, PaymentsSyncType, RefundExecuteType, RefundSyncType, Response},
webhooks,
};
use masking::ExposeInterface;
use rand::distributions::DistString;
use time::OffsetDateTime;
use transformers as globepay;
use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount};
#[derive(Clone)]
pub struct Globepay {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Globepay {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Globepay {}
impl api::PaymentSession for Globepay {}
impl api::ConnectorAccessToken for Globepay {}
impl api::MandateSetup for Globepay {}
impl api::PaymentAuthorize for Globepay {}
impl api::PaymentSync for Globepay {}
impl api::PaymentCapture for Globepay {}
impl api::PaymentVoid for Globepay {}
impl api::Refund for Globepay {}
impl api::RefundExecute for Globepay {}
impl api::RefundSync for Globepay {}
impl api::PaymentToken for Globepay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Globepay
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Globepay
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)
}
}
fn get_globlepay_query_params(
connector_auth_type: &ConnectorAuthType,
) -> CustomResult<String, errors::ConnectorError> {
let auth_type = globepay::GlobepayAuthType::try_from(connector_auth_type)?;
let time = (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000).to_string();
let nonce_str = rand::distributions::Alphanumeric.sample_string(&mut rand::thread_rng(), 12);
let valid_string = format!(
"{}&{time}&{nonce_str}&{}",
auth_type.partner_code.expose(),
auth_type.credential_code.expose()
);
let digest = crypto::Sha256
.generate_digest(valid_string.as_bytes())
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("error encoding the query params")?;
let sign = encode(digest).to_lowercase();
let param = format!("?sign={sign}&time={time}&nonce_str={nonce_str}");
Ok(param)
}
fn get_partner_code(
connector_auth_type: &ConnectorAuthType,
) -> CustomResult<String, errors::ConnectorError> {
let auth_type = globepay::GlobepayAuthType::try_from(connector_auth_type)?;
Ok(auth_type.partner_code.expose())
}
impl ConnectorCommon for Globepay {
fn id(&self) -> &'static str {
"globepay"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.globepay.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: globepay::GlobepayErrorResponse = res
.response
.parse_struct("GlobepayErrorResponse")
.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.return_code.to_string(),
message: consts::NO_ERROR_MESSAGE.to_string(),
reason: Some(response.return_msg),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl ConnectorValidation for Globepay {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Globepay {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Globepay {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Globepay
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Globepay".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Globepay {
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 query_params = get_globlepay_query_params(&req.connector_auth_type)?;
if matches!(
req.request.capture_method,
Some(common_enums::enums::CaptureMethod::Automatic)
| Some(common_enums::enums::CaptureMethod::SequentialAutomatic)
) {
Ok(format!(
"{}api/v1.0/gateway/partners/{}/orders/{}{query_params}",
self.base_url(connectors),
get_partner_code(&req.connector_auth_type)?,
req.payment_id
))
} else {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Manual Capture".to_owned(),
connector: "Globepay".to_owned(),
}
.into())
}
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = globepay::GlobepayRouterData::from((amount, req));
let connector_req = globepay::GlobepayPaymentsRequest::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::Put)
.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: globepay::GlobepayPaymentsResponse = res
.response
.parse_struct("Globepay 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 Globepay {
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 query_params = get_globlepay_query_params(&req.connector_auth_type)?;
Ok(format!(
"{}api/v1.0/gateway/partners/{}/orders/{}{query_params}",
self.base_url(connectors),
get_partner_code(&req.connector_auth_type)?,
req.payment_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)?)
.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: globepay::GlobepaySyncResponse = res
.response
.parse_struct("globepay 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 Globepay {
fn build_request(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Manual Capture".to_owned(),
connector: "Globepay".to_owned(),
}
.into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Globepay {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Globepay {
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 query_params = get_globlepay_query_params(&req.connector_auth_type)?;
Ok(format!(
"{}api/v1.0/gateway/partners/{}/orders/{}/refunds/{}{query_params}",
self.base_url(connectors),
get_partner_code(&req.connector_auth_type)?,
req.payment_id,
req.request.refund_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 = globepay::GlobepayRouterData::from((refund_amount, req));
let connector_req = globepay::GlobepayRefundRequest::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::Put)
.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: globepay::GlobepayRefundResponse = 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,
})
}
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 Globepay {
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 query_params = get_globlepay_query_params(&req.connector_auth_type)?;
Ok(format!(
"{}api/v1.0/gateway/partners/{}/orders/{}/refunds/{}{query_params}",
self.base_url(connectors),
get_partner_code(&req.connector_auth_type)?,
req.payment_id,
req.request.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: globepay::GlobepayRefundResponse = 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,
})
}
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 Globepay {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
impl ConnectorSpecifications for Globepay {}
| 4,297 | 2,086 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/coinbase.rs | .rs | pub mod transformers;
use std::fmt::Debug;
use common_enums::enums;
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
configs::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};
#[derive(Debug, Clone)]
pub struct Coinbase;
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,
network_advice_code: None,
network_decline_code: None,
network_error_message: 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 connector_req = coinbase::CoinbasePaymentsRequest::try_from(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(&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<'_>,
) -> 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::PaymentConnectorCategory::PaymentGateway,
};
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)
}
}
| 3,706 | 2,087 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/coingate.rs | .rs | pub mod transformers;
use common_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::{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 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,
network_advice_code: None,
network_decline_code: None,
network_error_message: 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 {
fn validate_connector_against_payment_request(
&self,
capture_method: Option<CaptureMethod>,
_payment_method: PaymentMethod,
_pmt: Option<PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
match capture_method {
CaptureMethod::Automatic | CaptureMethod::SequentialAutomatic => Ok(()),
CaptureMethod::ManualMultiple | CaptureMethod::Scheduled | CaptureMethod::Manual => {
Err(utils::construct_not_supported_error_report(
capture_method,
self.id(),
))
}
}
}
}
#[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<'_>,
) -> 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))
}
}
impl ConnectorSpecifications for Coingate {}
| 4,888 | 2,088 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/powertranz.rs | .rs | pub mod transformers;
use std::fmt::Debug;
use api_models::enums::AuthenticationType;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::{BytesExt, ValueExt},
request::{Method, Request, RequestBuilder, RequestContent},
};
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, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts, errors,
events::connector_api_logs::ConnectorEvent,
types::{
PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType,
PaymentsVoidType, RefundExecuteType, Response,
},
webhooks,
};
use lazy_static::lazy_static;
use masking::{ExposeInterface, Mask};
use transformers as powertranz;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{PaymentsAuthorizeRequestData as _, PaymentsCompleteAuthorizeRequestData as _},
};
#[derive(Debug, Clone)]
pub struct Powertranz;
impl api::Payment for Powertranz {}
impl api::PaymentSession for Powertranz {}
impl api::ConnectorAccessToken for Powertranz {}
impl api::MandateSetup for Powertranz {}
impl api::PaymentAuthorize for Powertranz {}
impl api::PaymentsCompleteAuthorize for Powertranz {}
impl api::PaymentSync for Powertranz {}
impl api::PaymentCapture for Powertranz {}
impl api::PaymentVoid for Powertranz {}
impl api::Refund for Powertranz {}
impl api::RefundExecute for Powertranz {}
impl api::RefundSync for Powertranz {}
impl api::PaymentToken for Powertranz {}
const POWER_TRANZ_ID: &str = "PowerTranz-PowerTranzId";
const POWER_TRANZ_PASSWORD: &str = "PowerTranz-PowerTranzPassword";
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Powertranz
{
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Powertranz
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 auth_header = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut auth_header);
Ok(header)
}
}
impl ConnectorCommon for Powertranz {
fn id(&self) -> &'static str {
"powertranz"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.powertranz.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = powertranz::PowertranzAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![
(
POWER_TRANZ_ID.to_string(),
auth.power_tranz_id.expose().into_masked(),
),
(
POWER_TRANZ_PASSWORD.to_string(),
auth.power_tranz_password.expose().into_masked(),
),
])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
// For error scenarios connector respond with 200 http status code and error response object in response
// For http status code other than 200 they send empty response back
event_builder.map(|i: &mut ConnectorEvent| i.set_error_response_body(&serde_json::json!({"error_response": std::str::from_utf8(&res.response).unwrap_or("")})));
Ok(ErrorResponse {
status_code: res.status_code,
code: consts::NO_ERROR_CODE.to_string(),
message: consts::NO_ERROR_MESSAGE.to_string(),
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl ConnectorValidation for Powertranz {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Powertranz {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Powertranz {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Powertranz
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Powertranz".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Powertranz {
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 mut endpoint = match req.request.is_auto_capture()? {
true => "sale",
false => "auth",
}
.to_string();
// 3ds payments uses different endpoints
if req.auth_type == AuthenticationType::ThreeDs {
endpoint.insert_str(0, "spi/")
};
Ok(format!("{}{endpoint}", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = powertranz::PowertranzPaymentsRequest::try_from(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(&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: powertranz::PowertranzBaseResponse = res
.response
.parse_struct("Powertranz 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 Powertranz
{
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 {
"application/json-patch+json"
}
fn get_url(
&self,
_req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}spi/payment", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let redirect_payload: powertranz::RedirectResponsePayload = req
.request
.get_redirect_response_payload()?
.parse_value("PowerTranz RedirectResponsePayload")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let spi_token = format!(r#""{}""#, redirect_payload.spi_token.expose());
Ok(RequestContent::Json(Box::new(spi_token)))
}
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: powertranz::PowertranzBaseResponse = res
.response
.parse_struct("Powertranz 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 Powertranz {
// default implementation of build_request method will be executed
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Powertranz {
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!("{}capture", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = powertranz::PowertranzBaseRequest::try_from(&req.request)?;
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: powertranz::PowertranzBaseResponse = res
.response
.parse_struct("Powertranz 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 Powertranz {
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: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}void", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = powertranz::PowertranzBaseRequest::try_from(&req.request)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
&self,
data: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: powertranz::PowertranzBaseResponse = res
.response
.parse_struct("powertranz 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 build_request(
&self,
req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
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_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 Powertranz {
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!("{}refund", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = powertranz::PowertranzBaseRequest::try_from(req)?;
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: powertranz::PowertranzBaseResponse = res
.response
.parse_struct("powertranz 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 Powertranz {
// default implementation of build_request method will be executed
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Powertranz {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
lazy_static! {
static ref POWERTRANZ_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
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 powertranz_supported_payment_methods = SupportedPaymentMethods::new();
powertranz_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(),
}
}),
),
}
);
powertranz_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(),
}
}),
),
}
);
powertranz_supported_payment_methods
};
static ref POWERTRANZ_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Powertranz",
description:
"Powertranz is a leading payment gateway serving the Caribbean and parts of Central America ",
connector_type: enums::PaymentConnectorCategory::PaymentGateway,
};
static ref POWERTRANZ_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
}
impl ConnectorSpecifications for Powertranz {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*POWERTRANZ_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*POWERTRANZ_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*POWERTRANZ_SUPPORTED_WEBHOOK_FLOWS)
}
}
| 5,214 | 2,089 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/jpmorgan.rs | .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, MinorUnit, MinorUnitForConnector},
};
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, RefreshTokenType, Response},
webhooks,
};
use masking::{Mask, Maskable, PeekInterface};
use transformers::{self as jpmorgan, JpmorganErrorResponse};
use crate::{
constants::headers,
types::{RefreshTokenRouterData, ResponseRouterData},
utils,
};
#[derive(Clone)]
pub struct Jpmorgan {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Jpmorgan {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Jpmorgan {}
impl api::PaymentSession for Jpmorgan {}
impl api::ConnectorAccessToken for Jpmorgan {}
impl api::MandateSetup for Jpmorgan {}
impl api::PaymentAuthorize for Jpmorgan {}
impl api::PaymentSync for Jpmorgan {}
impl api::PaymentCapture for Jpmorgan {}
impl api::PaymentVoid for Jpmorgan {}
impl api::Refund for Jpmorgan {}
impl api::RefundExecute for Jpmorgan {}
impl api::RefundSync for Jpmorgan {}
impl api::PaymentToken for Jpmorgan {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Jpmorgan
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Jpmorgan
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 headers = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let auth_header = (
headers::AUTHORIZATION.to_string(),
format!(
"Bearer {}",
req.access_token
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?
.token
.peek()
)
.into_masked(),
);
let request_id = (
headers::REQUEST_ID.to_string(),
req.connector_request_reference_id
.clone()
.to_string()
.into_masked(),
);
let merchant_id = (
headers::MERCHANT_ID.to_string(),
req.merchant_id.get_string_repr().to_string().into_masked(),
);
headers.push(auth_header);
headers.push(request_id);
headers.push(merchant_id);
Ok(headers)
}
}
impl ConnectorCommon for Jpmorgan {
fn id(&self) -> &'static str {
"jpmorgan"
}
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.jpmorgan.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: JpmorganErrorResponse = res
.response
.parse_struct("JpmorganErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
router_env::logger::info!(connector_response=?response);
event_builder.map(|i| i.set_response_body(&response));
let response_message = response
.response_message
.as_ref()
.map_or_else(|| consts::NO_ERROR_MESSAGE.to_string(), ToString::to_string);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.response_code,
message: response_message.clone(),
reason: Some(response_message),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl ConnectorValidation for Jpmorgan {
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 Jpmorgan {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Jpmorgan {
fn get_headers(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let client_id = req.request.app_id.clone();
let client_secret = req.request.id.clone();
let creds = format!(
"{}:{}",
client_id.peek(),
client_secret.unwrap_or_default().peek()
);
let encoded_creds = common_utils::consts::BASE64_ENGINE.encode(creds);
let auth_string = format!("Basic {}", encoded_creds);
Ok(vec![
(
headers::CONTENT_TYPE.to_string(),
RefreshTokenType::get_content_type(self).to_string().into(),
),
(
headers::AUTHORIZATION.to_string(),
auth_string.into_masked(),
),
])
}
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!(
"{}/am/oauth2/alpha/access_token",
connectors
.jpmorgan
.secondary_base_url
.as_ref()
.ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?
))
}
fn get_request_body(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = jpmorgan::JpmorganAuthUpdateRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(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: jpmorgan::JpmorganAuthUpdateResponse = res
.response
.parse_struct("jpmorgan JpmorganAuthUpdateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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 Jpmorgan
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Jpmorgan {
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!("{}/payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount: MinorUnit = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = jpmorgan::JpmorganRouterData::from((amount, req));
let connector_req = jpmorgan::JpmorganPaymentsRequest::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: jpmorgan::JpmorganPaymentsResponse = res
.response
.parse_struct("Jpmorgan 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<Capture, PaymentsCaptureData, PaymentsResponseData> for Jpmorgan {
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 tid = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/payments/{}/captures",
self.base_url(connectors),
tid
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount: MinorUnit = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = jpmorgan::JpmorganRouterData::from((amount, req));
let connector_req = jpmorgan::JpmorganCaptureRequest::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: jpmorgan::JpmorganPaymentsResponse = res
.response
.parse_struct("Jpmorgan 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 Jpmorgan {
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 tid = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!("{}/payments/{}", self.base_url(connectors), tid))
}
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: jpmorgan::JpmorganPaymentsResponse = res
.response
.parse_struct("jpmorgan 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<Void, PaymentsCancelData, PaymentsResponseData> for Jpmorgan {
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 tid = req.request.connector_transaction_id.clone();
Ok(format!("{}/payments/{}", self.base_url(connectors), tid))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount: MinorUnit = utils::convert_amount(
self.amount_converter,
req.request.minor_amount.unwrap_or_default(),
req.request.currency.unwrap_or_default(),
)?;
let connector_router_data = jpmorgan::JpmorganRouterData::from((amount, req));
let connector_req = jpmorgan::JpmorganCancelRequest::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::Patch)
.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: jpmorgan::JpmorganCancelResponse = res
.response
.parse_struct("JpmrorganPaymentsVoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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 Jpmorgan {
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("Refunds".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 = jpmorgan::JpmorganRouterData::from((refund_amount, req));
let connector_req = jpmorgan::JpmorganRefundRequest::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 response: jpmorgan::JpmorganRefundResponse = res
.response
.parse_struct("JpmorganRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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 Jpmorgan {
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 tid = req.request.connector_transaction_id.clone();
Ok(format!("{}/refunds/{}", self.base_url(connectors), tid))
}
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: jpmorgan::JpmorganRefundSyncResponse = res
.response
.parse_struct("jpmorgan 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 Jpmorgan {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static JPMORGAN_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
];
let supported_card_network = vec![
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Visa,
];
let mut jpmorgan_supported_payment_methods = SupportedPaymentMethods::new();
jpmorgan_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
jpmorgan_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
jpmorgan_supported_payment_methods
});
static JPMORGAN_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Jpmorgan",
description:
"J.P. Morgan is a global financial services firm and investment bank, offering banking, asset management, and payment processing solutions",
connector_type: enums::PaymentConnectorCategory::BankAcquirer,
};
static JPMORGAN_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Jpmorgan {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&JPMORGAN_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*JPMORGAN_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&JPMORGAN_SUPPORTED_WEBHOOK_FLOWS)
}
}
| 6,595 | 2,090 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/novalnet.rs | .rs | pub mod transformers;
use core::str;
use std::{collections::HashSet, sync::LazyLock};
use base64::Engine;
use common_enums::enums;
use common_utils::{
crypto,
errors::CustomResult,
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},
},
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, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
disputes, errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask};
use transformers as novalnet;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, PaymentMethodDataType, PaymentsAuthorizeRequestData},
};
#[derive(Clone)]
pub struct Novalnet {
amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Novalnet {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Novalnet {}
impl api::PaymentSession for Novalnet {}
impl api::ConnectorAccessToken for Novalnet {}
impl api::MandateSetup for Novalnet {}
impl api::PaymentAuthorize for Novalnet {}
impl api::PaymentSync for Novalnet {}
impl api::PaymentCapture for Novalnet {}
impl api::PaymentVoid for Novalnet {}
impl api::Refund for Novalnet {}
impl api::RefundExecute for Novalnet {}
impl api::RefundSync for Novalnet {}
impl api::PaymentToken for Novalnet {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Novalnet
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Novalnet
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 Novalnet {
fn id(&self) -> &'static str {
"novalnet"
}
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.novalnet.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = novalnet::NovalnetAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let api_key: String = auth.payment_access_key.expose();
let encoded_api_key = common_utils::consts::BASE64_ENGINE.encode(api_key);
Ok(vec![(
headers::X_NN_ACCESS_KEY.to_string(),
encoded_api_key.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: novalnet::NovalnetErrorResponse = res
.response
.parse_struct("NovalnetErrorResponse")
.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,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl ConnectorValidation for Novalnet {
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())
}
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd: HashSet<PaymentMethodDataType> = HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::GooglePay,
PaymentMethodDataType::PaypalRedirect,
PaymentMethodDataType::ApplePay,
]);
utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl ConnectorRedirectResponse for Novalnet {
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 => Ok(enums::CallConnectorAction::Trigger),
_ => Ok(enums::CallConnectorAction::Avoid),
}
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Novalnet {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Novalnet {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Novalnet
{
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> {
let endpoint = self.base_url(connectors);
Ok(format!("{}/payment", endpoint))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = novalnet::NovalnetPaymentsRequest::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(&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: novalnet::NovalnetPaymentsResponse = res
.response
.parse_struct("Novalnet 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 Novalnet {
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);
match req.request.is_auto_capture()? {
true => Ok(format!("{}/payment", endpoint)),
false => Ok(format!("{}/authorize", endpoint)),
}
}
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 = novalnet::NovalnetRouterData::from((amount, req));
let connector_req = novalnet::NovalnetPaymentsRequest::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: novalnet::NovalnetPaymentsResponse = res
.response
.parse_struct("Novalnet 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 Novalnet {
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);
Ok(format!("{}/transaction/details", endpoint))
}
fn get_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = novalnet::NovalnetSyncRequest::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: novalnet::NovalnetPSyncResponse = res
.response
.parse_struct("novalnet 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 Novalnet {
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!("{}/transaction/capture", endpoint))
}
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 = novalnet::NovalnetRouterData::from((amount, req));
let connector_req = novalnet::NovalnetCaptureRequest::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: novalnet::NovalnetCaptureResponse = res
.response
.parse_struct("Novalnet 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 Novalnet {
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!("{}/transaction/refund", endpoint))
}
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 = novalnet::NovalnetRouterData::from((refund_amount, req));
let connector_req = novalnet::NovalnetRefundRequest::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: novalnet::NovalnetRefundResponse = res
.response
.parse_struct("novalnet 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 Novalnet {
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);
Ok(format!("{}/transaction/details", endpoint))
}
fn get_request_body(
&self,
req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = novalnet::NovalnetSyncRequest::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: novalnet::NovalnetRefundSyncResponse = res
.response
.parse_struct("novalnet 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<Void, PaymentsCancelData, PaymentsResponseData> for Novalnet {
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!("{}/transaction/cancel", endpoint))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = novalnet::NovalnetCancelRequest::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: novalnet::NovalnetCancelResponse = res
.response
.parse_struct("NovalnetPaymentsVoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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_object_from_body(
body: &[u8],
) -> CustomResult<novalnet::NovalnetWebhookNotificationResponse, errors::ConnectorError> {
let novalnet_webhook_notification_response = body
.parse_struct("NovalnetWebhookNotificationResponse")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(novalnet_webhook_notification_response)
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Novalnet {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::Sha256))
}
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 = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
hex::decode(notif_item.event.checksum)
.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 notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let (amount, currency) = match notif.transaction {
novalnet::NovalnetWebhookTransactionData::CaptureTransactionData(data) => {
(data.amount, data.currency)
}
novalnet::NovalnetWebhookTransactionData::CancelTransactionData(data) => {
(data.amount, data.currency)
}
novalnet::NovalnetWebhookTransactionData::RefundsTransactionData(data) => {
(data.amount, data.currency)
}
novalnet::NovalnetWebhookTransactionData::SyncTransactionData(data) => {
(data.amount, data.currency)
}
};
let amount = amount
.map(|amount| amount.to_string())
.unwrap_or("".to_string());
let currency = currency
.map(|amount| amount.to_string())
.unwrap_or("".to_string());
let secret_auth = String::from_utf8(connector_webhook_secrets.secret.to_vec())
.change_context(errors::ConnectorError::WebhookVerificationSecretInvalid)
.attach_printable("Could not convert webhook secret auth to UTF-8")?;
let reversed_secret_auth = novalnet::reverse_string(&secret_auth);
let message = format!(
"{}{}{}{}{}{}",
notif.event.tid,
notif.event.event_type,
notif.result.status,
amount,
currency,
reversed_secret_auth
);
Ok(message.into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let transaction_order_no = match notif.transaction {
novalnet::NovalnetWebhookTransactionData::CaptureTransactionData(data) => data.order_no,
novalnet::NovalnetWebhookTransactionData::CancelTransactionData(data) => data.order_no,
novalnet::NovalnetWebhookTransactionData::RefundsTransactionData(data) => data.order_no,
novalnet::NovalnetWebhookTransactionData::SyncTransactionData(data) => data.order_no,
};
if novalnet::is_refund_event(¬if.event.event_type) {
Ok(api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(notif.event.tid.to_string()),
))
} else {
match transaction_order_no {
Some(order_no) => Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::PaymentAttemptId(order_no),
)),
None => Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
notif.event.tid.to_string(),
),
)),
}
}
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
let optional_transaction_status = match notif.transaction {
novalnet::NovalnetWebhookTransactionData::CaptureTransactionData(data) => {
Some(data.status)
}
novalnet::NovalnetWebhookTransactionData::CancelTransactionData(data) => data.status,
novalnet::NovalnetWebhookTransactionData::RefundsTransactionData(data) => {
Some(data.status)
}
novalnet::NovalnetWebhookTransactionData::SyncTransactionData(data) => {
Some(data.status)
}
};
let transaction_status =
optional_transaction_status.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "transaction_status",
})?;
// NOTE: transaction_status will always be present for Webhooks
// But we are handling optional type here, since we are reusing TransactionData Struct from NovalnetPaymentsResponseTransactionData for Webhooks response too
// In NovalnetPaymentsResponseTransactionData, transaction_status is optional
let incoming_webhook_event =
novalnet::get_incoming_webhook_event(notif.event.event_type, transaction_status);
Ok(incoming_webhook_event)
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(notif))
}
fn get_dispute_details(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<disputes::DisputePayload, errors::ConnectorError> {
let notif: transformers::NovalnetWebhookNotificationResponse =
get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let (amount, currency, reason, reason_code) = match notif.transaction {
novalnet::NovalnetWebhookTransactionData::CaptureTransactionData(data) => {
(data.amount, data.currency, None, None)
}
novalnet::NovalnetWebhookTransactionData::CancelTransactionData(data) => {
(data.amount, data.currency, None, None)
}
novalnet::NovalnetWebhookTransactionData::RefundsTransactionData(data) => {
(data.amount, data.currency, None, None)
}
novalnet::NovalnetWebhookTransactionData::SyncTransactionData(data) => {
(data.amount, data.currency, data.reason, data.reason_code)
}
};
let dispute_status =
novalnet::get_novalnet_dispute_status(notif.event.event_type).to_string();
Ok(disputes::DisputePayload {
amount: novalnet::option_to_result(amount)?.to_string(),
currency: novalnet::option_to_result(currency)?,
dispute_stage: api_models::enums::DisputeStage::Dispute,
connector_dispute_id: notif.event.tid.to_string(),
connector_reason: reason,
connector_reason_code: reason_code,
challenge_required_by: None,
connector_status: dispute_status,
created_at: None,
updated_at: None,
})
}
}
static NOVALNET_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::UnionPay,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::Interac,
];
let mut novalnet_supported_payment_methods = SupportedPaymentMethods::new();
novalnet_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(),
}
}),
),
},
);
novalnet_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(),
}
}),
),
},
);
novalnet_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, // three-ds needed for googlepay
},
);
novalnet_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,
},
);
novalnet_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,
},
);
novalnet_supported_payment_methods
});
static NOVALNET_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Novalnet",
description: "Novalnet provides tailored, data-driven payment solutions that maximize acceptance, boost conversions, and deliver seamless customer experiences worldwide.",
connector_type: enums::PaymentConnectorCategory::PaymentGateway,
};
static NOVALNET_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 4] = [
enums::EventClass::Payments,
enums::EventClass::Refunds,
enums::EventClass::Disputes,
enums::EventClass::Mandates,
];
impl ConnectorSpecifications for Novalnet {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&NOVALNET_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*NOVALNET_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&NOVALNET_SUPPORTED_WEBHOOK_FLOWS)
}
}
| 8,693 | 2,091 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/trustpay.rs | .rs | pub mod transformers;
use base64::Engine;
use common_enums::{enums, PaymentAction};
use common_utils::{
crypto,
errors::{CustomResult, ReportSwitchExt},
ext_traits::ByteSliceExt,
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},
PreProcessing,
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData,
RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
consts,
disputes::DisputePayload,
errors,
events::connector_api_logs::ConnectorEvent,
types::{
PaymentsAuthorizeType, PaymentsPreProcessingType, PaymentsSyncType, RefreshTokenType,
RefundExecuteType, RefundSyncType, Response,
},
webhooks,
};
use masking::{Mask, PeekInterface};
use transformers as trustpay;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, ConnectorErrorType, PaymentsPreProcessingRequestData},
};
#[derive(Clone)]
pub struct Trustpay {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Trustpay {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Trustpay
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> {
match req.payment_method {
enums::PaymentMethod::BankRedirect | enums::PaymentMethod::BankTransfer => {
let token = req
.access_token
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![
(
headers::CONTENT_TYPE.to_string(),
"application/json".to_owned().into(),
),
(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", token.token.peek()).into_masked(),
),
])
}
_ => {
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 Trustpay {
fn id(&self) -> &'static str {
"trustpay"
}
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.trustpay.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = trustpay::TrustpayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::X_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: Result<
trustpay::TrustpayErrorResponse,
Report<common_utils::errors::ParsingError>,
> = res.response.parse_struct("trustpay ErrorResponse");
match response {
Ok(response_data) => {
event_builder.map(|i| i.set_error_response_body(&response_data));
router_env::logger::info!(connector_response=?response_data);
let error_list = response_data.errors.clone().unwrap_or_default();
let option_error_code_message =
utils::get_error_code_error_message_based_on_priority(
self.clone(),
error_list.into_iter().map(|errors| errors.into()).collect(),
);
let reason = response_data.errors.map(|errors| {
errors
.iter()
.map(|error| error.description.clone())
.collect::<Vec<String>>()
.join(" & ")
});
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 vary for the same code, so relying on code alone as it is unique
message: option_error_code_message
.map(|error_code_message| error_code_message.error_code)
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: reason
.or(response_data.description)
.or(response_data.payment_description),
attempt_status: None,
connector_transaction_id: response_data.instance_id,
network_advice_code: None,
network_decline_code: None,
network_error_message: 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, "trustpay")
}
}
}
}
impl ConnectorValidation for Trustpay {}
impl api::Payment for Trustpay {}
impl api::PaymentToken for Trustpay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Trustpay
{
// Not Implemented (R)
}
impl api::MandateSetup for Trustpay {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Trustpay
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Trustpay".to_string())
.into(),
)
}
}
impl api::PaymentVoid for Trustpay {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Trustpay {}
impl api::ConnectorAccessToken for Trustpay {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Trustpay {
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
connectors.trustpay.base_url_bank_redirects, "api/oauth2/token"
))
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_headers(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = trustpay::TrustpayAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_value = auth
.project_id
.zip(auth.secret_key)
.map(|(project_id, secret_key)| {
format!(
"Basic {}",
common_utils::consts::BASE64_ENGINE
.encode(format!("{}:{}", project_id, secret_key))
)
});
Ok(vec![
(
headers::CONTENT_TYPE.to_string(),
RefreshTokenType::get_content_type(self).to_string().into(),
),
(headers::AUTHORIZATION.to_string(), auth_value.into_masked()),
])
}
fn get_request_body(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = trustpay::TrustpayAuthUpdateRequest::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(RefreshTokenType::get_headers(self, req, connectors)?)
.url(&RefreshTokenType::get_url(self, req, connectors)?)
.set_body(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: trustpay::TrustpayAuthUpdateResponse = res
.response
.parse_struct("trustpay TrustpayAuthUpdateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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: trustpay::TrustpayAccessTokenErrorResponse = res
.response
.parse_struct("Trustpay AccessTokenErrorResponse")
.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.result_info.result_code.to_string(),
// message vary for the same code, so relying on code alone as it is unique
message: response.result_info.result_code.to_string(),
reason: response.result_info.additional_info,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl api::PaymentSync for Trustpay {}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Trustpay {
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 id = req.request.connector_transaction_id.clone();
match req.payment_method {
enums::PaymentMethod::BankRedirect | enums::PaymentMethod::BankTransfer => Ok(format!(
"{}{}/{}",
connectors.trustpay.base_url_bank_redirects,
"api/Payments/Payment",
id.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?
)),
_ => Ok(format!(
"{}{}/{}",
self.base_url(connectors),
"api/v1/instance",
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: trustpay::TrustpayPaymentsResponse = res
.response
.parse_struct("trustpay 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 api::PaymentCapture for Trustpay {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Trustpay {}
impl api::PaymentsPreProcessing for Trustpay {}
impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
for Trustpay
{
fn get_headers(
&self,
req: &PaymentsPreProcessingRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::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_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "api/v1/intent"))
}
fn get_request_body(
&self,
req: &PaymentsPreProcessingRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let req_currency = req.request.get_currency()?;
let req_amount = req.request.get_minor_amount()?;
let amount = utils::convert_amount(self.amount_converter, req_amount, req_currency)?;
let connector_router_data = trustpay::TrustpayRouterData::try_from((amount, req))?;
let connector_req =
trustpay::TrustpayCreateIntentRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let req = Some(
RequestBuilder::new()
.method(Method::Post)
.attach_default_headers()
.headers(PaymentsPreProcessingType::get_headers(
self, req, connectors,
)?)
.url(&PaymentsPreProcessingType::get_url(self, req, connectors)?)
.set_body(PaymentsPreProcessingType::get_request_body(
self, req, connectors,
)?)
.build(),
);
Ok(req)
}
fn handle_response(
&self,
data: &PaymentsPreProcessingRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: trustpay::TrustpayCreateIntentResponse = res
.response
.parse_struct("TrustpayCreateIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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 Trustpay {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Trustpay {}
impl api::PaymentAuthorize for Trustpay {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Trustpay {
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> {
match req.payment_method {
enums::PaymentMethod::BankRedirect | enums::PaymentMethod::BankTransfer => Ok(format!(
"{}{}",
connectors.trustpay.base_url_bank_redirects, "api/Payments/Payment"
)),
_ => Ok(format!(
"{}{}",
self.base_url(connectors),
"api/v1/purchase"
)),
}
}
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 = trustpay::TrustpayRouterData::try_from((amount, req))?;
let connector_req = trustpay::TrustpayPaymentsRequest::try_from(&connector_router_data)?;
match req.payment_method {
enums::PaymentMethod::BankRedirect | enums::PaymentMethod::BankTransfer => {
Ok(RequestContent::Json(Box::new(connector_req)))
}
_ => 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(&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: trustpay::TrustpayPaymentsResponse = res
.response
.parse_struct("trustpay 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 Trustpay {}
impl api::RefundExecute for Trustpay {}
impl api::RefundSync for Trustpay {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Trustpay {
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> {
match req.payment_method {
enums::PaymentMethod::BankRedirect | enums::PaymentMethod::BankTransfer => Ok(format!(
"{}{}{}{}",
connectors.trustpay.base_url_bank_redirects,
"api/Payments/Payment/",
req.request.connector_transaction_id,
"/Refund"
)),
_ => Ok(format!("{}{}", self.base_url(connectors), "api/v1/Refund")),
}
}
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 = trustpay::TrustpayRouterData::try_from((amount, req))?;
let connector_req = trustpay::TrustpayRefundRequest::try_from(&connector_router_data)?;
match req.payment_method {
enums::PaymentMethod::BankRedirect | enums::PaymentMethod::BankTransfer => {
Ok(RequestContent::Json(Box::new(connector_req)))
}
_ => 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(&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: trustpay::RefundResponse = res
.response
.parse_struct("trustpay 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 Trustpay {
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 id = req
.request
.connector_refund_id
.to_owned()
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?;
match req.payment_method {
enums::PaymentMethod::BankRedirect | enums::PaymentMethod::BankTransfer => Ok(format!(
"{}{}/{}",
connectors.trustpay.base_url_bank_redirects, "api/Payments/Payment", id
)),
_ => Ok(format!(
"{}{}/{}",
self.base_url(connectors),
"api/v1/instance",
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: trustpay::RefundResponse = res
.response
.parse_struct("trustpay 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 Trustpay {
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let details: trustpay::TrustpayWebhookResponse = request
.body
.parse_struct("TrustpayWebhookResponse")
.switch()?;
match details.payment_information.credit_debit_indicator {
trustpay::CreditDebitIndicator::Crdt => {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::PaymentAttemptId(
details.payment_information.references.merchant_reference,
),
))
}
trustpay::CreditDebitIndicator::Dbit => {
if details.payment_information.status == trustpay::WebhookStatus::Chargebacked {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::PaymentAttemptId(
details.payment_information.references.merchant_reference,
),
))
} else {
Ok(api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::RefundId(
details.payment_information.references.merchant_reference,
),
))
}
}
}
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let response: trustpay::TrustpayWebhookResponse = request
.body
.parse_struct("TrustpayWebhookResponse")
.switch()?;
match (
response.payment_information.credit_debit_indicator,
response.payment_information.status,
) {
(trustpay::CreditDebitIndicator::Crdt, trustpay::WebhookStatus::Paid) => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
(trustpay::CreditDebitIndicator::Crdt, trustpay::WebhookStatus::Rejected) => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure)
}
(trustpay::CreditDebitIndicator::Dbit, trustpay::WebhookStatus::Paid) => {
Ok(api_models::webhooks::IncomingWebhookEvent::RefundSuccess)
}
(trustpay::CreditDebitIndicator::Dbit, trustpay::WebhookStatus::Refunded) => {
Ok(api_models::webhooks::IncomingWebhookEvent::RefundSuccess)
}
(trustpay::CreditDebitIndicator::Dbit, trustpay::WebhookStatus::Rejected) => {
Ok(api_models::webhooks::IncomingWebhookEvent::RefundFailure)
}
(trustpay::CreditDebitIndicator::Dbit, trustpay::WebhookStatus::Chargebacked) => {
Ok(api_models::webhooks::IncomingWebhookEvent::DisputeLost)
}
(
trustpay::CreditDebitIndicator::Dbit | trustpay::CreditDebitIndicator::Crdt,
trustpay::WebhookStatus::Unknown,
) => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported),
(trustpay::CreditDebitIndicator::Crdt, trustpay::WebhookStatus::Refunded) => {
Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
(trustpay::CreditDebitIndicator::Crdt, trustpay::WebhookStatus::Chargebacked) => {
Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
}
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let details: trustpay::TrustpayWebhookResponse = request
.body
.parse_struct("TrustpayWebhookResponse")
.switch()?;
Ok(Box::new(details.payment_information))
}
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 response: trustpay::TrustpayWebhookResponse = request
.body
.parse_struct("TrustpayWebhookResponse")
.switch()?;
hex::decode(response.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> {
let trustpay_response: trustpay::TrustpayWebhookResponse = request
.body
.parse_struct("TrustpayWebhookResponse")
.switch()?;
let response: serde_json::Value = request.body.parse_struct("Webhook Value").switch()?;
let values = utils::collect_and_sort_values_by_removing_signature(
&response,
&trustpay_response.signature,
);
let payload = values.join("/");
Ok(payload.into_bytes())
}
fn get_dispute_details(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<DisputePayload, errors::ConnectorError> {
let trustpay_response: trustpay::TrustpayWebhookResponse = request
.body
.parse_struct("TrustpayWebhookResponse")
.switch()?;
let payment_info = trustpay_response.payment_information;
let reason = payment_info.status_reason_information.unwrap_or_default();
let connector_dispute_id = payment_info
.references
.payment_id
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(DisputePayload {
amount: payment_info.amount.amount.to_string(),
currency: payment_info.amount.currency,
dispute_stage: api_models::enums::DisputeStage::Dispute,
connector_dispute_id,
connector_reason: reason.reason.reject_reason,
connector_reason_code: reason.reason.code,
challenge_required_by: None,
connector_status: payment_info.status.to_string(),
created_at: None,
updated_at: None,
})
}
}
impl ConnectorRedirectResponse for Trustpay {
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)
}
}
}
}
impl utils::ConnectorErrorTypeMapping for Trustpay {
fn get_connector_error_type(
&self,
error_code: String,
error_message: String,
) -> ConnectorErrorType {
match (error_code.as_str(), error_message.as_str()) {
// 2xx card api error codes and messages mapping
("100.100.600", "Empty CVV for VISA, MASTER not allowed") => ConnectorErrorType::UserError,
("100.350.100", "Referenced session is rejected (no action possible)") => ConnectorErrorType::TechnicalError,
("100.380.401", "User authentication failed") => ConnectorErrorType::UserError,
("100.380.501", "Risk management transaction timeout") => ConnectorErrorType::TechnicalError,
("100.390.103", "PARes validation failed - problem with signature") => ConnectorErrorType::TechnicalError,
("100.390.111", "Communication error to VISA/Mastercard Directory Server") => ConnectorErrorType::TechnicalError,
("100.390.112", "Technical error in 3D system") => ConnectorErrorType::TechnicalError,
("100.390.115", "Authentication failed due to invalid message format") => ConnectorErrorType::TechnicalError,
("100.390.118", "Authentication failed due to suspected fraud") => ConnectorErrorType::UserError,
("100.400.304", "Invalid input data") => ConnectorErrorType::UserError,
("200.300.404", "Invalid or missing parameter") => ConnectorErrorType::UserError,
("300.100.100", "Transaction declined (additional customer authentication required)") => ConnectorErrorType::UserError,
("400.001.301", "Card not enrolled in 3DS") => ConnectorErrorType::UserError,
("400.001.600", "Authentication error") => ConnectorErrorType::UserError,
("400.001.601", "Transaction declined (auth. declined)") => ConnectorErrorType::UserError,
("400.001.602", "Invalid transaction") => ConnectorErrorType::UserError,
("400.001.603", "Invalid transaction") => ConnectorErrorType::UserError,
("700.400.200", "Cannot refund (refund volume exceeded or tx reversed or invalid workflow)") => ConnectorErrorType::BusinessError,
("700.500.001", "Referenced session contains too many transactions") => ConnectorErrorType::TechnicalError,
("700.500.003", "Test accounts not allowed in production") => ConnectorErrorType::UserError,
("800.100.151", "Transaction declined (invalid card)") => ConnectorErrorType::UserError,
("800.100.152", "Transaction declined by authorization system") => ConnectorErrorType::UserError,
("800.100.153", "Transaction declined (invalid CVV)") => ConnectorErrorType::UserError,
("800.100.155", "Transaction declined (amount exceeds credit)") => ConnectorErrorType::UserError,
("800.100.157", "Transaction declined (wrong expiry date)") => ConnectorErrorType::UserError,
("800.100.162", "Transaction declined (limit exceeded)") => ConnectorErrorType::BusinessError,
("800.100.163", "Transaction declined (maximum transaction frequency exceeded)") => ConnectorErrorType::BusinessError,
("800.100.168", "Transaction declined (restricted card)") => ConnectorErrorType::UserError,
("800.100.170", "Transaction declined (transaction not permitted)") => ConnectorErrorType::UserError,
("800.100.172", "Transaction declined (account blocked)") => ConnectorErrorType::BusinessError,
("800.100.190", "Transaction declined (invalid configuration data)") => ConnectorErrorType::BusinessError,
("800.120.100", "Rejected by throttling") => ConnectorErrorType::TechnicalError,
("800.300.401", "Bin blacklisted") => ConnectorErrorType::BusinessError,
("800.700.100", "Transaction for the same session is currently being processed, please try again later") => ConnectorErrorType::TechnicalError,
("900.100.300", "Timeout, uncertain result") => ConnectorErrorType::TechnicalError,
// 4xx error codes for cards api are unique and messages vary, so we are relying only on error code to decide an error type
("4" | "5" | "6" | "7" | "8" | "9" | "10" | "11" | "12" | "13" | "14" | "15" | "16" | "17" | "18" | "19" | "26" | "34" | "39" | "48" | "52" | "85" | "86", _) => ConnectorErrorType::UserError,
("21" | "22" | "23" | "30" | "31" | "32" | "35" | "37" | "40" | "41" | "45" | "46" | "49" | "50" | "56" | "60" | "67" | "81" | "82" | "83" | "84" | "87", _) => ConnectorErrorType::BusinessError,
("59", _) => ConnectorErrorType::TechnicalError,
("1", _) => ConnectorErrorType::UnknownError,
// Error codes for bank redirects api are unique and messages vary, so we are relying only on error code to decide an error type
("1112008" | "1132000" | "1152000", _) => ConnectorErrorType::UserError,
("1112009" | "1122006" | "1132001" | "1132002" | "1132003" | "1132004" | "1132005" | "1132006" | "1132008" | "1132009" | "1132010" | "1132011" | "1132012" | "1132013" | "1133000" | "1133001" | "1133002" | "1133003" | "1133004", _) => ConnectorErrorType::BusinessError,
("1132014", _) => ConnectorErrorType::TechnicalError,
("1132007", _) => ConnectorErrorType::UnknownError,
_ => ConnectorErrorType::UnknownError,
}
}
}
impl ConnectorSpecifications for Trustpay {}
| 9,417 | 2,092 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/paybox.rs | .rs | pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use common_enums::{enums, CallConnectorAction, PaymentAction};
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::{
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,
},
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::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::{ExposeInterface, Mask};
use transformers as paybox;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{convert_amount, is_mandate_supported, PaymentMethodDataType, RouterData as _},
};
#[derive(Clone)]
pub struct Paybox {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Paybox {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Paybox {}
impl api::PaymentSession for Paybox {}
impl api::ConnectorAccessToken for Paybox {}
impl api::MandateSetup for Paybox {}
impl api::PaymentAuthorize for Paybox {}
impl api::PaymentSync for Paybox {}
impl api::PaymentCapture for Paybox {}
impl api::PaymentVoid for Paybox {}
impl api::Refund for Paybox {}
impl api::RefundExecute for Paybox {}
impl api::RefundSync for Paybox {}
impl api::PaymentToken for Paybox {}
impl api::PaymentsCompleteAuthorize for Paybox {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Paybox {
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<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Paybox
{
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paybox
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 Paybox {
fn id(&self) -> &'static str {
"paybox"
}
fn common_get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.paybox.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = paybox::PayboxAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.cle.expose().into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: paybox::PayboxErrorResponse = res
.response
.parse_struct("PayboxErrorResponse")
.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,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl ConnectorValidation for Paybox {
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<Session, PaymentsSessionData, PaymentsResponseData> for Paybox {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Paybox {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Paybox {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Paybox {
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() {
Ok(format!(
"{}cgi/RemoteMPI.cgi",
connectors.paybox.secondary_base_url
))
} else {
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_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = paybox::PayboxRouterData::from((amount, req));
let connector_req = paybox::PayboxPaymentsRequest::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()
.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: paybox::PayboxResponse =
paybox::parse_paybox_response(res.response, data.is_three_ds())?;
event_builder.map(|i| i.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 Paybox {
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_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = paybox::PayboxPSyncRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn get_url(
&self,
_req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
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,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: paybox::PayboxSyncResponse =
paybox::parse_url_encoded_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 Paybox {
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 = paybox::PayboxRouterData::from((amount, req));
let connector_req = paybox::PayboxCaptureRequest::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(&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: paybox::PayboxCaptureResponse =
paybox::parse_url_encoded_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<Execute, RefundsData, RefundsResponseData> for Paybox {
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 refund_amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = paybox::PayboxRouterData::from((refund_amount, req));
let connector_req = paybox::PayboxRefundRequest::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()
.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: paybox::TransactionResponse =
paybox::parse_url_encoded_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 Paybox {
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 = paybox::PayboxRsyncRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(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()
.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: paybox::PayboxSyncResponse =
paybox::parse_url_encoded_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 IncomingWebhook for Paybox {
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<'_>,
) -> 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))
}
}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Paybox
{
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 = paybox::PayboxRouterData::from((amount, req));
let connector_req = paybox::PaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(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,
)?)
.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: paybox::TransactionResponse =
paybox::parse_url_encoded_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 ConnectorRedirectResponse for Paybox {
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)
}
}
}
}
static PAYBOX_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 paybox_supported_payment_methods = SupportedPaymentMethods::new();
paybox_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(),
}
}),
),
},
);
paybox_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(),
}
}),
),
},
);
paybox_supported_payment_methods
});
static PAYBOX_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Paybox",
description:
"Paybox is a payment gateway that enables businesses to process online transactions securely ",
connector_type: enums::PaymentConnectorCategory::PaymentGateway,
};
static PAYBOX_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Paybox {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&PAYBOX_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*PAYBOX_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&PAYBOX_SUPPORTED_WEBHOOK_FLOWS)
}
}
| 5,773 | 2,093 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/volt.rs | .rs | pub mod transformers;
use api_models::webhooks::IncomingWebhookEvent;
use common_enums::enums;
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
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,
RefreshTokenRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, PaymentsAuthorizeType, RefreshTokenType, Response},
webhooks,
};
use lazy_static::lazy_static;
use masking::{ExposeInterface, Mask, PeekInterface};
use transformers as volt;
use self::volt::{webhook_headers, VoltWebhookBodyEventType};
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self},
};
#[derive(Clone)]
pub struct Volt {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Volt {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Volt {}
impl api::PaymentSession for Volt {}
impl api::ConnectorAccessToken for Volt {}
impl api::MandateSetup for Volt {}
impl api::PaymentAuthorize for Volt {}
impl api::PaymentSync for Volt {}
impl api::PaymentCapture for Volt {}
impl api::PaymentVoid for Volt {}
impl api::Refund for Volt {}
impl api::RefundExecute for Volt {}
impl api::RefundSync for Volt {}
impl api::PaymentToken for Volt {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Volt
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Volt
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 access_token = req
.access_token
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_header = (
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", access_token.token.peek()).into_masked(),
);
header.push(auth_header);
Ok(header)
}
}
impl ConnectorCommon for Volt {
fn id(&self) -> &'static str {
"volt"
}
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.volt.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = volt::VoltAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.username.expose().into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: volt::VoltErrorResponse = res
.response
.parse_struct("VoltErrorResponse")
.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.exception.error_list {
Some(error_list) => error_list
.iter()
.map(|error| error.message.clone())
.collect::<Vec<String>>()
.join(" & "),
None => response.exception.message.clone(),
};
Ok(ErrorResponse {
status_code: res.status_code,
code: response.exception.message.to_string(),
message: response.exception.message.clone(),
reason: Some(reason),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl ConnectorValidation for Volt {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Volt {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Volt {
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}oauth", 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![(
headers::CONTENT_TYPE.to_string(),
RefreshTokenType::get_content_type(self).to_string().into(),
)])
}
fn get_request_body(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = volt::VoltAuthUpdateRequest::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(RefreshTokenType::get_headers(self, req, connectors)?)
.url(&RefreshTokenType::get_url(self, req, connectors)?)
.set_body(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: volt::VoltAuthUpdateResponse = res
.response
.parse_struct("Volt VoltAuthUpdateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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> {
// auth error have different structure than common error
let response: volt::VoltAuthErrorResponse = res
.response
.parse_struct("VoltAuthErrorResponse")
.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: response.message.clone(),
reason: Some(response.message),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Volt {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Volt".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Volt {
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!("{}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 = volt::VoltRouterData::from((amount, req));
let connector_req = volt::VoltPaymentsRequest::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: volt::VoltPaymentsResponse = res
.response
.parse_struct("Volt 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 Volt {
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!(
"{}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: volt::VoltPaymentsResponseData = res
.response
.parse_struct("volt 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 Volt {
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: volt::VoltPaymentsResponse = res
.response
.parse_struct("Volt 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 Volt {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Volt {
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!(
"{}payments/{connector_payment_id}/request-refund",
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 = volt::VoltRouterData::from((amount, req));
let connector_req = volt::VoltRefundRequest::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: volt::RefundResponse = res
.response
.parse_struct("volt 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 Volt {
//Volt does not support Refund Sync
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Volt {
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(webhook_headers::X_VOLT_SIGNED, request.headers)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
hex::decode(signature)
.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 x_volt_timed =
utils::get_header_key_value(webhook_headers::X_VOLT_TIMED, request.headers)?;
let user_agent = utils::get_header_key_value(webhook_headers::USER_AGENT, request.headers)?;
let version = user_agent
.split('/')
.next_back()
.ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)?;
Ok(format!(
"{}|{}|{}",
String::from_utf8_lossy(request.body),
x_volt_timed,
version
)
.into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let parsed_webhook_response = request
.body
.parse_struct::<volt::WebhookResponse>("VoltRefundWebhookBodyReference")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
match parsed_webhook_response {
volt::WebhookResponse::Payment(payment_response) => {
let reference = match payment_response.merchant_internal_reference {
Some(merchant_internal_reference) => {
api_models::payments::PaymentIdType::PaymentAttemptId(
merchant_internal_reference,
)
}
None => api_models::payments::PaymentIdType::ConnectorTransactionId(
payment_response.payment,
),
};
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
reference,
))
}
volt::WebhookResponse::Refund(refund_response) => {
let refund_reference = match refund_response.external_reference {
Some(external_reference) => {
api_models::webhooks::RefundIdType::RefundId(external_reference)
}
None => api_models::webhooks::RefundIdType::ConnectorRefundId(
refund_response.refund,
),
};
Ok(api_models::webhooks::ObjectReferenceId::RefundId(
refund_reference,
))
}
}
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
if request.body.is_empty() {
Ok(IncomingWebhookEvent::EndpointVerification)
} else {
let payload: VoltWebhookBodyEventType = request
.body
.parse_struct("VoltWebhookBodyEventType")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(IncomingWebhookEvent::from(payload))
}
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let details: volt::VoltWebhookObjectResource = request
.body
.parse_struct("VoltWebhookObjectResource")
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(details))
}
}
lazy_static! {
static ref VOLT_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
let supported_capture_methods = vec![enums::CaptureMethod::Automatic];
let mut volt_supported_payment_methods = SupportedPaymentMethods::new();
volt_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::OpenBankingUk,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
volt_supported_payment_methods
};
static ref VOLT_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "VOLT",
description:
"Volt is a payment gateway operating in China, specializing in facilitating local bank transfers",
connector_type: enums::PaymentConnectorCategory::PaymentGateway,
};
static ref VOLT_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
}
impl ConnectorSpecifications for Volt {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*VOLT_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*VOLT_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*VOLT_SUPPORTED_WEBHOOK_FLOWS)
}
}
| 5,740 | 2,094 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/noon.rs | .rs | pub mod transformers;
use api_models::webhooks::{ConnectorWebhookSecrets, IncomingWebhookEvent, ObjectReferenceId};
use base64::Engine;
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::{Report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
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},
},
router_request_types::{
AccessTokenRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData},
types::{
MandateRevokeRouterData, 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::{
MandateRevokeType, PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType,
PaymentsVoidType, RefundExecuteType, RefundSyncType, Response,
},
webhooks,
};
use masking::{Mask, PeekInterface};
use router_env::logger;
use transformers as noon;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self as connector_utils, PaymentMethodDataType},
};
#[derive(Clone)]
pub struct Noon {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Noon {
pub const fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl api::Payment for Noon {}
impl api::PaymentSession for Noon {}
impl api::ConnectorAccessToken for Noon {}
impl api::MandateSetup for Noon {}
impl api::PaymentAuthorize for Noon {}
impl api::PaymentSync for Noon {}
impl api::PaymentCapture for Noon {}
impl api::PaymentVoid for Noon {}
impl api::Refund for Noon {}
impl api::RefundExecute for Noon {}
impl api::RefundSync for Noon {}
impl api::PaymentToken for Noon {}
impl api::ConnectorMandateRevoke for Noon {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Noon
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Noon
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 = get_auth_header(&req.connector_auth_type, connectors, req.test_mode)?;
header.append(&mut api_key);
Ok(header)
}
}
fn get_auth_header(
auth_type: &ConnectorAuthType,
connectors: &Connectors,
test_mode: Option<bool>,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = noon::NoonAuthType::try_from(auth_type)?;
let encoded_api_key = auth
.business_identifier
.zip(auth.application_identifier)
.zip(auth.api_key)
.map(|((business_identifier, application_identifier), api_key)| {
common_utils::consts::BASE64_ENGINE.encode(format!(
"{}.{}:{}",
business_identifier, application_identifier, api_key
))
});
let key_mode = test_mode.map_or(connectors.noon.key_mode.clone(), |is_test_mode| {
if is_test_mode {
"Test".to_string()
} else {
"Live".to_string()
}
});
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Key_{} {}", key_mode, encoded_api_key.peek()).into_masked(),
)])
}
impl ConnectorCommon for Noon {
fn id(&self) -> &'static str {
"noon"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.noon.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<noon::NoonErrorResponse, Report<common_utils::errors::ParsingError>> =
res.response.parse_struct("NoonErrorResponse");
match response {
Ok(noon_error_response) => {
event_builder.map(|i| i.set_error_response_body(&noon_error_response));
router_env::logger::info!(connector_response=?noon_error_response);
// Adding in case of timeouts, if psync gives 4xx with this code, fail the payment
let attempt_status = if noon_error_response.result_code == 19001 {
Some(enums::AttemptStatus::Failure)
} else {
None
};
Ok(ErrorResponse {
status_code: res.status_code,
code: noon_error_response.result_code.to_string(),
message: noon_error_response.class_description,
reason: Some(noon_error_response.message),
attempt_status,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
Err(error_message) => {
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_message);
connector_utils::handle_json_response_deserialization_failure(res, "noon")
}
}
}
}
impl ConnectorValidation for Noon {
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(
connector_utils::construct_not_implemented_error_report(capture_method, self.id()),
),
}
}
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,
]);
connector_utils::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> {
// since we can make psync call with our reference_id, having connector_transaction_id is not an mandatory criteria
Ok(())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Noon {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Noon {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Noon {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Noon".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Noon {
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/v1/order", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let mandate_details =
connector_utils::get_mandate_details(req.request.setup_mandate_details.clone())?;
let mandate_amount = mandate_details
.map(|mandate| {
connector_utils::convert_amount(
self.amount_converter,
mandate.amount,
mandate.currency,
)
})
.transpose()?;
let connector_router_data = noon::NoonRouterData::from((amount, req, mandate_amount));
let connector_req = noon::NoonPaymentsRequest::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: noon::NoonPaymentsResponse = res
.response
.parse_struct("Noon 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 Noon {
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!(
"{}payment/v1/order/getbyreference/{}",
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(&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: noon::NoonPaymentsResponse = res
.response
.parse_struct("noon 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 Noon {
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!("{}payment/v1/order", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = noon::NoonRouterData::from((amount, req, None));
let connector_req = noon::NoonPaymentsActionRequest::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: noon::NoonPaymentsResponse = res
.response
.parse_struct("Noon 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 Noon {
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!("{}payment/v1/order", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = noon::NoonPaymentsCancelRequest::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: noon::NoonPaymentsResponse = res
.response
.parse_struct("Noon 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<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>
for Noon
{
fn get_headers(
&self,
req: &MandateRevokeRouterData,
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: &MandateRevokeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}payment/v1/order", self.base_url(connectors)))
}
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 = noon::NoonRevokeMandateRequest::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: noon::NoonRevokeMandateResponse = res
.response
.parse_struct("Noon NoonRevokeMandateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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 Noon {
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!("{}payment/v1/order", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = noon::NoonRouterData::from((refund_amount, req, None));
let connector_req = noon::NoonPaymentsActionRequest::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: noon::RefundResponse = res
.response
.parse_struct("noon 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 Noon {
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!(
"{}payment/v1/order/getbyreference/{}",
self.base_url(connectors),
req.connector_request_reference_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: noon::RefundSyncResponse = res
.response
.parse_struct("noon 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)
}
}
impl api::ConnectorRedirectResponse for Noon {
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)
}
}
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Noon {
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: &ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let webhook_body: noon::NoonWebhookSignature = request
.body
.parse_struct("NoonWebhookSignature")
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
let signature = webhook_body.signature;
common_utils::consts::BASE64_ENGINE
.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: &ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let webhook_body: noon::NoonWebhookBody = request
.body
.parse_struct("NoonWebhookBody")
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
let message = format!(
"{},{},{},{},{}",
webhook_body.order_id,
webhook_body.order_status,
webhook_body.event_id,
webhook_body.event_type,
webhook_body.time_stamp,
);
Ok(message.into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
let details: noon::NoonWebhookOrderId = request
.body
.parse_struct("NoonWebhookOrderId")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
details.order_id.to_string(),
),
))
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let details: noon::NoonWebhookEvent = request
.body
.parse_struct("NoonWebhookEvent")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(match &details.event_type {
noon::NoonWebhookEventTypes::Sale | noon::NoonWebhookEventTypes::Capture => {
match &details.order_status {
noon::NoonPaymentStatus::Captured => IncomingWebhookEvent::PaymentIntentSuccess,
_ => Err(errors::ConnectorError::WebhookEventTypeNotFound)?,
}
}
noon::NoonWebhookEventTypes::Fail => IncomingWebhookEvent::PaymentIntentFailure,
noon::NoonWebhookEventTypes::Authorize
| noon::NoonWebhookEventTypes::Authenticate
| noon::NoonWebhookEventTypes::Refund
| noon::NoonWebhookEventTypes::Unknown => IncomingWebhookEvent::EventNotSupported,
})
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let resource: noon::NoonWebhookObject = request
.body
.parse_struct("NoonWebhookObject")
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(noon::NoonPaymentsResponse::from(resource)))
}
}
impl ConnectorSpecifications for Noon {}
| 7,035 | 2,095 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/rapyd.rs | .rs | pub mod transformers;
use api_models::webhooks::IncomingWebhookEvent;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE_URL_SAFE,
crypto, date_time,
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt, Encode, StringExt},
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, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
disputes::DisputePayload,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use lazy_static::lazy_static;
use masking::{ExposeInterface, Mask, PeekInterface, Secret};
use rand::distributions::{Alphanumeric, DistString};
use ring::hmac;
use router_env::logger;
use transformers as rapyd;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, convert_amount, get_header_key_value},
};
#[derive(Clone)]
pub struct Rapyd {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Rapyd {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl Rapyd {
pub fn generate_signature(
&self,
auth: &rapyd::RapydAuthType,
http_method: &str,
url_path: &str,
body: &str,
timestamp: i64,
salt: &str,
) -> CustomResult<String, errors::ConnectorError> {
let rapyd::RapydAuthType {
access_key,
secret_key,
} = auth;
let to_sign = format!(
"{http_method}{url_path}{salt}{timestamp}{}{}{body}",
access_key.peek(),
secret_key.peek()
);
let key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.peek().as_bytes());
let tag = hmac::sign(&key, to_sign.as_bytes());
let hmac_sign = hex::encode(tag);
let signature_value = BASE64_ENGINE_URL_SAFE.encode(hmac_sign);
Ok(signature_value)
}
}
impl ConnectorCommon for Rapyd {
fn id(&self) -> &'static str {
"rapyd"
}
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.rapyd.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: Result<
rapyd::RapydPaymentsResponse,
Report<common_utils::errors::ParsingError>,
> = res.response.parse_struct("Rapyd ErrorResponse");
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.status.error_code,
message: response_data.status.status.unwrap_or_default(),
reason: response_data.status.message,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: 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, "rapyd")
}
}
}
}
impl ConnectorValidation for Rapyd {}
impl api::ConnectorAccessToken for Rapyd {}
impl api::PaymentToken for Rapyd {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Rapyd
{
// Not Implemented (R)
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Rapyd {}
impl api::PaymentAuthorize for Rapyd {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Rapyd {
fn get_headers(
&self,
_req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![(
headers::CONTENT_TYPE.to_string(),
types::PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
)])
}
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/payments", 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 = rapyd::RapydRouterData::from((amount, req));
let connector_req = rapyd::RapydPaymentsRequest::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> {
let timestamp = date_time::now_unix_timestamp();
let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12);
let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?;
let body = types::PaymentsAuthorizeType::get_request_body(self, req, connectors)?;
let req_body = body.get_inner_value().expose();
let signature =
self.generate_signature(&auth, "post", "/v1/payments", &req_body, timestamp, &salt)?;
let headers = vec![
("access_key".to_string(), auth.access_key.into_masked()),
("salt".to_string(), salt.into_masked()),
("timestamp".to_string(), timestamp.to_string().into()),
("signature".to_string(), signature.into_masked()),
];
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.headers(headers)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, 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: rapyd::RapydPaymentsResponse = res
.response
.parse_struct("Rapyd 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)
}
}
impl api::Payment for Rapyd {}
impl api::MandateSetup for Rapyd {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Rapyd {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Rapyd".to_string())
.into(),
)
}
}
impl api::PaymentVoid for Rapyd {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Rapyd {
fn get_headers(
&self,
_req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![(
headers::CONTENT_TYPE.to_string(),
types::PaymentsVoidType::get_content_type(self)
.to_string()
.into(),
)])
}
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!(
"{}/v1/payments/{}",
self.base_url(connectors),
req.request.connector_transaction_id
))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let timestamp = date_time::now_unix_timestamp();
let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12);
let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?;
let url_path = format!("/v1/payments/{}", req.request.connector_transaction_id);
let signature =
self.generate_signature(&auth, "delete", &url_path, "", timestamp, &salt)?;
let headers = vec![
("access_key".to_string(), auth.access_key.into_masked()),
("salt".to_string(), salt.into_masked()),
("timestamp".to_string(), timestamp.to_string().into()),
("signature".to_string(), signature.into_masked()),
];
let request = RequestBuilder::new()
.method(Method::Delete)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.headers(headers)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: rapyd::RapydPaymentsResponse = res
.response
.parse_struct("Rapyd 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)
}
}
impl api::PaymentSync for Rapyd {}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Rapyd {
fn get_headers(
&self,
_req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![(
headers::CONTENT_TYPE.to_string(),
types::PaymentsSyncType::get_content_type(self)
.to_string()
.into(),
)])
}
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 id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/v1/payments/{}",
self.base_url(connectors),
id.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let timestamp = date_time::now_unix_timestamp();
let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12);
let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?;
let response_id = req.request.connector_transaction_id.clone();
let url_path = format!(
"/v1/payments/{}",
response_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?
);
let signature = self.generate_signature(&auth, "get", &url_path, "", timestamp, &salt)?;
let headers = vec![
("access_key".to_string(), auth.access_key.into_masked()),
("salt".to_string(), salt.into_masked()),
("timestamp".to_string(), timestamp.to_string().into()),
("signature".to_string(), signature.into_masked()),
];
let request = RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.headers(headers)
.build();
Ok(Some(request))
}
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: rapyd::RapydPaymentsResponse = res
.response
.parse_struct("Rapyd 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)
}
}
impl api::PaymentCapture for Rapyd {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Rapyd {
fn get_headers(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![(
headers::CONTENT_TYPE.to_string(),
types::PaymentsCaptureType::get_content_type(self)
.to_string()
.into(),
)])
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
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 = rapyd::RapydRouterData::from((amount, req));
let connector_req = rapyd::CaptureRequest::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 timestamp = date_time::now_unix_timestamp();
let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12);
let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?;
let url_path = format!(
"/v1/payments/{}/capture",
req.request.connector_transaction_id
);
let body = types::PaymentsCaptureType::get_request_body(self, req, connectors)?;
let req_body = body.get_inner_value().expose();
let signature =
self.generate_signature(&auth, "post", &url_path, &req_body, timestamp, &salt)?;
let headers = vec![
("access_key".to_string(), auth.access_key.into_masked()),
("salt".to_string(), salt.into_masked()),
("timestamp".to_string(), timestamp.to_string().into()),
("signature".to_string(), signature.into_masked()),
];
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.headers(headers)
.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: rapyd::RapydPaymentsResponse = res
.response
.parse_struct("RapydPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/v1/payments/{}/capture",
self.base_url(connectors),
req.request.connector_transaction_id
))
}
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 Rapyd {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Rapyd {
//TODO: implement sessions flow
}
impl api::Refund for Rapyd {}
impl api::RefundExecute for Rapyd {}
impl api::RefundSync for Rapyd {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Rapyd {
fn get_headers(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![(
headers::CONTENT_TYPE.to_string(),
types::RefundExecuteType::get_content_type(self)
.to_string()
.into(),
)])
}
fn get_content_type(&self) -> &'static str {
ConnectorCommon::common_get_content_type(self)
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/v1/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_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = rapyd::RapydRouterData::from((amount, req));
let connector_req = rapyd::RapydRefundRequest::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 timestamp = date_time::now_unix_timestamp();
let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12);
let body = types::RefundExecuteType::get_request_body(self, req, connectors)?;
let req_body = body.get_inner_value().expose();
let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?;
let signature =
self.generate_signature(&auth, "post", "/v1/refunds", &req_body, timestamp, &salt)?;
let headers = vec![
("access_key".to_string(), auth.access_key.into_masked()),
("salt".to_string(), salt.into_masked()),
("timestamp".to_string(), timestamp.to_string().into()),
("signature".to_string(), signature.into_masked()),
];
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(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: rapyd::RefundResponse = res
.response
.parse_struct("rapyd 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 Rapyd {
// default implementation of build_request method will be executed
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: rapyd::RefundResponse = res
.response
.parse_struct("rapyd 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)
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Rapyd {
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 base64_signature = get_header_key_value("signature", request.headers)?;
let signature = BASE64_ENGINE_URL_SAFE
.decode(base64_signature.as_bytes())
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
Ok(signature)
}
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 host = get_header_key_value("host", request.headers)?;
let connector = self.id();
let url_path = format!(
"https://{host}/webhooks/{}/{connector}",
merchant_id.get_string_repr()
);
let salt = get_header_key_value("salt", request.headers)?;
let timestamp = get_header_key_value("timestamp", request.headers)?;
let stringify_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 auth: transformers::RapydAuthType = stringify_auth
.parse_struct("RapydAuthType")
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let access_key = auth.access_key;
let secret_key = auth.secret_key;
let body_string = String::from_utf8(request.body.to_vec())
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Could not convert body to UTF-8")?;
let to_sign = format!(
"{url_path}{salt}{timestamp}{}{}{body_string}",
access_key.peek(),
secret_key.peek()
);
Ok(to_sign.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::WebhookSourceVerificationFailed)?;
let message = self
.get_webhook_source_verification_message(
request,
merchant_id,
&connector_webhook_secrets,
)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let stringify_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 auth: transformers::RapydAuthType = stringify_auth
.parse_struct("RapydAuthType")
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let secret_key = auth.secret_key;
let key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.peek().as_bytes());
let tag = hmac::sign(&key, &message);
let hmac_sign = hex::encode(tag);
Ok(hmac_sign.as_bytes().eq(&signature))
}
fn get_webhook_object_reference_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook: transformers::RapydIncomingWebhook = request
.body
.parse_struct("RapydIncomingWebhook")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(match webhook.data {
transformers::WebhookData::Payment(payment_data) => {
api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(payment_data.id),
)
}
transformers::WebhookData::Refund(refund_data) => {
api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(refund_data.id),
)
}
transformers::WebhookData::Dispute(dispute_data) => {
api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
dispute_data.original_transaction_id,
),
)
}
})
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let webhook: transformers::RapydIncomingWebhook = request
.body
.parse_struct("RapydIncomingWebhook")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(match webhook.webhook_type {
rapyd::RapydWebhookObjectEventType::PaymentCompleted
| rapyd::RapydWebhookObjectEventType::PaymentCaptured => {
IncomingWebhookEvent::PaymentIntentSuccess
}
rapyd::RapydWebhookObjectEventType::PaymentFailed => {
IncomingWebhookEvent::PaymentIntentFailure
}
rapyd::RapydWebhookObjectEventType::PaymentRefundFailed
| rapyd::RapydWebhookObjectEventType::PaymentRefundRejected => {
IncomingWebhookEvent::RefundFailure
}
rapyd::RapydWebhookObjectEventType::RefundCompleted => {
IncomingWebhookEvent::RefundSuccess
}
rapyd::RapydWebhookObjectEventType::PaymentDisputeCreated => {
IncomingWebhookEvent::DisputeOpened
}
rapyd::RapydWebhookObjectEventType::Unknown => IncomingWebhookEvent::EventNotSupported,
rapyd::RapydWebhookObjectEventType::PaymentDisputeUpdated => match webhook.data {
rapyd::WebhookData::Dispute(data) => IncomingWebhookEvent::from(data.status),
_ => IncomingWebhookEvent::EventNotSupported,
},
})
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook: transformers::RapydIncomingWebhook = request
.body
.parse_struct("RapydIncomingWebhook")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
let res_json = match webhook.data {
transformers::WebhookData::Payment(payment_data) => {
let rapyd_response: transformers::RapydPaymentsResponse = payment_data.into();
rapyd_response
.encode_to_value()
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?
}
transformers::WebhookData::Refund(refund_data) => refund_data
.encode_to_value()
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?,
transformers::WebhookData::Dispute(dispute_data) => dispute_data
.encode_to_value()
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?,
};
Ok(Box::new(res_json))
}
fn get_dispute_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<DisputePayload, errors::ConnectorError> {
let webhook: transformers::RapydIncomingWebhook = request
.body
.parse_struct("RapydIncomingWebhook")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
let webhook_dispute_data = match webhook.data {
transformers::WebhookData::Dispute(dispute_data) => Ok(dispute_data),
_ => Err(errors::ConnectorError::WebhookBodyDecodingFailed),
}?;
Ok(DisputePayload {
amount: webhook_dispute_data.amount.to_string(),
currency: webhook_dispute_data.currency,
dispute_stage: api_models::enums::DisputeStage::Dispute,
connector_dispute_id: webhook_dispute_data.token,
connector_reason: Some(webhook_dispute_data.dispute_reason_description),
connector_reason_code: None,
challenge_required_by: webhook_dispute_data.due_date,
connector_status: webhook_dispute_data.status.to_string(),
created_at: webhook_dispute_data.created_at,
updated_at: webhook_dispute_data.updated_at,
})
}
}
lazy_static! {
static ref RAPYD_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
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::Visa,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Discover,
];
let mut rapyd_supported_payment_methods = SupportedPaymentMethods::new();
rapyd_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,
}
);
rapyd_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,
}
);
rapyd_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(),
}
}),
),
}
);
rapyd_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(),
}
}),
),
}
);
rapyd_supported_payment_methods
};
static ref RAPYD_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Rapyd",
description:
"Rapyd is a fintech company that enables businesses to collect payments in local currencies across the globe ",
connector_type: enums::PaymentConnectorCategory::PaymentGateway,
};
static ref RAPYD_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = vec![enums::EventClass::Payments, enums::EventClass::Refunds, enums::EventClass::Disputes];
}
impl ConnectorSpecifications for Rapyd {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*RAPYD_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*RAPYD_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*RAPYD_SUPPORTED_WEBHOOK_FLOWS)
}
}
| 8,643 | 2,096 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/fiservemea.rs | .rs | pub mod transformers;
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 lazy_static::lazy_static;
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,
network_advice_code: None,
network_decline_code: None,
network_error_message: 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,
network_advice_code: None,
network_decline_code: None,
network_error_message: 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<'_>,
) -> 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))
}
}
lazy_static! {
static ref FISERVEMEA_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
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 ref 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::PaymentConnectorCategory::BankAcquirer,
};
static ref FISERVEMEA_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
}
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)
}
}
| 6,635 | 2,097 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/nuvei.rs | .rs | pub mod transformers;
use std::fmt::Debug;
use api_models::{payments::PaymentIdType, webhooks::IncomingWebhookEvent};
use common_enums::{enums, CallConnectorAction, PaymentAction};
use common_utils::{
crypto,
errors::{CustomResult, ReportSwitchExt},
ext_traits::{ByteSliceExt, BytesExt, ValueExt},
id_type,
request::{Method, Request, RequestBuilder, RequestContent},
};
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},
AuthorizeSessionToken, CompleteAuthorize, PreProcessing,
},
router_request_types::{
AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData,
PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData,
PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsAuthorizeSessionTokenRouterData,
PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData,
PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::ExposeInterface;
use transformers as nuvei;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, is_mandate_supported, PaymentMethodDataType, RouterData as _},
};
#[derive(Debug, Clone)]
pub struct Nuvei;
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nuvei
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 headers = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
Ok(headers)
}
}
impl ConnectorCommon for Nuvei {
fn id(&self) -> &'static str {
"nuvei"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.nuvei.base_url.as_ref()
}
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![])
}
}
impl ConnectorValidation for Nuvei {
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(
utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
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 Nuvei {}
impl api::PaymentToken for Nuvei {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Nuvei
{
// Not Implemented (R)
}
impl api::MandateSetup for Nuvei {}
impl api::PaymentVoid for Nuvei {}
impl api::PaymentSync for Nuvei {}
impl api::PaymentCapture for Nuvei {}
impl api::PaymentSession for Nuvei {}
impl api::PaymentAuthorize for Nuvei {}
impl api::PaymentAuthorizeSessionToken for Nuvei {}
impl api::Refund for Nuvei {}
impl api::RefundExecute for Nuvei {}
impl api::RefundSync for Nuvei {}
impl api::PaymentsCompleteAuthorize for Nuvei {}
impl api::ConnectorAccessToken for Nuvei {}
impl api::PaymentsPreProcessing for Nuvei {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Nuvei {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Nuvei".to_string())
.into(),
)
}
}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Nuvei
{
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!(
"{}ppp/api/v1/payment.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let meta: nuvei::NuveiMeta = utils::to_connector_meta(req.request.connector_meta.clone())?;
let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, meta.session_token))?;
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: nuvei::NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.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 ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nuvei {
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!(
"{}ppp/api/v1/voidTransaction.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nuvei::NuveiPaymentFlowRequest::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::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: nuvei::NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.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 ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Nuvei {}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nuvei {
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!(
"{}ppp/api/v1/getPaymentStatus.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nuvei::NuveiPaymentSyncRequest::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 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: nuvei::NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.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)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Nuvei {
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!(
"{}ppp/api/v1/settleTransaction.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nuvei::NuveiPaymentFlowRequest::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::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: nuvei::NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.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 ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Nuvei {}
#[async_trait::async_trait]
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Nuvei {
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!(
"{}ppp/api/v1/payment.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, req.get_session_token()?))?;
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: nuvei::NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.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 ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>
for Nuvei
{
fn get_headers(
&self,
req: &PaymentsAuthorizeSessionTokenRouterData,
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: &PaymentsAuthorizeSessionTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ppp/api/v1/getSessionToken.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeSessionTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nuvei::NuveiSessionRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeSessionTokenRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsPreAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsPreAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsPreAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeSessionTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeSessionTokenRouterData, errors::ConnectorError> {
let response: nuvei::NuveiSessionResponse =
res.response.parse_struct("NuveiSessionResponse").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<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
for Nuvei
{
fn get_headers(
&self,
req: &PaymentsPreProcessingRouterData,
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: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ppp/api/v1/initPayment.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsPreProcessingRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, req.get_session_token()?))?;
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: nuvei::NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.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 ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nuvei {
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!(
"{}ppp/api/v1/refundTransaction.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nuvei::NuveiPaymentFlowRequest::try_from(req)?;
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: nuvei::NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.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 ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nuvei {}
#[async_trait::async_trait]
impl IncomingWebhook for Nuvei {
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::Sha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let signature = utils::get_header_key_value("advanceResponseChecksum", request.headers)?;
hex::decode(signature).change_context(errors::ConnectorError::WebhookResponseEncodingFailed)
}
fn get_webhook_source_verification_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &id_type::MerchantId,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let body = serde_urlencoded::from_str::<nuvei::NuveiWebhookDetails>(&request.query_params)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let secret_str = std::str::from_utf8(&connector_webhook_secrets.secret)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let status = format!("{:?}", body.status).to_uppercase();
let to_sign = format!(
"{}{}{}{}{}{}{}",
secret_str,
body.total_amount,
body.currency,
body.response_time_stamp,
body.ppp_transaction_id,
status,
body.product_id
);
Ok(to_sign.into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let body =
serde_urlencoded::from_str::<nuvei::NuveiWebhookTransactionId>(&request.query_params)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
PaymentIdType::ConnectorTransactionId(body.ppp_transaction_id),
))
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let body =
serde_urlencoded::from_str::<nuvei::NuveiWebhookDataStatus>(&request.query_params)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
match body.status {
nuvei::NuveiWebhookStatus::Approved => Ok(IncomingWebhookEvent::PaymentIntentSuccess),
nuvei::NuveiWebhookStatus::Declined => Ok(IncomingWebhookEvent::PaymentIntentFailure),
nuvei::NuveiWebhookStatus::Unknown
| nuvei::NuveiWebhookStatus::Pending
| nuvei::NuveiWebhookStatus::Update => Ok(IncomingWebhookEvent::EventNotSupported),
}
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let body = serde_urlencoded::from_str::<nuvei::NuveiWebhookDetails>(&request.query_params)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let payment_response = nuvei::NuveiPaymentsResponse::from(body);
Ok(Box::new(payment_response))
}
}
impl ConnectorRedirectResponse for Nuvei {
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 => {
if let Some(payload) = json_payload {
let redirect_response: nuvei::NuveiRedirectionResponse =
payload.parse_value("NuveiRedirectionResponse").switch()?;
let acs_response: nuvei::NuveiACSResponse =
utils::base64_decode(redirect_response.cres.expose())?
.as_slice()
.parse_struct("NuveiACSResponse")
.switch()?;
match acs_response.trans_status {
None | Some(nuvei::LiabilityShift::Failed) => {
Ok(CallConnectorAction::StatusUpdate {
status: enums::AttemptStatus::AuthenticationFailed,
error_code: None,
error_message: None,
})
}
_ => Ok(CallConnectorAction::Trigger),
}
} else {
Ok(CallConnectorAction::Trigger)
}
}
}
}
}
impl ConnectorSpecifications for Nuvei {}
| 7,270 | 2,098 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/worldpay.rs | .rs | mod requests;
mod response;
pub mod transformers;
use api_models::{payments::PaymentIdType, webhooks::IncomingWebhookEvent};
use common_enums::{enums, PaymentAction};
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},
CompleteAuthorize,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, ResponseId, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundExecuteRouterData,
RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, PaymentsVoidType, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::Mask;
use requests::{
WorldpayCompleteAuthorizationRequest, WorldpayPartialRequest, WorldpayPaymentsRequest,
};
use response::{
EventType, ResponseIdStr, WorldpayErrorResponse, WorldpayEventResponse,
WorldpayPaymentsResponse, WorldpayWebhookEventType, WorldpayWebhookTransactionId,
WP_CORRELATION_ID,
};
use ring::hmac;
use self::transformers as worldpay;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{
construct_not_implemented_error_report, convert_amount, get_header_key_value,
is_mandate_supported, ForeignTryFrom, PaymentMethodDataType, RefundsRequestData,
},
};
#[derive(Clone)]
pub struct Worldpay {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Worldpay {
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Worldpay
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 headers = vec![
(
headers::ACCEPT.to_string(),
self.get_content_type().to_string().into(),
),
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(headers::WP_API_VERSION.to_string(), "2024-06-01".into()),
];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
headers.append(&mut api_key);
Ok(headers)
}
}
impl ConnectorCommon for Worldpay {
fn id(&self) -> &'static str {
"worldpay"
}
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.worldpay.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = worldpay::WorldpayAuthType::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 = if !res.response.is_empty() {
res.response
.parse_struct("WorldpayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?
} else {
WorldpayErrorResponse::default(res.status_code)
};
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_name,
message: response.message,
reason: response.validation_errors.map(|e| e.to_string()),
attempt_status: Some(enums::AttemptStatus::Failure),
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl ConnectorValidation for Worldpay {
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_implemented_error_report(capture_method, self.id()),
),
}
}
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.clone(), pm_type, mandate_supported_pmd, self.id())
}
fn is_webhook_source_verification_mandatory(&self) -> bool {
true
}
}
impl api::Payment for Worldpay {}
impl api::MandateSetup for Worldpay {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Worldpay
{
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!("{}api/payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let auth = worldpay::WorldpayAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let connector_router_data = worldpay::WorldpayRouterData::try_from((
&self.get_currency_unit(),
req.request.currency,
req.request.minor_amount.unwrap_or_default(),
req,
))?;
let connector_req =
WorldpayPaymentsRequest::try_from((&connector_router_data, &auth.entity_id))?;
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(&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: WorldpayPaymentsResponse = res
.response
.parse_struct("Worldpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let optional_correlation_id = res.headers.and_then(|headers| {
headers
.get(WP_CORRELATION_ID)
.and_then(|header_value| header_value.to_str().ok())
.map(|id| id.to_string())
});
RouterData::foreign_try_from((
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
optional_correlation_id,
))
.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::PaymentToken for Worldpay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Worldpay
{
// Not Implemented (R)
}
impl api::PaymentVoid for Worldpay {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Worldpay {
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!(
"{}api/payments/{}/cancellations",
self.base_url(connectors),
urlencoding::encode(&connector_payment_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)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError>
where
Void: Clone,
PaymentsCancelData: Clone,
PaymentsResponseData: Clone,
{
match res.status_code {
202 => {
let response: WorldpayPaymentsResponse = res
.response
.parse_struct("Worldpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let optional_correlation_id = res.headers.and_then(|headers| {
headers
.get(WP_CORRELATION_ID)
.and_then(|header_value| header_value.to_str().ok())
.map(|id| id.to_string())
});
Ok(PaymentsCancelRouterData {
status: enums::AttemptStatus::from(response.outcome.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::foreign_try_from((
response,
Some(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: optional_correlation_id,
incremental_authorization_allowed: None,
charges: None,
}),
..data.clone()
})
}
_ => Err(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 Worldpay {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Worldpay {}
impl api::PaymentSync for Worldpay {}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Worldpay {
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!(
"{}api/payments/{}",
self.base_url(connectors),
urlencoding::encode(&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 get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response = if !res.response.is_empty() {
res.response
.parse_struct("WorldpayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?
} else {
WorldpayErrorResponse::default(res.status_code)
};
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_name,
message: response.message,
reason: response.validation_errors.map(|e| e.to_string()),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: WorldpayEventResponse =
res.response
.parse_struct("Worldpay EventResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let optional_correlation_id = res.headers.and_then(|headers| {
headers
.get(WP_CORRELATION_ID)
.and_then(|header_value| header_value.to_str().ok())
.map(|id| id.to_string())
});
let attempt_status = data.status;
let worldpay_status = response.last_event;
let status = match (attempt_status, worldpay_status.clone()) {
(
enums::AttemptStatus::Authorizing
| enums::AttemptStatus::Authorized
| enums::AttemptStatus::CaptureInitiated
| enums::AttemptStatus::Charged
| enums::AttemptStatus::Pending
| enums::AttemptStatus::VoidInitiated,
EventType::Authorized,
) => attempt_status,
_ => enums::AttemptStatus::from(&worldpay_status),
};
Ok(PaymentsSyncRouterData {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: 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: optional_correlation_id,
incremental_authorization_allowed: None,
charges: None,
}),
..data.clone()
})
}
}
impl api::PaymentCapture for Worldpay {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Worldpay {
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/payments/{}/partialSettlements",
self.base_url(connectors),
urlencoding::encode(&connector_payment_id),
))
}
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_req = WorldpayPartialRequest::try_from((req, amount_to_capture))?;
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> {
match res.status_code {
202 => {
let response: WorldpayPaymentsResponse = res
.response
.parse_struct("Worldpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let optional_correlation_id = res.headers.and_then(|headers| {
headers
.get(WP_CORRELATION_ID)
.and_then(|header_value| header_value.to_str().ok())
.map(|id| id.to_string())
});
Ok(PaymentsCaptureRouterData {
status: enums::AttemptStatus::from(response.outcome.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::foreign_try_from((
response,
Some(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: optional_correlation_id,
incremental_authorization_allowed: None,
charges: None,
}),
..data.clone()
})
}
_ => Err(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 Worldpay {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Worldpay {}
impl api::PaymentAuthorize for Worldpay {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Worldpay {
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/payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = worldpay::WorldpayRouterData::try_from((
&self.get_currency_unit(),
req.request.currency,
req.request.minor_amount,
req,
))?;
let auth = worldpay::WorldpayAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let connector_req =
WorldpayPaymentsRequest::try_from((&connector_router_data, &auth.entity_id))?;
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: WorldpayPaymentsResponse = res
.response
.parse_struct("Worldpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let optional_correlation_id = res.headers.and_then(|headers| {
headers
.get(WP_CORRELATION_ID)
.and_then(|header_value| header_value.to_str().ok())
.map(|id| id.to_string())
});
RouterData::foreign_try_from((
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
optional_correlation_id,
))
.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::PaymentsCompleteAuthorize for Worldpay {}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Worldpay
{
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 connector_payment_id = req
.request
.connector_transaction_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorTransactionID)?;
let stage = match req.status {
enums::AttemptStatus::DeviceDataCollectionPending => "3dsDeviceData".to_string(),
_ => "3dsChallenges".to_string(),
};
Ok(format!(
"{}api/payments/{connector_payment_id}/{stage}",
self.base_url(connectors),
))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = WorldpayCompleteAuthorizationRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = 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();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: WorldpayPaymentsResponse = res
.response
.parse_struct("WorldpayPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let optional_correlation_id = res.headers.and_then(|headers| {
headers
.get(WP_CORRELATION_ID)
.and_then(|header_value| header_value.to_str().ok())
.map(|id| id.to_string())
});
RouterData::foreign_try_from((
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
optional_correlation_id,
))
.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::Refund for Worldpay {}
impl api::RefundExecute for Worldpay {}
impl api::RefundSync for Worldpay {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Worldpay {
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_request_body(
&self,
req: &RefundExecuteRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_to_refund = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_req = WorldpayPartialRequest::try_from((req, amount_to_refund))?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
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/payments/{}/partialRefunds",
self.base_url(connectors),
urlencoding::encode(&connector_payment_id),
))
}
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> {
match res.status_code {
202 => {
let response: WorldpayPaymentsResponse = res
.response
.parse_struct("Worldpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let optional_correlation_id = res.headers.and_then(|headers| {
headers
.get(WP_CORRELATION_ID)
.and_then(|header_value| header_value.to_str().ok())
.map(|id| id.to_string())
});
Ok(RefundExecuteRouterData {
response: Ok(RefundsResponseData {
refund_status: enums::RefundStatus::from(response.outcome.clone()),
connector_refund_id: ResponseIdStr::foreign_try_from((
response,
optional_correlation_id,
))?
.id,
}),
..data.clone()
})
}
_ => Err(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 Worldpay {
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!(
"{}api/payments/{}",
self.base_url(connectors),
urlencoding::encode(&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: WorldpayEventResponse =
res.response
.parse_struct("Worldpay EventResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(RefundSyncRouterData {
response: Ok(RefundsResponseData {
connector_refund_id: data.request.refund_id.clone(),
refund_status: enums::RefundStatus::from(response.last_event),
}),
..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)
}
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 Worldpay {
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::Sha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let mut event_signature =
get_header_key_value("Event-Signature", request.headers)?.split(',');
let sign_header = event_signature
.next_back()
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)?;
let signature = sign_header
.split('/')
.next_back()
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)?;
hex::decode(signature).change_context(errors::ConnectorError::WebhookResponseEncodingFailed)
}
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(request.body.to_vec())
}
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<masking::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 secret_key = hex::decode(connector_webhook_secrets.secret)
.change_context(errors::ConnectorError::WebhookVerificationSecretInvalid)?;
let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &secret_key);
let signed_message = hmac::sign(&signing_key, &message);
let computed_signature = hex::encode(signed_message.as_ref());
Ok(computed_signature.as_bytes() == hex::encode(signature).as_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let body: WorldpayWebhookTransactionId = request
.body
.parse_struct("WorldpayWebhookTransactionId")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
PaymentIdType::PaymentAttemptId(body.event_details.transaction_reference),
))
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let body: WorldpayWebhookEventType = request
.body
.parse_struct("WorldpayWebhookEventType")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
match body.event_details.event_type {
EventType::Authorized => Ok(IncomingWebhookEvent::PaymentIntentAuthorizationSuccess),
EventType::Settled => Ok(IncomingWebhookEvent::PaymentIntentSuccess),
EventType::SentForSettlement | EventType::SentForAuthorization => {
Ok(IncomingWebhookEvent::PaymentIntentProcessing)
}
EventType::Error | EventType::Expired | EventType::SettlementFailed => {
Ok(IncomingWebhookEvent::PaymentIntentFailure)
}
EventType::Unknown
| EventType::Cancelled
| EventType::Refused
| EventType::Refunded
| EventType::SentForRefund
| EventType::RefundFailed => Ok(IncomingWebhookEvent::EventNotSupported),
}
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let body: WorldpayWebhookEventType = request
.body
.parse_struct("WorldpayWebhookEventType")
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
let psync_body = WorldpayEventResponse::try_from(body)?;
Ok(Box::new(psync_body))
}
fn get_mandate_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Option<hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails>,
errors::ConnectorError,
> {
let body: WorldpayWebhookTransactionId = request
.body
.parse_struct("WorldpayWebhookTransactionId")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let mandate_reference = body.event_details.token.map(|mandate_token| {
hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails {
connector_mandate_id: mandate_token.href,
}
});
Ok(mandate_reference)
}
fn get_network_txn_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Option<hyperswitch_domain_models::router_flow_types::ConnectorNetworkTxnId>,
errors::ConnectorError,
> {
let body: WorldpayWebhookTransactionId = request
.body
.parse_struct("WorldpayWebhookTransactionId")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let optional_network_txn_id = body.event_details.scheme_reference.map(|network_txn_id| {
hyperswitch_domain_models::router_flow_types::ConnectorNetworkTxnId::new(network_txn_id)
});
Ok(optional_network_txn_id)
}
}
impl ConnectorRedirectResponse for Worldpay {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
action: PaymentAction,
) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> {
match action {
PaymentAction::CompleteAuthorize => Ok(enums::CallConnectorAction::Trigger),
PaymentAction::PSync | PaymentAction::PaymentAuthenticateCompleteAuthorize => {
Ok(enums::CallConnectorAction::Avoid)
}
}
}
}
impl ConnectorSpecifications for Worldpay {}
| 9,482 | 2,099 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/billwerk.rs | .rs | pub mod transformers;
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},
};
use lazy_static::lazy_static;
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,
network_advice_code: None,
network_decline_code: None,
network_error_message: 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<'_>,
) -> 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))
}
}
lazy_static! {
static ref BILLWERK_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
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 ref 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::PaymentConnectorCategory::PaymentGateway,
};
static ref BILLWERK_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
}
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)
}
}
| 6,543 | 2,100 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/getnet.rs | .rs | pub mod transformers;
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::{PaymentsResponseData, RefundsResponseData},
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,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl ConnectorValidation for Getnet {
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::Scheduled | enums::CaptureMethod::ManualMultiple => Err(
utils::construct_not_implemented_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 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!(
"{}/merchants/{}/payments/{}",
endpoint, merchant_id, 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!(
"{}/merchants/{}/payments/{}",
endpoint, merchant_id, 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<'_>,
) -> 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)
}
}
impl ConnectorSpecifications for Getnet {}
| 6,291 | 2,101 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/hipay.rs | .rs | pub mod transformers;
use base64::Engine;
use common_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::{PaymentsResponseData, RefundsResponseData},
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>(data: T) -> Result<Form, 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(form)
}
#[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);
let connector_req = build_form_from_struct(connector_req)
.change_context(errors::ConnectorError::ParsingFailed)?;
Ok(RequestContent::FormData(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)?)
.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,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl ConnectorValidation for Hipay {
fn validate_connector_against_payment_request(
&self,
capture_method: Option<CaptureMethod>,
_payment_method: PaymentMethod,
_pmt: Option<PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
match capture_method {
CaptureMethod::Automatic
| CaptureMethod::Manual
| CaptureMethod::SequentialAutomatic => Ok(()),
CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => {
Err(errors::ConnectorError::NotSupported {
message: capture_method.to_string(),
connector: self.id(),
}
.into())
}
}
}
}
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);
let connector_req = build_form_from_struct(connector_req)
.change_context(errors::ConnectorError::ParsingFailed)?;
Ok(RequestContent::FormData(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,
)?)
.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);
let connector_req = build_form_from_struct(connector_req)
.change_context(errors::ConnectorError::ParsingFailed)?;
Ok(RequestContent::FormData(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: 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);
let connector_req = build_form_from_struct(connector_req)
.change_context(errors::ConnectorError::ParsingFailed)?;
Ok(RequestContent::FormData(connector_req))
}
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);
let connector_req = build_form_from_struct(connector_req)
.change_context(errors::ConnectorError::ParsingFailed)?;
Ok(RequestContent::FormData(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: 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<'_>,
) -> 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 Hipay {}
| 5,929 | 2,102 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/braintree.rs | .rs | pub mod transformers;
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},
};
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::{MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData},
types::{
MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, 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, PaymentsSyncType, PaymentsVoidType, RefundExecuteType,
RefundSyncType, Response, TokenizationType,
},
webhooks::{IncomingWebhook, IncomingWebhookFlowError, IncomingWebhookRequestDetails},
};
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, to_currency_lower_unit, PaymentMethodDataType,
PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
},
};
#[derive(Clone)]
pub struct Braintree {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Braintree {
pub const fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
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,
network_advice_code: None,
network_decline_code: None,
network_error_message: 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,
network_advice_code: None,
network_decline_code: None,
network_error_message: 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_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(
utils::construct_not_implemented_error_report(capture_method, self.id()),
),
}
}
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]);
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 {}
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<'_>,
) -> 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<'_>,
) -> 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: to_currency_lower_unit(
dispute_data.amount_disputed.to_string(),
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)
}
}
impl ConnectorSpecifications for Braintree {}
| 9,746 | 2,103 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/klarna.rs | .rs | pub mod transformers;
use api_models::webhooks::IncomingWebhookEvent;
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::{PayLaterData, 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::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSessionRouterData, PaymentsSyncRouterData, 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::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::{Mask, PeekInterface};
use router_env::logger;
use transformers as klarna;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{
construct_not_supported_error_report, convert_amount, get_http_header,
get_unimplemented_payment_method_error_message, missing_field_err, RefundsRequestData,
},
};
#[derive(Clone)]
pub struct Klarna {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Klarna {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl ConnectorCommon for Klarna {
fn id(&self) -> &'static str {
"klarna"
}
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.klarna.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = klarna::KlarnaAuthType::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: klarna::KlarnaErrorResponse = res
.response
.parse_struct("KlarnaErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
// KlarnaErrorResponse will either have error_messages or error_message field Ref: https://docs.klarna.com/api/errors/
let reason = response
.error_messages
.map(|messages| messages.join(" & "))
.or(response.error_message.clone());
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_code,
message: response
.error_message
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl ConnectorValidation for Klarna {
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()),
),
}
}
}
impl api::Payment for Klarna {}
impl api::PaymentAuthorize for Klarna {}
impl api::PaymentSync for Klarna {}
impl api::PaymentVoid for Klarna {}
impl api::PaymentCapture for Klarna {}
impl api::PaymentSession for Klarna {}
impl api::ConnectorAccessToken for Klarna {}
impl api::PaymentToken for Klarna {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Klarna
{
// Not Implemented (R)
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Klarna {
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Klarna
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(),
types::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 build_region_specific_endpoint(
base_url: &str,
connector_metadata: &Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<String, errors::ConnectorError> {
let klarna_metadata_object =
transformers::KlarnaConnectorMetadataObject::try_from(connector_metadata)?;
let klarna_region = klarna_metadata_object
.klarna_region
.ok_or(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata.klarna_region",
})
.map(String::from)?;
Ok(base_url.replace("{{klarna_region}}", &klarna_region))
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Klarna {
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> {
let endpoint =
build_region_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
Ok(format!("{endpoint}payments/v1/sessions"))
}
fn get_request_body(
&self,
req: &PaymentsSessionRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = klarna::KlarnaRouterData::from((amount, req));
let connector_req = klarna::KlarnaSessionRequest::try_from(&connector_router_data)?;
// encode only for for urlencoded things.
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: klarna::KlarnaSessionResponse = res
.response
.parse_struct("KlarnaSessionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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 Klarna {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Klarna {
// 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 Klarna".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Klarna {
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 order_id = req.request.connector_transaction_id.clone();
let endpoint =
build_region_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
Ok(format!(
"{endpoint}ordermanagement/v1/orders/{order_id}/captures"
))
}
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 = klarna::KlarnaRouterData::from((amount, req));
let connector_req = klarna::KlarnaCaptureRequest::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::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(Some(request))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
match res.headers {
Some(headers) => {
let capture_id = get_http_header("Capture-Id", &headers)
.attach_printable("Missing capture id in headers")
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let response = klarna::KlarnaCaptureResponse {
capture_id: Some(capture_id.to_owned()),
};
event_builder.map(|i| i.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 => Err(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable("Expected headers, but received no headers in response")?,
}
}
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 Klarna {
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 order_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let endpoint =
build_region_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
let payment_experience = req.request.payment_experience;
match payment_experience {
Some(common_enums::PaymentExperience::InvokeSdkClient) => {
Ok(format!("{endpoint}ordermanagement/v1/orders/{order_id}"))
}
Some(common_enums::PaymentExperience::RedirectToUrl) => {
Ok(format!("{endpoint}checkout/v3/orders/{order_id}"))
}
None => Err(error_stack::report!(errors::ConnectorError::NotSupported {
message: "payment_experience not supported".to_string(),
connector: "klarna",
})),
_ => Err(error_stack::report!(errors::ConnectorError::NotSupported {
message: "payment_experience not supported".to_string(),
connector: "klarna",
})),
}
}
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: klarna::KlarnaPsyncResponse = res
.response
.parse_struct("klarna KlarnaPsyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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 Klarna {
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 payment_method_data = &req.request.payment_method_data;
let payment_experience = req
.request
.payment_experience
.as_ref()
.ok_or_else(missing_field_err("payment_experience"))?;
let payment_method_type = req
.request
.payment_method_type
.as_ref()
.ok_or_else(missing_field_err("payment_method_type"))?;
let endpoint =
build_region_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
match payment_method_data {
PaymentMethodData::PayLater(PayLaterData::KlarnaSdk { token }) => {
match (payment_experience, payment_method_type) {
(
common_enums::PaymentExperience::InvokeSdkClient,
common_enums::PaymentMethodType::Klarna,
) => Ok(format!(
"{endpoint}payments/v1/authorizations/{token}/order",
)),
#[cfg(feature = "v1")]
(
common_enums::PaymentExperience::DisplayQrCode
| common_enums::PaymentExperience::DisplayWaitScreen
| common_enums::PaymentExperience::InvokePaymentApp
| common_enums::PaymentExperience::InvokeSdkClient
| common_enums::PaymentExperience::LinkWallet
| common_enums::PaymentExperience::OneClick
| common_enums::PaymentExperience::RedirectToUrl
| common_enums::PaymentExperience::CollectOtp,
common_enums::PaymentMethodType::Ach
| common_enums::PaymentMethodType::Affirm
| common_enums::PaymentMethodType::AfterpayClearpay
| common_enums::PaymentMethodType::Alfamart
| common_enums::PaymentMethodType::AliPay
| common_enums::PaymentMethodType::AliPayHk
| common_enums::PaymentMethodType::Alma
| common_enums::PaymentMethodType::AmazonPay
| common_enums::PaymentMethodType::ApplePay
| common_enums::PaymentMethodType::Atome
| common_enums::PaymentMethodType::Bacs
| common_enums::PaymentMethodType::BancontactCard
| common_enums::PaymentMethodType::Becs
| common_enums::PaymentMethodType::Benefit
| common_enums::PaymentMethodType::Bizum
| common_enums::PaymentMethodType::Blik
| common_enums::PaymentMethodType::Boleto
| common_enums::PaymentMethodType::BcaBankTransfer
| common_enums::PaymentMethodType::BniVa
| common_enums::PaymentMethodType::BriVa
| common_enums::PaymentMethodType::CardRedirect
| common_enums::PaymentMethodType::CimbVa
| common_enums::PaymentMethodType::ClassicReward
| common_enums::PaymentMethodType::Credit
| common_enums::PaymentMethodType::CryptoCurrency
| common_enums::PaymentMethodType::Cashapp
| common_enums::PaymentMethodType::Dana
| common_enums::PaymentMethodType::DanamonVa
| common_enums::PaymentMethodType::Debit
| common_enums::PaymentMethodType::DirectCarrierBilling
| common_enums::PaymentMethodType::Efecty
| common_enums::PaymentMethodType::Eft
| common_enums::PaymentMethodType::Eps
| common_enums::PaymentMethodType::Evoucher
| common_enums::PaymentMethodType::Giropay
| common_enums::PaymentMethodType::Givex
| common_enums::PaymentMethodType::GooglePay
| common_enums::PaymentMethodType::GoPay
| common_enums::PaymentMethodType::Gcash
| common_enums::PaymentMethodType::Ideal
| common_enums::PaymentMethodType::Interac
| common_enums::PaymentMethodType::Indomaret
| common_enums::PaymentMethodType::Klarna
| common_enums::PaymentMethodType::KakaoPay
| common_enums::PaymentMethodType::MandiriVa
| common_enums::PaymentMethodType::Knet
| common_enums::PaymentMethodType::MbWay
| common_enums::PaymentMethodType::MobilePay
| common_enums::PaymentMethodType::Momo
| common_enums::PaymentMethodType::MomoAtm
| common_enums::PaymentMethodType::Multibanco
| common_enums::PaymentMethodType::LocalBankRedirect
| common_enums::PaymentMethodType::OnlineBankingThailand
| common_enums::PaymentMethodType::OnlineBankingCzechRepublic
| common_enums::PaymentMethodType::OnlineBankingFinland
| common_enums::PaymentMethodType::OnlineBankingFpx
| common_enums::PaymentMethodType::OnlineBankingPoland
| common_enums::PaymentMethodType::OnlineBankingSlovakia
| common_enums::PaymentMethodType::Oxxo
| common_enums::PaymentMethodType::PagoEfectivo
| common_enums::PaymentMethodType::PermataBankTransfer
| common_enums::PaymentMethodType::OpenBankingUk
| common_enums::PaymentMethodType::PayBright
| common_enums::PaymentMethodType::Paypal
| common_enums::PaymentMethodType::Paze
| common_enums::PaymentMethodType::Pix
| common_enums::PaymentMethodType::PaySafeCard
| common_enums::PaymentMethodType::Przelewy24
| common_enums::PaymentMethodType::Pse
| common_enums::PaymentMethodType::RedCompra
| common_enums::PaymentMethodType::RedPagos
| common_enums::PaymentMethodType::SamsungPay
| common_enums::PaymentMethodType::Sepa
| common_enums::PaymentMethodType::SepaBankTransfer
| common_enums::PaymentMethodType::Sofort
| common_enums::PaymentMethodType::Swish
| common_enums::PaymentMethodType::TouchNGo
| common_enums::PaymentMethodType::Trustly
| common_enums::PaymentMethodType::Twint
| common_enums::PaymentMethodType::UpiCollect
| common_enums::PaymentMethodType::UpiIntent
| common_enums::PaymentMethodType::Venmo
| common_enums::PaymentMethodType::Vipps
| common_enums::PaymentMethodType::Walley
| common_enums::PaymentMethodType::WeChatPay
| common_enums::PaymentMethodType::SevenEleven
| common_enums::PaymentMethodType::Lawson
| common_enums::PaymentMethodType::LocalBankTransfer
| common_enums::PaymentMethodType::InstantBankTransfer
| common_enums::PaymentMethodType::MiniStop
| common_enums::PaymentMethodType::FamilyMart
| common_enums::PaymentMethodType::Seicomart
| common_enums::PaymentMethodType::PayEasy
| common_enums::PaymentMethodType::Mifinity
| common_enums::PaymentMethodType::Fps
| common_enums::PaymentMethodType::DuitNow
| common_enums::PaymentMethodType::PromptPay
| common_enums::PaymentMethodType::VietQr
| common_enums::PaymentMethodType::OpenBankingPIS,
) => Err(error_stack::report!(errors::ConnectorError::NotSupported {
message: payment_method_type.to_string(),
connector: "klarna",
})),
#[cfg(feature = "v2")]
(
common_enums::PaymentExperience::DisplayQrCode
| common_enums::PaymentExperience::DisplayWaitScreen
| common_enums::PaymentExperience::InvokePaymentApp
| common_enums::PaymentExperience::InvokeSdkClient
| common_enums::PaymentExperience::LinkWallet
| common_enums::PaymentExperience::OneClick
| common_enums::PaymentExperience::RedirectToUrl
| common_enums::PaymentExperience::CollectOtp,
common_enums::PaymentMethodType::Ach
| common_enums::PaymentMethodType::Affirm
| common_enums::PaymentMethodType::AfterpayClearpay
| common_enums::PaymentMethodType::Alfamart
| common_enums::PaymentMethodType::AliPay
| common_enums::PaymentMethodType::AliPayHk
| common_enums::PaymentMethodType::Alma
| common_enums::PaymentMethodType::AmazonPay
| common_enums::PaymentMethodType::ApplePay
| common_enums::PaymentMethodType::Atome
| common_enums::PaymentMethodType::Bacs
| common_enums::PaymentMethodType::BancontactCard
| common_enums::PaymentMethodType::Becs
| common_enums::PaymentMethodType::Benefit
| common_enums::PaymentMethodType::Bizum
| common_enums::PaymentMethodType::Blik
| common_enums::PaymentMethodType::Boleto
| common_enums::PaymentMethodType::BcaBankTransfer
| common_enums::PaymentMethodType::BniVa
| common_enums::PaymentMethodType::BriVa
| common_enums::PaymentMethodType::CardRedirect
| common_enums::PaymentMethodType::CimbVa
| common_enums::PaymentMethodType::ClassicReward
| common_enums::PaymentMethodType::Credit
| common_enums::PaymentMethodType::Card
| common_enums::PaymentMethodType::CryptoCurrency
| common_enums::PaymentMethodType::Cashapp
| common_enums::PaymentMethodType::Dana
| common_enums::PaymentMethodType::DanamonVa
| common_enums::PaymentMethodType::Debit
| common_enums::PaymentMethodType::DirectCarrierBilling
| common_enums::PaymentMethodType::Efecty
| common_enums::PaymentMethodType::Eft
| common_enums::PaymentMethodType::Eps
| common_enums::PaymentMethodType::Evoucher
| common_enums::PaymentMethodType::Giropay
| common_enums::PaymentMethodType::Givex
| common_enums::PaymentMethodType::GooglePay
| common_enums::PaymentMethodType::GoPay
| common_enums::PaymentMethodType::Gcash
| common_enums::PaymentMethodType::Ideal
| common_enums::PaymentMethodType::Interac
| common_enums::PaymentMethodType::Indomaret
| common_enums::PaymentMethodType::Klarna
| common_enums::PaymentMethodType::KakaoPay
| common_enums::PaymentMethodType::MandiriVa
| common_enums::PaymentMethodType::Knet
| common_enums::PaymentMethodType::MbWay
| common_enums::PaymentMethodType::MobilePay
| common_enums::PaymentMethodType::Momo
| common_enums::PaymentMethodType::MomoAtm
| common_enums::PaymentMethodType::Multibanco
| common_enums::PaymentMethodType::LocalBankRedirect
| common_enums::PaymentMethodType::OnlineBankingThailand
| common_enums::PaymentMethodType::OnlineBankingCzechRepublic
| common_enums::PaymentMethodType::OnlineBankingFinland
| common_enums::PaymentMethodType::OnlineBankingFpx
| common_enums::PaymentMethodType::OnlineBankingPoland
| common_enums::PaymentMethodType::OnlineBankingSlovakia
| common_enums::PaymentMethodType::Oxxo
| common_enums::PaymentMethodType::PagoEfectivo
| common_enums::PaymentMethodType::PermataBankTransfer
| common_enums::PaymentMethodType::OpenBankingUk
| common_enums::PaymentMethodType::PayBright
| common_enums::PaymentMethodType::Paypal
| common_enums::PaymentMethodType::Paze
| common_enums::PaymentMethodType::Pix
| common_enums::PaymentMethodType::PaySafeCard
| common_enums::PaymentMethodType::Przelewy24
| common_enums::PaymentMethodType::Pse
| common_enums::PaymentMethodType::RedCompra
| common_enums::PaymentMethodType::RedPagos
| common_enums::PaymentMethodType::SamsungPay
| common_enums::PaymentMethodType::Sepa
| common_enums::PaymentMethodType::SepaBankTransfer
| common_enums::PaymentMethodType::Sofort
| common_enums::PaymentMethodType::Swish
| common_enums::PaymentMethodType::TouchNGo
| common_enums::PaymentMethodType::Trustly
| common_enums::PaymentMethodType::Twint
| common_enums::PaymentMethodType::UpiCollect
| common_enums::PaymentMethodType::UpiIntent
| common_enums::PaymentMethodType::Venmo
| common_enums::PaymentMethodType::Vipps
| common_enums::PaymentMethodType::Walley
| common_enums::PaymentMethodType::WeChatPay
| common_enums::PaymentMethodType::SevenEleven
| common_enums::PaymentMethodType::Lawson
| common_enums::PaymentMethodType::LocalBankTransfer
| common_enums::PaymentMethodType::InstantBankTransfer
| common_enums::PaymentMethodType::MiniStop
| common_enums::PaymentMethodType::FamilyMart
| common_enums::PaymentMethodType::Seicomart
| common_enums::PaymentMethodType::PayEasy
| common_enums::PaymentMethodType::Mifinity
| common_enums::PaymentMethodType::Fps
| common_enums::PaymentMethodType::DuitNow
| common_enums::PaymentMethodType::PromptPay
| common_enums::PaymentMethodType::VietQr
| common_enums::PaymentMethodType::OpenBankingPIS,
) => Err(error_stack::report!(errors::ConnectorError::NotSupported {
message: payment_method_type.to_string(),
connector: "klarna",
})),
}
}
PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect {}) => {
match (payment_experience, payment_method_type) {
(
common_enums::PaymentExperience::RedirectToUrl,
common_enums::PaymentMethodType::Klarna,
) => Ok(format!("{endpoint}checkout/v3/orders",)),
#[cfg(feature = "v1")]
(
common_enums::PaymentExperience::DisplayQrCode
| common_enums::PaymentExperience::DisplayWaitScreen
| common_enums::PaymentExperience::InvokePaymentApp
| common_enums::PaymentExperience::InvokeSdkClient
| common_enums::PaymentExperience::LinkWallet
| common_enums::PaymentExperience::OneClick
| common_enums::PaymentExperience::RedirectToUrl
| common_enums::PaymentExperience::CollectOtp,
common_enums::PaymentMethodType::Ach
| common_enums::PaymentMethodType::Affirm
| common_enums::PaymentMethodType::AfterpayClearpay
| common_enums::PaymentMethodType::Alfamart
| common_enums::PaymentMethodType::AliPay
| common_enums::PaymentMethodType::AliPayHk
| common_enums::PaymentMethodType::Alma
| common_enums::PaymentMethodType::AmazonPay
| common_enums::PaymentMethodType::ApplePay
| common_enums::PaymentMethodType::Atome
| common_enums::PaymentMethodType::Bacs
| common_enums::PaymentMethodType::BancontactCard
| common_enums::PaymentMethodType::Becs
| common_enums::PaymentMethodType::Benefit
| common_enums::PaymentMethodType::Bizum
| common_enums::PaymentMethodType::Blik
| common_enums::PaymentMethodType::Boleto
| common_enums::PaymentMethodType::BcaBankTransfer
| common_enums::PaymentMethodType::BniVa
| common_enums::PaymentMethodType::BriVa
| common_enums::PaymentMethodType::CardRedirect
| common_enums::PaymentMethodType::CimbVa
| common_enums::PaymentMethodType::ClassicReward
| common_enums::PaymentMethodType::Credit
| common_enums::PaymentMethodType::CryptoCurrency
| common_enums::PaymentMethodType::Cashapp
| common_enums::PaymentMethodType::Dana
| common_enums::PaymentMethodType::DanamonVa
| common_enums::PaymentMethodType::Debit
| common_enums::PaymentMethodType::DirectCarrierBilling
| common_enums::PaymentMethodType::Efecty
| common_enums::PaymentMethodType::Eft
| common_enums::PaymentMethodType::Eps
| common_enums::PaymentMethodType::Evoucher
| common_enums::PaymentMethodType::Giropay
| common_enums::PaymentMethodType::Givex
| common_enums::PaymentMethodType::GooglePay
| common_enums::PaymentMethodType::GoPay
| common_enums::PaymentMethodType::Gcash
| common_enums::PaymentMethodType::Ideal
| common_enums::PaymentMethodType::Interac
| common_enums::PaymentMethodType::Indomaret
| common_enums::PaymentMethodType::Klarna
| common_enums::PaymentMethodType::KakaoPay
| common_enums::PaymentMethodType::MandiriVa
| common_enums::PaymentMethodType::Knet
| common_enums::PaymentMethodType::MbWay
| common_enums::PaymentMethodType::MobilePay
| common_enums::PaymentMethodType::Momo
| common_enums::PaymentMethodType::MomoAtm
| common_enums::PaymentMethodType::Multibanco
| common_enums::PaymentMethodType::LocalBankRedirect
| common_enums::PaymentMethodType::OnlineBankingThailand
| common_enums::PaymentMethodType::OnlineBankingCzechRepublic
| common_enums::PaymentMethodType::OnlineBankingFinland
| common_enums::PaymentMethodType::OnlineBankingFpx
| common_enums::PaymentMethodType::OnlineBankingPoland
| common_enums::PaymentMethodType::OnlineBankingSlovakia
| common_enums::PaymentMethodType::Oxxo
| common_enums::PaymentMethodType::PagoEfectivo
| common_enums::PaymentMethodType::PermataBankTransfer
| common_enums::PaymentMethodType::OpenBankingUk
| common_enums::PaymentMethodType::PayBright
| common_enums::PaymentMethodType::Paypal
| common_enums::PaymentMethodType::Paze
| common_enums::PaymentMethodType::Pix
| common_enums::PaymentMethodType::PaySafeCard
| common_enums::PaymentMethodType::Przelewy24
| common_enums::PaymentMethodType::Pse
| common_enums::PaymentMethodType::RedCompra
| common_enums::PaymentMethodType::RedPagos
| common_enums::PaymentMethodType::SamsungPay
| common_enums::PaymentMethodType::Sepa
| common_enums::PaymentMethodType::SepaBankTransfer
| common_enums::PaymentMethodType::Sofort
| common_enums::PaymentMethodType::Swish
| common_enums::PaymentMethodType::TouchNGo
| common_enums::PaymentMethodType::Trustly
| common_enums::PaymentMethodType::Twint
| common_enums::PaymentMethodType::UpiCollect
| common_enums::PaymentMethodType::UpiIntent
| common_enums::PaymentMethodType::Venmo
| common_enums::PaymentMethodType::Vipps
| common_enums::PaymentMethodType::Walley
| common_enums::PaymentMethodType::WeChatPay
| common_enums::PaymentMethodType::SevenEleven
| common_enums::PaymentMethodType::Lawson
| common_enums::PaymentMethodType::LocalBankTransfer
| common_enums::PaymentMethodType::InstantBankTransfer
| common_enums::PaymentMethodType::MiniStop
| common_enums::PaymentMethodType::FamilyMart
| common_enums::PaymentMethodType::Seicomart
| common_enums::PaymentMethodType::PayEasy
| common_enums::PaymentMethodType::Mifinity
| common_enums::PaymentMethodType::Fps
| common_enums::PaymentMethodType::DuitNow
| common_enums::PaymentMethodType::PromptPay
| common_enums::PaymentMethodType::VietQr
| common_enums::PaymentMethodType::OpenBankingPIS,
) => Err(error_stack::report!(errors::ConnectorError::NotSupported {
message: payment_method_type.to_string(),
connector: "klarna",
})),
#[cfg(feature = "v2")]
(
common_enums::PaymentExperience::DisplayQrCode
| common_enums::PaymentExperience::DisplayWaitScreen
| common_enums::PaymentExperience::InvokePaymentApp
| common_enums::PaymentExperience::InvokeSdkClient
| common_enums::PaymentExperience::LinkWallet
| common_enums::PaymentExperience::OneClick
| common_enums::PaymentExperience::RedirectToUrl
| common_enums::PaymentExperience::CollectOtp,
common_enums::PaymentMethodType::Ach
| common_enums::PaymentMethodType::Affirm
| common_enums::PaymentMethodType::AfterpayClearpay
| common_enums::PaymentMethodType::Alfamart
| common_enums::PaymentMethodType::AliPay
| common_enums::PaymentMethodType::AliPayHk
| common_enums::PaymentMethodType::Alma
| common_enums::PaymentMethodType::AmazonPay
| common_enums::PaymentMethodType::ApplePay
| common_enums::PaymentMethodType::Atome
| common_enums::PaymentMethodType::Bacs
| common_enums::PaymentMethodType::BancontactCard
| common_enums::PaymentMethodType::Becs
| common_enums::PaymentMethodType::Benefit
| common_enums::PaymentMethodType::Bizum
| common_enums::PaymentMethodType::Blik
| common_enums::PaymentMethodType::Boleto
| common_enums::PaymentMethodType::BcaBankTransfer
| common_enums::PaymentMethodType::BniVa
| common_enums::PaymentMethodType::BriVa
| common_enums::PaymentMethodType::CardRedirect
| common_enums::PaymentMethodType::CimbVa
| common_enums::PaymentMethodType::ClassicReward
| common_enums::PaymentMethodType::Credit
| common_enums::PaymentMethodType::Card
| common_enums::PaymentMethodType::CryptoCurrency
| common_enums::PaymentMethodType::Cashapp
| common_enums::PaymentMethodType::Dana
| common_enums::PaymentMethodType::DanamonVa
| common_enums::PaymentMethodType::Debit
| common_enums::PaymentMethodType::DirectCarrierBilling
| common_enums::PaymentMethodType::Efecty
| common_enums::PaymentMethodType::Eft
| common_enums::PaymentMethodType::Eps
| common_enums::PaymentMethodType::Evoucher
| common_enums::PaymentMethodType::Giropay
| common_enums::PaymentMethodType::Givex
| common_enums::PaymentMethodType::GooglePay
| common_enums::PaymentMethodType::GoPay
| common_enums::PaymentMethodType::Gcash
| common_enums::PaymentMethodType::Ideal
| common_enums::PaymentMethodType::Interac
| common_enums::PaymentMethodType::Indomaret
| common_enums::PaymentMethodType::Klarna
| common_enums::PaymentMethodType::KakaoPay
| common_enums::PaymentMethodType::MandiriVa
| common_enums::PaymentMethodType::Knet
| common_enums::PaymentMethodType::MbWay
| common_enums::PaymentMethodType::MobilePay
| common_enums::PaymentMethodType::Momo
| common_enums::PaymentMethodType::MomoAtm
| common_enums::PaymentMethodType::Multibanco
| common_enums::PaymentMethodType::LocalBankRedirect
| common_enums::PaymentMethodType::OnlineBankingThailand
| common_enums::PaymentMethodType::OnlineBankingCzechRepublic
| common_enums::PaymentMethodType::OnlineBankingFinland
| common_enums::PaymentMethodType::OnlineBankingFpx
| common_enums::PaymentMethodType::OnlineBankingPoland
| common_enums::PaymentMethodType::OnlineBankingSlovakia
| common_enums::PaymentMethodType::Oxxo
| common_enums::PaymentMethodType::PagoEfectivo
| common_enums::PaymentMethodType::PermataBankTransfer
| common_enums::PaymentMethodType::OpenBankingUk
| common_enums::PaymentMethodType::PayBright
| common_enums::PaymentMethodType::Paypal
| common_enums::PaymentMethodType::Paze
| common_enums::PaymentMethodType::Pix
| common_enums::PaymentMethodType::PaySafeCard
| common_enums::PaymentMethodType::Przelewy24
| common_enums::PaymentMethodType::Pse
| common_enums::PaymentMethodType::RedCompra
| common_enums::PaymentMethodType::RedPagos
| common_enums::PaymentMethodType::SamsungPay
| common_enums::PaymentMethodType::Sepa
| common_enums::PaymentMethodType::SepaBankTransfer
| common_enums::PaymentMethodType::Sofort
| common_enums::PaymentMethodType::Swish
| common_enums::PaymentMethodType::TouchNGo
| common_enums::PaymentMethodType::Trustly
| common_enums::PaymentMethodType::Twint
| common_enums::PaymentMethodType::UpiCollect
| common_enums::PaymentMethodType::UpiIntent
| common_enums::PaymentMethodType::Venmo
| common_enums::PaymentMethodType::Vipps
| common_enums::PaymentMethodType::Walley
| common_enums::PaymentMethodType::WeChatPay
| common_enums::PaymentMethodType::SevenEleven
| common_enums::PaymentMethodType::Lawson
| common_enums::PaymentMethodType::LocalBankTransfer
| common_enums::PaymentMethodType::InstantBankTransfer
| common_enums::PaymentMethodType::MiniStop
| common_enums::PaymentMethodType::FamilyMart
| common_enums::PaymentMethodType::Seicomart
| common_enums::PaymentMethodType::PayEasy
| common_enums::PaymentMethodType::Mifinity
| common_enums::PaymentMethodType::Fps
| common_enums::PaymentMethodType::DuitNow
| common_enums::PaymentMethodType::PromptPay
| common_enums::PaymentMethodType::VietQr
| common_enums::PaymentMethodType::OpenBankingPIS,
) => Err(error_stack::report!(errors::ConnectorError::NotSupported {
message: payment_method_type.to_string(),
connector: "klarna",
})),
}
}
PaymentMethodData::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::OpenBanking(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(report!(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message(req.connector.as_str(),),
)))
}
}
}
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 = klarna::KlarnaRouterData::from((amount, req));
let connector_req = klarna::KlarnaPaymentsRequest::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: klarna::KlarnaAuthResponse = res
.response
.parse_struct("KlarnaPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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 Klarna {
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> {
let order_id = req.request.connector_transaction_id.clone();
let endpoint =
build_region_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
Ok(format!(
"{endpoint}ordermanagement/v1/orders/{order_id}/cancel"
))
}
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> {
logger::debug!("Expected zero bytes response, skipped parsing of the response");
let status = if res.status_code == 204 {
enums::AttemptStatus::Voided
} else {
enums::AttemptStatus::VoidFailed
};
Ok(PaymentsCancelRouterData {
status,
..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::Refund for Klarna {}
impl api::RefundExecute for Klarna {}
impl api::RefundSync for Klarna {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Klarna {
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 order_id = req.request.connector_transaction_id.clone();
let endpoint =
build_region_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
Ok(format!(
"{endpoint}ordermanagement/v1/orders/{order_id}/refunds",
))
}
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 = klarna::KlarnaRouterData::from((amount, req));
let connector_req = klarna::KlarnaRefundRequest::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> {
match res.headers {
Some(headers) => {
let refund_id = get_http_header("Refund-Id", &headers)
.attach_printable("Missing refund id in headers")
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let response = klarna::KlarnaRefundResponse {
refund_id: refund_id.to_owned(),
};
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
None => Err(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable("Expected headers, but received no headers in response")?,
}
}
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 Klarna {
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 refund_id = req.request.get_connector_refund_id()?;
let endpoint =
build_region_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
Ok(format!(
"{endpoint}ordermanagement/v1/orders/{order_id}/refunds/{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)?)
.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: klarna::KlarnaRefundSyncResponse = res
.response
.parse_struct("klarna KlarnaRefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.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 Klarna {
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<'_>,
) -> 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))
}
}
impl ConnectorSpecifications for Klarna {}
| 12,912 | 2,104 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/cashtocode.rs | .rs | pub mod transformers;
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::{PaymentsResponseData, RefundsResponseData},
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,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl ConnectorValidation for Cashtocode {
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(
utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
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<'_>,
) -> 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
}
impl ConnectorSpecifications for Cashtocode {}
| 3,681 | 2,105 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.