id
stringlengths 24
57
| type
stringclasses 1
value | granularity
stringclasses 4
values | content
stringlengths 8.08k
87.1k
| metadata
dict |
|---|---|---|---|---|
large_file_-854675014196548777
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs
</path>
<file>
use cards::CardNumber;
use common_enums::{enums, Currency};
use common_utils::{pii::Email, types::StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{PaymentsAuthorizeData, ResponseId},
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{consts::NO_ERROR_CODE, errors};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Deserializer, Serialize};
use crate::{
types::{
PaymentsCaptureResponseRouterData, PaymentsSyncResponseRouterData,
RefundsResponseRouterData, ResponseRouterData,
},
utils::{CardData, PaymentsAuthorizeRequestData, RefundsRequestData, RouterData as _},
};
pub struct ElavonRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for ElavonRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "lowercase")]
pub enum TransactionType {
CcSale,
CcAuthOnly,
CcComplete,
CcReturn,
TxnQuery,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "UPPERCASE")]
pub enum SyncTransactionType {
Sale,
AuthOnly,
Return,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum ElavonPaymentsRequest {
Card(CardPaymentRequest),
MandatePayment(MandatePaymentRequest),
}
#[derive(Debug, Serialize)]
pub struct CardPaymentRequest {
pub ssl_transaction_type: TransactionType,
pub ssl_account_id: Secret<String>,
pub ssl_user_id: Secret<String>,
pub ssl_pin: Secret<String>,
pub ssl_amount: StringMajorUnit,
pub ssl_card_number: CardNumber,
pub ssl_exp_date: Secret<String>,
pub ssl_cvv2cvc2: Secret<String>,
pub ssl_email: Email,
#[serde(skip_serializing_if = "Option::is_none")]
pub ssl_add_token: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ssl_get_token: Option<String>,
pub ssl_transaction_currency: Currency,
}
#[derive(Debug, Serialize)]
pub struct MandatePaymentRequest {
pub ssl_transaction_type: TransactionType,
pub ssl_account_id: Secret<String>,
pub ssl_user_id: Secret<String>,
pub ssl_pin: Secret<String>,
pub ssl_amount: StringMajorUnit,
pub ssl_email: Email,
pub ssl_token: Secret<String>,
}
impl TryFrom<&ElavonRouterData<&PaymentsAuthorizeRouterData>> for ElavonPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ElavonRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let auth = ElavonAuthType::try_from(&item.router_data.connector_auth_type)?;
if item.router_data.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Card 3DS".to_string(),
connector: "Elavon",
})?
};
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => Ok(Self::Card(CardPaymentRequest {
ssl_transaction_type: match item.router_data.request.is_auto_capture()? {
true => TransactionType::CcSale,
false => TransactionType::CcAuthOnly,
},
ssl_account_id: auth.account_id.clone(),
ssl_user_id: auth.user_id.clone(),
ssl_pin: auth.pin.clone(),
ssl_amount: item.amount.clone(),
ssl_card_number: req_card.card_number.clone(),
ssl_exp_date: req_card.get_expiry_date_as_mmyy()?,
ssl_cvv2cvc2: req_card.card_cvc,
ssl_email: item.router_data.get_billing_email()?,
ssl_add_token: match item.router_data.request.is_mandate_payment() {
true => Some("Y".to_string()),
false => None,
},
ssl_get_token: match item.router_data.request.is_mandate_payment() {
true => Some("Y".to_string()),
false => None,
},
ssl_transaction_currency: item.router_data.request.currency,
})),
PaymentMethodData::MandatePayment => Ok(Self::MandatePayment(MandatePaymentRequest {
ssl_transaction_type: match item.router_data.request.is_auto_capture()? {
true => TransactionType::CcSale,
false => TransactionType::CcAuthOnly,
},
ssl_account_id: auth.account_id.clone(),
ssl_user_id: auth.user_id.clone(),
ssl_pin: auth.pin.clone(),
ssl_amount: item.amount.clone(),
ssl_email: item.router_data.get_billing_email()?,
ssl_token: Secret::new(item.router_data.request.get_connector_mandate_id()?),
})),
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
pub struct ElavonAuthType {
pub(super) account_id: Secret<String>,
pub(super) user_id: Secret<String>,
pub(super) pin: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for ElavonAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
account_id: api_key.to_owned(),
user_id: key1.to_owned(),
pin: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
enum SslResult {
#[serde(rename = "0")]
ImportedBatchFile,
#[serde(other)]
DeclineOrUnauthorized,
}
#[derive(Debug, Clone, Serialize)]
pub struct ElavonPaymentsResponse {
pub result: ElavonResult,
}
#[derive(Debug, Clone, Serialize)]
pub enum ElavonResult {
Success(PaymentResponse),
Error(ElavonErrorResponse),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ElavonErrorResponse {
error_code: Option<String>,
error_message: String,
error_name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentResponse {
ssl_result: SslResult,
ssl_txn_id: String,
ssl_result_message: String,
ssl_token: Option<Secret<String>>,
}
impl<'de> Deserialize<'de> for ElavonPaymentsResponse {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize, Debug)]
#[serde(rename = "txn")]
struct XmlResponse {
// Error fields
#[serde(rename = "errorCode", default)]
error_code: Option<String>,
#[serde(rename = "errorMessage", default)]
error_message: Option<String>,
#[serde(rename = "errorName", default)]
error_name: Option<String>,
// Success fields
#[serde(rename = "ssl_result", default)]
ssl_result: Option<SslResult>,
#[serde(rename = "ssl_txn_id", default)]
ssl_txn_id: Option<String>,
#[serde(rename = "ssl_result_message", default)]
ssl_result_message: Option<String>,
#[serde(rename = "ssl_token", default)]
ssl_token: Option<Secret<String>>,
}
let xml_res = XmlResponse::deserialize(deserializer)?;
let result = match (xml_res.error_message.clone(), xml_res.error_name.clone()) {
(Some(error_message), Some(error_name)) => ElavonResult::Error(ElavonErrorResponse {
error_code: xml_res.error_code.clone(),
error_message,
error_name,
}),
_ => {
if let (Some(ssl_result), Some(ssl_txn_id), Some(ssl_result_message)) = (
xml_res.ssl_result.clone(),
xml_res.ssl_txn_id.clone(),
xml_res.ssl_result_message.clone(),
) {
ElavonResult::Success(PaymentResponse {
ssl_result,
ssl_txn_id,
ssl_result_message,
ssl_token: xml_res.ssl_token.clone(),
})
} else {
return Err(serde::de::Error::custom(
"Invalid Response XML structure - neither error nor success",
));
}
}
};
Ok(Self { result })
}
}
impl<F>
TryFrom<
ResponseRouterData<F, ElavonPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
ElavonPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status =
get_payment_status(&item.response.result, item.data.request.is_auto_capture()?);
let response = match &item.response.result {
ElavonResult::Error(error) => Err(ErrorResponse {
code: error
.error_code
.clone()
.unwrap_or(NO_ERROR_CODE.to_string()),
message: error.error_message.clone(),
reason: Some(error.error_message.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
ElavonResult::Success(response) => {
if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: response.ssl_result_message.clone(),
message: response.ssl_result_message.clone(),
reason: Some(response.ssl_result_message.clone()),
attempt_status: None,
connector_transaction_id: Some(response.ssl_txn_id.clone()),
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.ssl_txn_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(Some(MandateReference {
connector_mandate_id: response
.ssl_token
.as_ref()
.map(|secret| secret.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(response.ssl_txn_id.clone()),
incremental_authorization_allowed: None,
charges: None,
})
}
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub enum TransactionSyncStatus {
PEN, // Pended
OPN, // Unpended / release / open
REV, // Review
STL, // Settled
PST, // Failed due to post-auth rule
FPR, // Failed due to fraud prevention rules
PRE, // Failed due to pre-auth rule
}
#[derive(Debug, Serialize)]
#[serde(rename = "txn")]
pub struct PaymentsCaptureRequest {
pub ssl_transaction_type: TransactionType,
pub ssl_account_id: Secret<String>,
pub ssl_user_id: Secret<String>,
pub ssl_pin: Secret<String>,
pub ssl_amount: StringMajorUnit,
pub ssl_txn_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename = "txn")]
pub struct PaymentsVoidRequest {
pub ssl_transaction_type: TransactionType,
pub ssl_account_id: Secret<String>,
pub ssl_user_id: Secret<String>,
pub ssl_pin: Secret<String>,
pub ssl_txn_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename = "txn")]
pub struct ElavonRefundRequest {
pub ssl_transaction_type: TransactionType,
pub ssl_account_id: Secret<String>,
pub ssl_user_id: Secret<String>,
pub ssl_pin: Secret<String>,
pub ssl_amount: StringMajorUnit,
pub ssl_txn_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename = "txn")]
pub struct SyncRequest {
pub ssl_transaction_type: TransactionType,
pub ssl_account_id: Secret<String>,
pub ssl_user_id: Secret<String>,
pub ssl_pin: Secret<String>,
pub ssl_txn_id: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename = "txn")]
pub struct ElavonSyncResponse {
pub ssl_trans_status: TransactionSyncStatus,
pub ssl_transaction_type: SyncTransactionType,
pub ssl_txn_id: String,
}
impl TryFrom<&RefundSyncRouterData> for SyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> {
let auth = ElavonAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
ssl_txn_id: item.request.get_connector_refund_id()?,
ssl_transaction_type: TransactionType::TxnQuery,
ssl_account_id: auth.account_id.clone(),
ssl_user_id: auth.user_id.clone(),
ssl_pin: auth.pin.clone(),
})
}
}
impl TryFrom<&PaymentsSyncRouterData> for SyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let auth = ElavonAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
ssl_txn_id: item
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
ssl_transaction_type: TransactionType::TxnQuery,
ssl_account_id: auth.account_id.clone(),
ssl_user_id: auth.user_id.clone(),
ssl_pin: auth.pin.clone(),
})
}
}
impl<F> TryFrom<&ElavonRouterData<&RefundsRouterData<F>>> for ElavonRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ElavonRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let auth = ElavonAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
ssl_txn_id: item.router_data.request.connector_transaction_id.clone(),
ssl_amount: item.amount.clone(),
ssl_transaction_type: TransactionType::CcReturn,
ssl_account_id: auth.account_id.clone(),
ssl_user_id: auth.user_id.clone(),
ssl_pin: auth.pin.clone(),
})
}
}
impl TryFrom<&ElavonRouterData<&PaymentsCaptureRouterData>> for PaymentsCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ElavonRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let auth = ElavonAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
ssl_txn_id: item.router_data.request.connector_transaction_id.clone(),
ssl_amount: item.amount.clone(),
ssl_transaction_type: TransactionType::CcComplete,
ssl_account_id: auth.account_id.clone(),
ssl_user_id: auth.user_id.clone(),
ssl_pin: auth.pin.clone(),
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<ElavonSyncResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<ElavonSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: get_sync_status(item.data.status, &item.response),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.ssl_txn_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, ElavonSyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, ElavonSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.ssl_txn_id.clone(),
refund_status: get_refund_status(item.data.request.refund_status, &item.response),
}),
..item.data
})
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<ElavonPaymentsResponse>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<ElavonPaymentsResponse>,
) -> Result<Self, Self::Error> {
let status = map_payment_status(&item.response.result, enums::AttemptStatus::Charged);
let response = match &item.response.result {
ElavonResult::Error(error) => Err(ErrorResponse {
code: error
.error_code
.clone()
.unwrap_or(NO_ERROR_CODE.to_string()),
message: error.error_message.clone(),
reason: Some(error.error_message.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
ElavonResult::Success(response) => {
if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: response.ssl_result_message.clone(),
message: response.ssl_result_message.clone(),
reason: Some(response.ssl_result_message.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.ssl_txn_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(response.ssl_txn_id.clone()),
incremental_authorization_allowed: None,
charges: None,
})
}
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<Execute, ElavonPaymentsResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, ElavonPaymentsResponse>,
) -> Result<Self, Self::Error> {
let status = enums::RefundStatus::from(&item.response.result);
let response = match &item.response.result {
ElavonResult::Error(error) => Err(ErrorResponse {
code: error
.error_code
.clone()
.unwrap_or(NO_ERROR_CODE.to_string()),
message: error.error_message.clone(),
reason: Some(error.error_message.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
ElavonResult::Success(response) => {
if status == enums::RefundStatus::Failure {
Err(ErrorResponse {
code: response.ssl_result_message.clone(),
message: response.ssl_result_message.clone(),
reason: Some(response.ssl_result_message.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: response.ssl_txn_id.clone(),
refund_status: enums::RefundStatus::from(&item.response.result),
})
}
}
};
Ok(Self {
response,
..item.data
})
}
}
trait ElavonResponseValidator {
fn is_successful(&self) -> bool;
}
impl ElavonResponseValidator for ElavonResult {
fn is_successful(&self) -> bool {
matches!(self, Self::Success(response) if response.ssl_result == SslResult::ImportedBatchFile)
}
}
fn map_payment_status(
item: &ElavonResult,
success_status: enums::AttemptStatus,
) -> enums::AttemptStatus {
if item.is_successful() {
success_status
} else {
enums::AttemptStatus::Failure
}
}
impl From<&ElavonResult> for enums::RefundStatus {
fn from(item: &ElavonResult) -> Self {
if item.is_successful() {
Self::Success
} else {
Self::Failure
}
}
}
fn get_refund_status(
prev_status: enums::RefundStatus,
item: &ElavonSyncResponse,
) -> enums::RefundStatus {
match item.ssl_trans_status {
TransactionSyncStatus::REV | TransactionSyncStatus::OPN | TransactionSyncStatus::PEN => {
prev_status
}
TransactionSyncStatus::STL => enums::RefundStatus::Success,
TransactionSyncStatus::PST | TransactionSyncStatus::FPR | TransactionSyncStatus::PRE => {
enums::RefundStatus::Failure
}
}
}
impl From<&ElavonSyncResponse> for enums::AttemptStatus {
fn from(item: &ElavonSyncResponse) -> Self {
match item.ssl_trans_status {
TransactionSyncStatus::REV
| TransactionSyncStatus::OPN
| TransactionSyncStatus::PEN => Self::Pending,
TransactionSyncStatus::STL => match item.ssl_transaction_type {
SyncTransactionType::Sale => Self::Charged,
SyncTransactionType::AuthOnly => Self::Authorized,
SyncTransactionType::Return => Self::Pending,
},
TransactionSyncStatus::PST
| TransactionSyncStatus::FPR
| TransactionSyncStatus::PRE => Self::Failure,
}
}
}
fn get_sync_status(
prev_status: enums::AttemptStatus,
item: &ElavonSyncResponse,
) -> enums::AttemptStatus {
match item.ssl_trans_status {
TransactionSyncStatus::REV | TransactionSyncStatus::OPN | TransactionSyncStatus::PEN => {
prev_status
}
TransactionSyncStatus::STL => match item.ssl_transaction_type {
SyncTransactionType::Sale => enums::AttemptStatus::Charged,
SyncTransactionType::AuthOnly => enums::AttemptStatus::Authorized,
SyncTransactionType::Return => enums::AttemptStatus::Pending,
},
TransactionSyncStatus::PST | TransactionSyncStatus::FPR | TransactionSyncStatus::PRE => {
enums::AttemptStatus::Failure
}
}
}
fn get_payment_status(item: &ElavonResult, is_auto_capture: bool) -> enums::AttemptStatus {
if item.is_successful() {
if is_auto_capture {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
} else {
enums::AttemptStatus::Failure
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5304
}
|
large_file_6010503007113649202
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs
</path>
<file>
#[cfg(feature = "payouts")]
use api_models::{
self,
payouts::{BankRedirect, PayoutMethodData},
};
use common_enums::{enums, Currency};
use common_utils::{
id_type,
pii::{self, Email, IpAddress},
request::Method,
types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankRedirectData, PaymentMethodData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::Execute,
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::PoQuote, router_response_types::PayoutsResponseData,
types::PayoutsRouterData,
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
#[cfg(feature = "payouts")]
use crate::{types::PayoutsResponseRouterData, utils::PayoutsData as _};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, BrowserInformationData, PaymentsAuthorizeRequestData, RouterData as _},
};
pub struct GigadatRouterData<T> {
pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for GigadatRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
const CONNECTOR_BASE_URL: &str = "https://interac.express-connect.com/";
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct GigadatConnectorMetadataObject {
pub site: String,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for GigadatConnectorMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
Ok(metadata)
}
}
// CPI (Combined Pay-in) Request Structure for Gigadat
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GigadatCpiRequest {
pub user_id: id_type::CustomerId,
pub site: String,
pub user_ip: Secret<String, IpAddress>,
pub currency: Currency,
pub amount: FloatMajorUnit,
pub transaction_id: String,
#[serde(rename = "type")]
pub transaction_type: GidadatTransactionType,
pub sandbox: bool,
pub name: Secret<String>,
pub email: Email,
pub mobile: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum GidadatTransactionType {
Cpi,
Eto,
}
impl TryFrom<&GigadatRouterData<&PaymentsAuthorizeRouterData>> for GigadatCpiRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &GigadatRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let metadata: GigadatConnectorMetadataObject =
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankRedirect(BankRedirectData::Interac { .. }) => {
let router_data = item.router_data;
let name = router_data.get_billing_full_name()?;
let email = router_data.get_billing_email()?;
let mobile = router_data.get_billing_phone_number()?;
let currency = item.router_data.request.currency;
let sandbox = match item.router_data.test_mode {
Some(true) => true,
Some(false) | None => false,
};
let user_ip = router_data.request.get_browser_info()?.get_ip_address()?;
Ok(Self {
user_id: router_data.get_customer_id()?,
site: metadata.site,
user_ip,
currency,
amount: item.amount,
transaction_id: router_data.connector_request_reference_id.clone(),
transaction_type: GidadatTransactionType::Cpi,
name,
sandbox,
email,
mobile,
})
}
PaymentMethodData::BankRedirect(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Gigadat"),
))?,
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Gigadat"),
)
.into()),
}
}
}
#[derive(Debug, Clone)]
pub struct GigadatAuthType {
pub campaign_id: Secret<String>,
pub access_token: Secret<String>,
pub security_token: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for GigadatAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
security_token: api_secret.to_owned(),
access_token: api_key.to_owned(),
campaign_id: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigadatPaymentResponse {
pub token: Secret<String>,
pub data: GigadatPaymentData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GigadatPaymentData {
pub transaction_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GigadatPaymentStatus {
StatusInited,
StatusSuccess,
StatusRejected,
StatusRejected1,
StatusExpired,
StatusAborted1,
StatusPending,
StatusFailed,
}
impl From<GigadatPaymentStatus> for enums::AttemptStatus {
fn from(item: GigadatPaymentStatus) -> Self {
match item {
GigadatPaymentStatus::StatusSuccess => Self::Charged,
GigadatPaymentStatus::StatusInited | GigadatPaymentStatus::StatusPending => {
Self::Pending
}
GigadatPaymentStatus::StatusRejected
| GigadatPaymentStatus::StatusExpired
| GigadatPaymentStatus::StatusRejected1
| GigadatPaymentStatus::StatusAborted1
| GigadatPaymentStatus::StatusFailed => Self::Failure,
}
}
}
impl From<GigadatPaymentStatus> for api_models::webhooks::IncomingWebhookEvent {
fn from(item: GigadatPaymentStatus) -> Self {
match item {
GigadatPaymentStatus::StatusSuccess => Self::PaymentIntentSuccess,
GigadatPaymentStatus::StatusFailed
| GigadatPaymentStatus::StatusRejected
| GigadatPaymentStatus::StatusRejected1
| GigadatPaymentStatus::StatusExpired
| GigadatPaymentStatus::StatusAborted1 => Self::PaymentIntentFailure,
GigadatPaymentStatus::StatusInited | GigadatPaymentStatus::StatusPending => {
Self::PaymentIntentProcessing
}
}
}
}
impl TryFrom<String> for GigadatPaymentStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: String) -> Result<Self, Self::Error> {
match value.as_str() {
"STATUS_INITED" => Ok(Self::StatusInited),
"STATUS_SUCCESS" => Ok(Self::StatusSuccess),
"STATUS_REJECTED" => Ok(Self::StatusRejected),
"STATUS_REJECTED1" => Ok(Self::StatusRejected1),
"STATUS_EXPIRED" => Ok(Self::StatusExpired),
"STATUS_ABORTED1" => Ok(Self::StatusAborted1),
"STATUS_PENDING" => Ok(Self::StatusPending),
"STATUS_FAILED" => Ok(Self::StatusFailed),
_ => Err(errors::ConnectorError::WebhookBodyDecodingFailed.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigadatTransactionStatusResponse {
pub status: GigadatPaymentStatus,
}
impl<F, T> TryFrom<ResponseRouterData<F, GigadatPaymentResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, GigadatPaymentResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
// Will be raising a sepearte PR to populate a field connect_base_url in routerData and use it here
let base_url = CONNECTOR_BASE_URL;
let redirect_url = format!(
"{}webflow?transaction={}&token={}",
base_url,
item.data.connector_request_reference_id,
item.response.token.peek()
);
let redirection_data = Some(RedirectForm::Form {
endpoint: redirect_url,
method: Method::Get,
form_fields: Default::default(),
});
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.data.transaction_id),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, GigadatTransactionStatusResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, GigadatTransactionStatusResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct GigadatRefundRequest {
pub amount: FloatMajorUnit,
pub transaction_id: String,
pub campaign_id: Secret<String>,
}
impl<F> TryFrom<&GigadatRouterData<&RefundsRouterData<F>>> for GigadatRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &GigadatRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let auth_type = GigadatAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
amount: item.amount.to_owned(),
transaction_id: item.router_data.request.connector_transaction_id.clone(),
campaign_id: auth_type.campaign_id,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
success: bool,
data: GigadatPaymentData,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = match item.http_code {
200 => enums::RefundStatus::Success,
400 | 401 | 422 => enums::RefundStatus::Failure,
_ => enums::RefundStatus::Pending,
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.data.transaction_id.to_string(),
refund_status,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GigadatPayoutQuoteRequest {
pub amount: FloatMajorUnit,
pub campaign: Secret<String>,
pub currency: Currency,
pub email: Email,
pub mobile: Secret<String>,
pub name: Secret<String>,
pub site: String,
pub transaction_id: String,
#[serde(rename = "type")]
pub transaction_type: GidadatTransactionType,
pub user_id: id_type::CustomerId,
pub user_ip: Secret<String, IpAddress>,
pub sandbox: bool,
}
// Payouts fulfill request transform
#[cfg(feature = "payouts")]
impl TryFrom<&GigadatRouterData<&PayoutsRouterData<PoQuote>>> for GigadatPayoutQuoteRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &GigadatRouterData<&PayoutsRouterData<PoQuote>>,
) -> Result<Self, Self::Error> {
match item.router_data.get_payout_method_data()? {
PayoutMethodData::BankRedirect(BankRedirect::Interac(interac_data)) => {
let metadata: GigadatConnectorMetadataObject =
utils::to_connector_meta_from_secret(
item.router_data.connector_meta_data.clone(),
)
.change_context(
errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
},
)?;
let router_data = item.router_data;
let name = router_data.get_billing_full_name()?;
let email = interac_data.email;
let mobile = router_data.get_billing_phone_number()?;
let currency = item.router_data.request.destination_currency;
let user_ip = router_data.request.get_browser_info()?.get_ip_address()?;
let auth_type = GigadatAuthType::try_from(&item.router_data.connector_auth_type)?;
let sandbox = match item.router_data.test_mode {
Some(true) => true,
Some(false) | None => false,
};
Ok(Self {
user_id: router_data.get_customer_id()?,
site: metadata.site,
user_ip,
currency,
amount: item.amount,
transaction_id: router_data.connector_request_reference_id.clone(),
transaction_type: GidadatTransactionType::Eto,
name,
email,
mobile,
campaign: auth_type.campaign_id,
sandbox,
})
}
PayoutMethodData::Card(_) | PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => {
Err(errors::ConnectorError::NotSupported {
message: "Payment Method Not Supported".to_string(),
connector: "Gigadat",
})?
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigadatPayoutQuoteResponse {
pub token: Secret<String>,
pub data: GigadatPayoutData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GigadatPayoutData {
pub transaction_id: String,
#[serde(rename = "type")]
pub transaction_type: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct GigadatPayoutMeta {
pub token: Secret<String>,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, GigadatPayoutQuoteResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, GigadatPayoutQuoteResponse>,
) -> Result<Self, Self::Error> {
let connector_meta = serde_json::json!(GigadatPayoutMeta {
token: item.response.token,
});
Ok(Self {
response: Ok(PayoutsResponseData {
status: None,
connector_payout_id: Some(item.response.data.transaction_id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: Some(Secret::new(connector_meta)),
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigadatPayoutResponse {
pub id: String,
pub status: GigadatPayoutStatus,
pub data: GigadatPayoutData,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, GigadatPayoutResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, GigadatPayoutResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::from(item.response.status)),
connector_payout_id: Some(item.response.data.transaction_id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigadatPayoutSyncResponse {
pub status: GigadatPayoutStatus,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GigadatPayoutStatus {
StatusInited,
StatusSuccess,
StatusRejected,
StatusRejected1,
StatusExpired,
StatusAborted1,
StatusPending,
StatusFailed,
}
#[cfg(feature = "payouts")]
impl From<GigadatPayoutStatus> for enums::PayoutStatus {
fn from(item: GigadatPayoutStatus) -> Self {
match item {
GigadatPayoutStatus::StatusSuccess => Self::Success,
GigadatPayoutStatus::StatusPending => Self::RequiresFulfillment,
GigadatPayoutStatus::StatusInited => Self::Pending,
GigadatPayoutStatus::StatusRejected
| GigadatPayoutStatus::StatusExpired
| GigadatPayoutStatus::StatusRejected1
| GigadatPayoutStatus::StatusAborted1
| GigadatPayoutStatus::StatusFailed => Self::Failed,
}
}
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, GigadatPayoutSyncResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, GigadatPayoutSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::from(item.response.status)),
connector_payout_id: None,
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct GigadatErrorResponse {
pub err: String,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct GigadatRefundErrorResponse {
pub error: Vec<Error>,
pub message: String,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct Error {
pub code: Option<String>,
pub detail: String,
}
#[derive(Debug, Deserialize)]
pub struct GigadatWebhookQueryParameters {
pub transaction: String,
pub status: GigadatPaymentStatus,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct GigadatWebhookKeyValue {
pub key: String,
pub value: String,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4561
}
|
large_file_8102894706007918090
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/payme/transformers.rs
</path>
<file>
use std::collections::HashMap;
use api_models::enums::{AuthenticationType, PaymentMethod};
use common_enums::enums;
use common_utils::{
pii,
types::{MinorUnit, StringMajorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},
router_flow_types::{Execute, Void},
router_request_types::{PaymentsCancelData, PaymentsPreProcessingData, ResponseId},
router_response_types::{
MandateReference, PaymentsResponseData, PreprocessingResponseId, RedirectForm,
RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{PaymentsCancelResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
utils::{
self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData,
PaymentsCancelRequestData, PaymentsCompleteAuthorizeRequestData,
PaymentsPreProcessingRequestData, PaymentsSyncRequestData, RouterData as OtherRouterData,
},
};
const LANGUAGE: &str = "en";
#[derive(Debug, Serialize)]
pub struct PaymeRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for PaymeRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Serialize)]
pub struct PayRequest {
buyer_name: Secret<String>,
buyer_email: pii::Email,
payme_sale_id: String,
#[serde(flatten)]
card: PaymeCard,
language: String,
}
#[derive(Debug, Serialize)]
pub struct MandateRequest {
currency: enums::Currency,
sale_price: MinorUnit,
transaction_id: String,
product_name: String,
sale_return_url: String,
seller_payme_id: Secret<String>,
sale_callback_url: String,
buyer_key: Secret<String>,
language: String,
}
#[derive(Debug, Serialize)]
pub struct Pay3dsRequest {
buyer_name: Secret<String>,
buyer_email: pii::Email,
buyer_key: Secret<String>,
payme_sale_id: String,
meta_data_jwt: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymePaymentRequest {
MandateRequest(MandateRequest),
PayRequest(PayRequest),
}
#[derive(Debug, Serialize)]
pub struct PaymeQuerySaleRequest {
sale_payme_id: String,
seller_payme_id: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct PaymeQueryTransactionRequest {
payme_transaction_id: String,
seller_payme_id: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct PaymeCard {
credit_card_cvv: Secret<String>,
credit_card_exp: Secret<String>,
credit_card_number: cards::CardNumber,
}
#[derive(Debug, Serialize)]
pub struct CaptureBuyerRequest {
seller_payme_id: Secret<String>,
#[serde(flatten)]
card: PaymeCard,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CaptureBuyerResponse {
buyer_key: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct GenerateSaleRequest {
currency: enums::Currency,
sale_type: SaleType,
sale_price: MinorUnit,
transaction_id: String,
product_name: String,
sale_return_url: String,
seller_payme_id: Secret<String>,
sale_callback_url: String,
sale_payment_method: SalePaymentMethod,
services: Option<ThreeDs>,
language: String,
}
#[derive(Debug, Serialize)]
pub struct ThreeDs {
name: ThreeDsType,
settings: ThreeDsSettings,
}
#[derive(Debug, Serialize)]
pub enum ThreeDsType {
#[serde(rename = "3D Secure")]
ThreeDs,
}
#[derive(Debug, Serialize)]
pub struct ThreeDsSettings {
active: bool,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GenerateSaleResponse {
payme_sale_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PaymePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaymePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
// To handle webhook response
PaymePaymentsResponse::PaymePaySaleResponse(response) => {
Self::try_from(ResponseRouterData {
response,
data: item.data,
http_code: item.http_code,
})
}
// To handle PSync response
PaymePaymentsResponse::SaleQueryResponse(response) => {
Self::try_from(ResponseRouterData {
response,
data: item.data,
http_code: item.http_code,
})
}
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, PaymePaySaleResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaymePaySaleResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = enums::AttemptStatus::from(item.response.sale_status.clone());
let response = if utils::is_payment_failure(status) {
// To populate error message in case of failure
Err(get_pay_sale_error_response((
&item.response,
item.http_code,
)))
} else {
Ok(PaymentsResponseData::try_from(&item.response)?)
};
Ok(Self {
status,
response,
..item.data
})
}
}
fn get_pay_sale_error_response(
(pay_sale_response, http_code): (&PaymePaySaleResponse, u16),
) -> ErrorResponse {
let code = pay_sale_response
.status_error_code
.map(|error_code| error_code.to_string())
.unwrap_or(consts::NO_ERROR_CODE.to_string());
ErrorResponse {
code,
message: pay_sale_response
.status_error_details
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: pay_sale_response.status_error_details.to_owned(),
status_code: http_code,
attempt_status: None,
connector_transaction_id: Some(pay_sale_response.payme_sale_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
impl TryFrom<&PaymePaySaleResponse> for PaymentsResponseData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &PaymePaySaleResponse) -> Result<Self, Self::Error> {
let redirection_data = match value.sale_3ds {
Some(true) => value.redirect_url.clone().map(|url| RedirectForm::Form {
endpoint: url.to_string(),
method: common_utils::request::Method::Get,
form_fields: HashMap::<String, String>::new(),
}),
_ => None,
};
Ok(Self::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(value.payme_sale_id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(value.buyer_key.clone().map(|buyer_key| {
MandateReference {
connector_mandate_id: Some(buyer_key.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}
})),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, SaleQueryResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SaleQueryResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
// Only one element would be present since we are passing one transaction id in the PSync request
let transaction_response = item
.response
.items
.first()
.cloned()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let status = enums::AttemptStatus::from(transaction_response.sale_status.clone());
let response = if utils::is_payment_failure(status) {
// To populate error message in case of failure
Err(get_sale_query_error_response((
&transaction_response,
item.http_code,
)))
} else {
Ok(PaymentsResponseData::from(&transaction_response))
};
Ok(Self {
status,
response,
..item.data
})
}
}
fn get_sale_query_error_response(
(sale_query_response, http_code): (&SaleQuery, u16),
) -> ErrorResponse {
ErrorResponse {
code: sale_query_response
.sale_error_code
.clone()
.unwrap_or(consts::NO_ERROR_CODE.to_string()),
message: sale_query_response
.sale_error_text
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: sale_query_response.sale_error_text.clone(),
status_code: http_code,
attempt_status: None,
connector_transaction_id: Some(sale_query_response.sale_payme_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
impl From<&SaleQuery> for PaymentsResponseData {
fn from(value: &SaleQuery) -> Self {
Self::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(value.sale_payme_id.clone()),
redirection_data: Box::new(None),
// mandate reference will be updated with webhooks only. That has been handled with PaymePaySaleResponse struct
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SaleType {
Sale,
Authorize,
Token,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SalePaymentMethod {
CreditCard,
ApplePay,
}
impl TryFrom<&PaymeRouterData<&PaymentsPreProcessingRouterData>> for GenerateSaleRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaymeRouterData<&PaymentsPreProcessingRouterData>,
) -> Result<Self, Self::Error> {
let sale_type = SaleType::try_from(item.router_data)?;
let seller_payme_id =
PaymeAuthType::try_from(&item.router_data.connector_auth_type)?.seller_payme_id;
let order_details = item.router_data.request.get_order_details()?;
let services = get_services(item.router_data);
let product_name = order_details
.first()
.ok_or_else(utils::missing_field_err("order_details"))?
.product_name
.clone();
let pmd = item
.router_data
.request
.payment_method_data
.to_owned()
.ok_or_else(utils::missing_field_err("payment_method_data"))?;
Ok(Self {
seller_payme_id,
sale_price: item.amount.to_owned(),
currency: item.router_data.request.get_currency()?,
product_name,
sale_payment_method: SalePaymentMethod::try_from(&pmd)?,
sale_type,
transaction_id: item.router_data.payment_id.clone(),
sale_return_url: item.router_data.request.get_router_return_url()?,
sale_callback_url: item.router_data.request.get_webhook_url()?,
language: LANGUAGE.to_string(),
services,
})
}
}
impl TryFrom<&PaymentMethodData> for SalePaymentMethod {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentMethodData) -> Result<Self, Self::Error> {
match item {
PaymentMethodData::Card(_) => Ok(Self::CreditCard),
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::ApplePayThirdPartySdk(_) => Ok(Self::ApplePay),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::BluecodeRedirect {}
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePay(_)
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::ApplePay(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotSupported {
message: "Wallet".to_string(),
connector: "payme",
}
.into()),
},
PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into())
}
}
}
}
impl TryFrom<&PaymeRouterData<&PaymentsAuthorizeRouterData>> for PaymePaymentRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: &PaymeRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payme_request = if value.router_data.request.mandate_id.is_some() {
Self::MandateRequest(MandateRequest::try_from(value)?)
} else {
Self::PayRequest(PayRequest::try_from(value.router_data)?)
};
Ok(payme_request)
}
}
impl TryFrom<&PaymentsSyncRouterData> for PaymeQuerySaleRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let seller_payme_id = PaymeAuthType::try_from(&value.connector_auth_type)?.seller_payme_id;
Ok(Self {
sale_payme_id: value.request.get_connector_transaction_id()?,
seller_payme_id,
})
}
}
impl TryFrom<&RefundSyncRouterData> for PaymeQueryTransactionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &RefundSyncRouterData) -> Result<Self, Self::Error> {
let seller_payme_id = PaymeAuthType::try_from(&value.connector_auth_type)?.seller_payme_id;
Ok(Self {
payme_transaction_id: value
.request
.connector_refund_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?,
seller_payme_id,
})
}
}
impl<F>
utils::ForeignTryFrom<(
ResponseRouterData<
F,
GenerateSaleResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
StringMajorUnit,
)> for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, apple_pay_amount): (
ResponseRouterData<
F,
GenerateSaleResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
StringMajorUnit,
),
) -> Result<Self, Self::Error> {
match item.data.payment_method {
PaymentMethod::Card => {
match item.data.auth_type {
AuthenticationType::NoThreeDs => {
Ok(Self {
// We don't get any status from payme, so defaulting it to pending
// then move to authorize flow
status: enums::AttemptStatus::Pending,
preprocessing_id: Some(item.response.payme_sale_id.to_owned()),
response: Ok(PaymentsResponseData::PreProcessingResponse {
pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(
item.response.payme_sale_id,
),
connector_metadata: None,
session_token: None,
connector_response_reference_id: None,
}),
..item.data
})
}
AuthenticationType::ThreeDs => Ok(Self {
// We don't go to authorize flow in 3ds,
// Response is send directly after preprocessing flow
// redirection data is send to run script along
// status is made authentication_pending to show redirection
status: enums::AttemptStatus::AuthenticationPending,
preprocessing_id: Some(item.response.payme_sale_id.to_owned()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.payme_sale_id.to_owned(),
),
redirection_data: Box::new(Some(RedirectForm::Payme)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
}
}
_ => {
let currency_code = item.data.request.get_currency()?;
let pmd = item.data.request.payment_method_data.to_owned();
let payme_auth_type = PaymeAuthType::try_from(&item.data.connector_auth_type)?;
let session_token = match pmd {
Some(PaymentMethodData::Wallet(WalletData::ApplePayThirdPartySdk(
_,
))) => Some(api_models::payments::SessionToken::ApplePay(Box::new(
api_models::payments::ApplepaySessionTokenResponse {
session_token_data: Some(
api_models::payments::ApplePaySessionResponse::NoSessionResponse(api_models::payments::NullObject),
),
payment_request_data: Some(
api_models::payments::ApplePayPaymentRequest {
country_code: item.data.get_billing_country()?,
currency_code,
total: api_models::payments::AmountInfo {
label: "Apple Pay".to_string(),
total_type: None,
amount: apple_pay_amount,
},
merchant_capabilities: None,
supported_networks: None,
merchant_identifier: None,
required_billing_contact_fields: None,
required_shipping_contact_fields: None,
recurring_payment_request: None,
},
),
connector: "payme".to_string(),
delayed_session_token: true,
sdk_next_action: api_models::payments::SdkNextAction {
next_action: api_models::payments::NextActionCall::Sync,
},
connector_reference_id: Some(item.response.payme_sale_id.to_owned()),
connector_sdk_public_key: Some(
payme_auth_type.payme_public_key.expose(),
),
connector_merchant_id: payme_auth_type
.payme_merchant_id
.map(|mid| mid.expose()),
},
))),
_ => None,
};
Ok(Self {
// We don't get any status from payme, so defaulting it to pending
status: enums::AttemptStatus::Pending,
preprocessing_id: Some(item.response.payme_sale_id.to_owned()),
response: Ok(PaymentsResponseData::PreProcessingResponse {
pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(
item.response.payme_sale_id,
),
connector_metadata: None,
session_token,
connector_response_reference_id: None,
}),
..item.data
})
}
}
}
}
impl TryFrom<&PaymeRouterData<&PaymentsAuthorizeRouterData>> for MandateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymeRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
let seller_payme_id =
PaymeAuthType::try_from(&item.router_data.connector_auth_type)?.seller_payme_id;
let order_details = item.router_data.request.get_order_details()?;
let product_name = order_details
.first()
.ok_or_else(utils::missing_field_err("order_details"))?
.product_name
.clone();
Ok(Self {
currency: item.router_data.request.currency,
sale_price: item.amount.to_owned(),
transaction_id: item.router_data.payment_id.clone(),
product_name,
sale_return_url: item.router_data.request.get_router_return_url()?,
seller_payme_id,
sale_callback_url: item.router_data.request.get_webhook_url()?,
buyer_key: Secret::new(item.router_data.request.get_connector_mandate_id()?),
language: LANGUAGE.to_string(),
})
}
}
impl TryFrom<&PaymentsAuthorizeRouterData> for PayRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = PaymeCard {
credit_card_cvv: req_card.card_cvc.clone(),
credit_card_exp: req_card
.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?,
credit_card_number: req_card.card_number,
};
let buyer_email = item.request.get_email()?;
let buyer_name = item.get_billing_address()?.get_full_name()?;
let payme_sale_id = item.preprocessing_id.to_owned().ok_or(
errors::ConnectorError::MissingConnectorRelatedTransactionID {
id: "payme_sale_id".to_string(),
},
)?;
Ok(Self {
card,
buyer_email,
buyer_name,
payme_sale_id,
language: LANGUAGE.to_string(),
})
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("payme"),
))?
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymeRedirectResponseData {
meta_data: String,
}
impl TryFrom<&PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
Some(PaymentMethodData::Card(_)) => {
let buyer_email = item.request.get_email()?;
let buyer_name = item.get_billing_address()?.get_full_name()?;
let payload_data = item.request.get_redirect_response_payload()?.expose();
let jwt_data: PaymeRedirectResponseData = serde_json::from_value(payload_data)
.change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "meta_data_jwt",
})?;
let payme_sale_id = item
.request
.connector_transaction_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorTransactionID)?;
let pm_token = item.get_payment_method_token()?;
let buyer_key =
match pm_token {
PaymentMethodToken::Token(token) => token,
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Payme"),
)?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Payme"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Payme"))?
}
};
Ok(Self {
buyer_email,
buyer_key,
buyer_name,
payme_sale_id,
meta_data_jwt: Secret::new(jwt_data.meta_data),
})
}
Some(PaymentMethodData::CardRedirect(_))
| Some(PaymentMethodData::Wallet(_))
| Some(PaymentMethodData::PayLater(_))
| Some(PaymentMethodData::BankRedirect(_))
| Some(PaymentMethodData::BankDebit(_))
| Some(PaymentMethodData::BankTransfer(_))
| Some(PaymentMethodData::Crypto(_))
| Some(PaymentMethodData::MandatePayment)
| Some(PaymentMethodData::Reward)
| Some(PaymentMethodData::RealTimePayment(_))
| Some(PaymentMethodData::MobilePayment(_))
| Some(PaymentMethodData::Upi(_))
| Some(PaymentMethodData::Voucher(_))
| Some(PaymentMethodData::GiftCard(_))
| Some(PaymentMethodData::OpenBanking(_))
| Some(PaymentMethodData::CardToken(_))
| Some(PaymentMethodData::NetworkToken(_))
| Some(PaymentMethodData::CardDetailsForNetworkTransactionId(_))
| None => {
Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into())
}
}
}
}
impl TryFrom<&TokenizationRouterData> for CaptureBuyerRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let seller_payme_id =
PaymeAuthType::try_from(&item.connector_auth_type)?.seller_payme_id;
let card = PaymeCard {
credit_card_cvv: req_card.card_cvc.clone(),
credit_card_exp: req_card
.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?,
credit_card_number: req_card.card_number,
};
Ok(Self {
card,
seller_payme_id,
})
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into())
}
}
}
}
// Auth Struct
pub struct PaymeAuthType {
#[allow(dead_code)]
pub(super) payme_public_key: Secret<String>,
pub(super) seller_payme_id: Secret<String>,
pub(super) payme_merchant_id: Option<Secret<String>>,
}
impl TryFrom<&ConnectorAuthType> for PaymeAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
seller_payme_id: api_key.to_owned(),
payme_public_key: key1.to_owned(),
payme_merchant_id: None,
}),
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
seller_payme_id: api_key.to_owned(),
payme_public_key: key1.to_owned(),
payme_merchant_id: Some(api_secret.to_owned()),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<&PaymentsPreProcessingRouterData> for SaleType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> {
let sale_type = if value.request.setup_mandate_details.is_some() {
// First mandate
Self::Token
} else {
// Normal payments
match value.request.is_auto_capture()? {
true => Self::Sale,
false => Self::Authorize,
}
};
Ok(sale_type)
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, strum::Display)]
#[serde(rename_all = "kebab-case")]
pub enum SaleStatus {
Initial,
Completed,
Refunded,
PartialRefund,
Authorized,
Voided,
PartialVoid,
Failed,
Chargeback,
}
impl From<SaleStatus> for enums::AttemptStatus {
fn from(item: SaleStatus) -> Self {
match item {
SaleStatus::Initial => Self::Authorizing,
SaleStatus::Completed => Self::Charged,
SaleStatus::Refunded | SaleStatus::PartialRefund => Self::AutoRefunded,
SaleStatus::Authorized => Self::Authorized,
SaleStatus::Voided | SaleStatus::PartialVoid => Self::Voided,
SaleStatus::Failed => Self::Failure,
SaleStatus::Chargeback => Self::AutoRefunded,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum PaymePaymentsResponse {
PaymePaySaleResponse(PaymePaySaleResponse),
SaleQueryResponse(SaleQueryResponse),
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SaleQueryResponse {
items: Vec<SaleQuery>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SaleQuery {
sale_status: SaleStatus,
sale_payme_id: String,
sale_error_text: Option<String>,
sale_error_code: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymePaySaleResponse {
sale_status: SaleStatus,
payme_sale_id: String,
payme_transaction_id: Option<String>,
buyer_key: Option<Secret<String>>,
status_error_details: Option<String>,
status_error_code: Option<u32>,
sale_3ds: Option<bool>,
redirect_url: Option<Url>,
}
#[derive(Serialize, Deserialize)]
pub struct PaymeMetadata {
payme_transaction_id: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, CaptureBuyerResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CaptureBuyerResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_token: Some(PaymentMethodToken::Token(item.response.buyer_key.clone())),
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.buyer_key.expose(),
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct PaymentCaptureRequest {
payme_sale_id: String,
sale_price: MinorUnit,
}
impl TryFrom<&PaymeRouterData<&PaymentsCaptureRouterData>> for PaymentCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymeRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
if item.router_data.request.minor_amount_to_capture
!= item.router_data.request.minor_payment_amount
{
Err(errors::ConnectorError::NotSupported {
message: "Partial Capture".to_string(),
connector: "Payme",
})?
}
Ok(Self {
payme_sale_id: item.router_data.request.connector_transaction_id.clone(),
sale_price: item.amount,
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
pub struct PaymeRefundRequest {
sale_refund_amount: MinorUnit,
payme_sale_id: String,
seller_payme_id: Secret<String>,
language: String,
}
impl<F> TryFrom<&PaymeRouterData<&RefundsRouterData<F>>> for PaymeRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymeRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let auth_type = PaymeAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
payme_sale_id: item.router_data.request.connector_transaction_id.clone(),
seller_payme_id: auth_type.seller_payme_id,
sale_refund_amount: item.amount.to_owned(),
language: LANGUAGE.to_string(),
})
}
}
impl TryFrom<SaleStatus> for enums::RefundStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(sale_status: SaleStatus) -> Result<Self, Self::Error> {
match sale_status {
SaleStatus::Refunded | SaleStatus::PartialRefund => Ok(Self::Success),
SaleStatus::Failed => Ok(Self::Failure),
SaleStatus::Initial
| SaleStatus::Completed
| SaleStatus::Authorized
| SaleStatus::Voided
| SaleStatus::PartialVoid
| SaleStatus::Chargeback => Err(errors::ConnectorError::ResponseHandlingFailed)?,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaymeRefundResponse {
sale_status: SaleStatus,
payme_transaction_id: Option<String>,
status_error_code: Option<u32>,
}
impl TryFrom<RefundsResponseRouterData<Execute, PaymeRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, PaymeRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::try_from(item.response.sale_status.clone())?;
let response = if utils::is_refund_failure(refund_status) {
let payme_response = &item.response;
let status_error_code = payme_response
.status_error_code
.map(|error_code| error_code.to_string());
Err(ErrorResponse {
code: status_error_code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: status_error_code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: status_error_code,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: payme_response.payme_transaction_id.clone(),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item
.response
.payme_transaction_id
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?,
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct PaymeVoidRequest {
sale_currency: enums::Currency,
payme_sale_id: String,
seller_payme_id: Secret<String>,
language: String,
}
impl TryFrom<&PaymeRouterData<&RouterData<Void, PaymentsCancelData, PaymentsResponseData>>>
for PaymeVoidRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaymeRouterData<&RouterData<Void, PaymentsCancelData, PaymentsResponseData>>,
) -> Result<Self, Self::Error> {
let auth_type = PaymeAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
payme_sale_id: item.router_data.request.connector_transaction_id.clone(),
seller_payme_id: auth_type.seller_payme_id,
sale_currency: item.router_data.request.get_currency()?,
language: LANGUAGE.to_string(),
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaymeVoidResponse {
sale_status: SaleStatus,
payme_transaction_id: Option<String>,
status_error_code: Option<u32>,
}
impl TryFrom<PaymentsCancelResponseRouterData<PaymeVoidResponse>> for PaymentsCancelRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<PaymeVoidResponse>,
) -> Result<Self, Self::Error> {
let status = enums::AttemptStatus::from(item.response.sale_status.clone());
let response = if utils::is_payment_failure(status) {
let payme_response = &item.response;
let status_error_code = payme_response
.status_error_code
.map(|error_code| error_code.to_string());
Err(ErrorResponse {
code: status_error_code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: status_error_code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: status_error_code,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: payme_response.payme_transaction_id.clone(),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
// Since we are not receiving payme_sale_id, we are not populating the transaction response
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymeQueryTransactionResponse {
items: Vec<TransactionQuery>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TransactionQuery {
sale_status: SaleStatus,
payme_transaction_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PaymeQueryTransactionResponse, T, RefundsResponseData>>
for RouterData<F, T, RefundsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaymeQueryTransactionResponse, T, RefundsResponseData>,
) -> Result<Self, Self::Error> {
let pay_sale_response = item
.response
.items
.first()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let refund_status = enums::RefundStatus::try_from(pay_sale_response.sale_status.clone())?;
let response = if utils::is_refund_failure(refund_status) {
Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_string(),
message: consts::NO_ERROR_CODE.to_string(),
reason: None,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(pay_sale_response.payme_transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
refund_status,
connector_refund_id: pay_sale_response.payme_transaction_id.clone(),
})
};
Ok(Self {
response,
..item.data
})
}
}
fn get_services(item: &PaymentsPreProcessingRouterData) -> Option<ThreeDs> {
match item.auth_type {
AuthenticationType::ThreeDs => {
let settings = ThreeDsSettings { active: true };
Some(ThreeDs {
name: ThreeDsType::ThreeDs,
settings,
})
}
AuthenticationType::NoThreeDs => None,
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct PaymeErrorResponse {
pub status_code: u16,
pub status_error_details: String,
pub status_additional_info: serde_json::Value,
pub status_error_code: u32,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum NotifyType {
SaleComplete,
SaleAuthorized,
Refund,
SaleFailure,
SaleChargeback,
SaleChargebackRefund,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct WebhookEventDataResource {
pub sale_status: SaleStatus,
pub payme_signature: Secret<String>,
pub buyer_key: Option<Secret<String>>,
pub notify_type: NotifyType,
pub payme_sale_id: String,
pub payme_transaction_id: String,
pub status_error_details: Option<String>,
pub status_error_code: Option<u32>,
pub price: MinorUnit,
pub currency: enums::Currency,
}
#[derive(Debug, Deserialize)]
pub struct WebhookEventDataResourceEvent {
pub notify_type: NotifyType,
}
#[derive(Debug, Deserialize)]
pub struct WebhookEventDataResourceSignature {
pub payme_signature: Secret<String>,
}
/// This try_from will ensure that webhook body would be properly parsed into PSync response
impl From<WebhookEventDataResource> for PaymePaySaleResponse {
fn from(value: WebhookEventDataResource) -> Self {
Self {
sale_status: value.sale_status,
payme_sale_id: value.payme_sale_id,
payme_transaction_id: Some(value.payme_transaction_id),
buyer_key: value.buyer_key,
sale_3ds: None,
redirect_url: None,
status_error_code: value.status_error_code,
status_error_details: value.status_error_details,
}
}
}
/// This try_from will ensure that webhook body would be properly parsed into RSync response
impl From<WebhookEventDataResource> for PaymeQueryTransactionResponse {
fn from(value: WebhookEventDataResource) -> Self {
let item = TransactionQuery {
sale_status: value.sale_status,
payme_transaction_id: value.payme_transaction_id,
};
Self { items: vec![item] }
}
}
impl From<NotifyType> for api_models::webhooks::IncomingWebhookEvent {
fn from(value: NotifyType) -> Self {
match value {
NotifyType::SaleComplete => Self::PaymentIntentSuccess,
NotifyType::Refund => Self::RefundSuccess,
NotifyType::SaleFailure => Self::PaymentIntentFailure,
NotifyType::SaleChargeback => Self::DisputeOpened,
NotifyType::SaleChargebackRefund => Self::DisputeWon,
NotifyType::SaleAuthorized => Self::EventNotSupported,
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/payme/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 9936
}
|
large_file_-5830402063186533049
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs
</path>
<file>
use std::str::FromStr;
use api_models::payments::{DeviceChannel, ThreeDsCompletionIndicator};
use base64::Engine;
use common_enums::enums;
use common_utils::{consts::BASE64_ENGINE, date_time, ext_traits::OptionExt as _};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, ErrorResponse},
router_flow_types::authentication::{Authentication, PreAuthentication},
router_request_types::{
authentication::{
AuthNFlowType, ChallengeParams, ConnectorAuthenticationRequestData, MessageCategory,
PreAuthNRequestData,
},
BrowserInformation,
},
router_response_types::AuthenticationResponseData,
};
use hyperswitch_interfaces::{api::CurrencyUnit, consts::NO_ERROR_MESSAGE, errors};
use iso_currency::Currency;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::{json, to_string};
use crate::{
types::{ConnectorAuthenticationRouterData, PreAuthNRouterData, ResponseRouterData},
utils::{get_card_details, to_connector_meta, AddressDetailsData, CardData as _},
};
pub struct ThreedsecureioRouterData<T> {
pub amount: String,
pub router_data: T,
}
impl<T> TryFrom<(&CurrencyUnit, enums::Currency, i64, T)> for ThreedsecureioRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(_currency_unit, _currency, amount, item): (&CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
Ok(Self {
amount: amount.to_string(),
router_data: item,
})
}
}
impl<T> TryFrom<(i64, T)> for ThreedsecureioRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, router_data): (i64, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount: amount.to_string(),
router_data,
})
}
}
impl
TryFrom<
ResponseRouterData<
PreAuthentication,
ThreedsecureioPreAuthenticationResponse,
PreAuthNRequestData,
AuthenticationResponseData,
>,
> for PreAuthNRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
PreAuthentication,
ThreedsecureioPreAuthenticationResponse,
PreAuthNRequestData,
AuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
let response = match item.response {
ThreedsecureioPreAuthenticationResponse::Success(pre_authn_response) => {
let three_ds_method_data = json!({
"threeDSServerTransID": pre_authn_response.threeds_server_trans_id,
});
let three_ds_method_data_str = to_string(&three_ds_method_data)
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable("error while constructing three_ds_method_data_str")?;
let three_ds_method_data_base64 = BASE64_ENGINE.encode(three_ds_method_data_str);
let connector_metadata = serde_json::json!(ThreeDSecureIoConnectorMetaData {
ds_start_protocol_version: pre_authn_response.ds_start_protocol_version,
ds_end_protocol_version: pre_authn_response.ds_end_protocol_version,
acs_start_protocol_version: pre_authn_response.acs_start_protocol_version,
acs_end_protocol_version: pre_authn_response.acs_end_protocol_version.clone(),
});
Ok(AuthenticationResponseData::PreAuthNResponse {
threeds_server_transaction_id: pre_authn_response
.threeds_server_trans_id
.clone(),
maximum_supported_3ds_version: common_utils::types::SemanticVersion::from_str(
&pre_authn_response.acs_end_protocol_version,
)
.change_context(errors::ConnectorError::ParsingFailed)?,
connector_authentication_id: pre_authn_response.threeds_server_trans_id,
three_ds_method_data: Some(three_ds_method_data_base64),
three_ds_method_url: pre_authn_response.threeds_method_url,
message_version: common_utils::types::SemanticVersion::from_str(
&pre_authn_response.acs_end_protocol_version,
)
.change_context(errors::ConnectorError::ParsingFailed)?,
connector_metadata: Some(connector_metadata),
directory_server_id: None,
})
}
ThreedsecureioPreAuthenticationResponse::Failure(error_response) => {
Err(ErrorResponse {
code: error_response.error_code,
message: error_response
.error_description
.clone()
.unwrap_or(NO_ERROR_MESSAGE.to_owned()),
reason: error_response.error_description,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
};
Ok(Self {
response,
..item.data.clone()
})
}
}
impl
TryFrom<
ResponseRouterData<
Authentication,
ThreedsecureioAuthenticationResponse,
ConnectorAuthenticationRequestData,
AuthenticationResponseData,
>,
> for ConnectorAuthenticationRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
Authentication,
ThreedsecureioAuthenticationResponse,
ConnectorAuthenticationRequestData,
AuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
let response = match item.response {
ThreedsecureioAuthenticationResponse::Success(response) => {
let creq = serde_json::json!({
"threeDSServerTransID": response.three_dsserver_trans_id,
"acsTransID": response.acs_trans_id,
"messageVersion": response.message_version,
"messageType": "CReq",
"challengeWindowSize": "01",
});
let creq_str = to_string(&creq)
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable("error while constructing creq_str")?;
let creq_base64 = Engine::encode(&BASE64_ENGINE, creq_str)
.trim_end_matches('=')
.to_owned();
Ok(AuthenticationResponseData::AuthNResponse {
trans_status: response.trans_status.clone().into(),
authn_flow_type: if response.trans_status == ThreedsecureioTransStatus::C {
AuthNFlowType::Challenge(Box::new(ChallengeParams {
acs_url: response.acs_url,
challenge_request: Some(creq_base64),
acs_reference_number: Some(response.acs_reference_number.clone()),
acs_trans_id: Some(response.acs_trans_id.clone()),
three_dsserver_trans_id: Some(response.three_dsserver_trans_id),
acs_signed_content: response.acs_signed_content,
challenge_request_key: None,
}))
} else {
AuthNFlowType::Frictionless
},
authentication_value: response.authentication_value,
connector_metadata: None,
ds_trans_id: Some(response.ds_trans_id),
eci: None,
challenge_code: None,
challenge_cancel: None,
challenge_code_reason: None,
message_extension: None,
})
}
ThreedsecureioAuthenticationResponse::Error(err_response) => match *err_response {
ThreedsecureioErrorResponseWrapper::ErrorResponse(resp) => Err(ErrorResponse {
code: resp.error_code,
message: resp
.error_description
.clone()
.unwrap_or(NO_ERROR_MESSAGE.to_owned()),
reason: resp.error_description,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
ThreedsecureioErrorResponseWrapper::ErrorString(error) => Err(ErrorResponse {
code: error.clone(),
message: error.clone(),
reason: Some(error),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
},
};
Ok(Self {
response,
..item.data.clone()
})
}
}
pub struct ThreedsecureioAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for ThreedsecureioAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<&ThreedsecureioRouterData<&ConnectorAuthenticationRouterData>>
for ThreedsecureioAuthenticationRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ThreedsecureioRouterData<&ConnectorAuthenticationRouterData>,
) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
//browser_details are mandatory for Browser flows
let browser_details = match request.browser_details.clone() {
Some(details) => Ok::<Option<BrowserInformation>, Self::Error>(Some(details)),
None => {
if request.device_channel == DeviceChannel::Browser {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "browser_info",
})?
} else {
Ok(None)
}
}
}?;
let card_details = get_card_details(request.payment_method_data.clone(), "threedsecureio")?;
let currency = request
.currency
.map(|currency| currency.to_string())
.ok_or(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("missing field currency")?;
let purchase_currency: Currency = Currency::from_code(¤cy)
.ok_or(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("error while parsing Currency")?;
let billing_address = request.billing_address.address.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "billing_address.address",
},
)?;
let billing_state = billing_address.clone().to_state_code()?;
let billing_country = isocountry::CountryCode::for_alpha2(
&billing_address
.country
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "billing_address.address.country",
})?
.to_string(),
)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Error parsing billing_address.address.country")?;
let connector_meta_data: ThreeDSecureIoMetaData = item
.router_data
.connector_meta_data
.clone()
.parse_value("ThreeDSecureIoMetaData")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let pre_authentication_data = &request.pre_authentication_data;
let sdk_information = match request.device_channel {
DeviceChannel::App => Some(item.router_data.request.sdk_information.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "sdk_information",
},
)?),
DeviceChannel::Browser => None,
};
let (acquirer_bin, acquirer_merchant_id) = pre_authentication_data
.acquirer_bin
.clone()
.zip(pre_authentication_data.acquirer_merchant_id.clone())
.get_required_value("acquirer_details")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "acquirer_details",
})?;
let meta: ThreeDSecureIoConnectorMetaData =
to_connector_meta(request.pre_authentication_data.connector_metadata.clone())?;
let card_holder_name = billing_address.get_optional_full_name();
Ok(Self {
ds_start_protocol_version: meta.ds_start_protocol_version.clone(),
ds_end_protocol_version: meta.ds_end_protocol_version.clone(),
acs_start_protocol_version: meta.acs_start_protocol_version.clone(),
acs_end_protocol_version: meta.acs_end_protocol_version.clone(),
three_dsserver_trans_id: pre_authentication_data
.threeds_server_transaction_id
.clone(),
acct_number: card_details.card_number.clone(),
notification_url: request
.return_url
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("missing return_url")?,
three_dscomp_ind: ThreeDSecureIoThreeDsCompletionIndicator::from(
request.threeds_method_comp_ind.clone(),
),
three_dsrequestor_url: request.three_ds_requestor_url.clone(),
acquirer_bin,
acquirer_merchant_id,
card_expiry_date: card_details.get_expiry_date_as_yymm()?.expose(),
bill_addr_city: billing_address
.city
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "billing_address.address.city",
})?
.to_string(),
bill_addr_country: billing_country.numeric_id().to_string().into(),
bill_addr_line1: billing_address.line1.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "billing_address.address.line1",
},
)?,
bill_addr_post_code: billing_address.zip.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "billing_address.address.zip",
},
)?,
bill_addr_state: billing_state,
// Indicates the type of Authentication request, "01" for Payment transaction
three_dsrequestor_authentication_ind: "01".to_string(),
device_channel: match item.router_data.request.device_channel.clone() {
DeviceChannel::App => "01",
DeviceChannel::Browser => "02",
}
.to_string(),
message_category: match item.router_data.request.message_category.clone() {
MessageCategory::Payment => "01",
MessageCategory::NonPayment => "02",
}
.to_string(),
browser_javascript_enabled: browser_details
.as_ref()
.and_then(|details| details.java_script_enabled),
browser_accept_header: browser_details
.as_ref()
.and_then(|details| details.accept_header.clone()),
browser_ip: browser_details
.clone()
.and_then(|details| details.ip_address.map(|ip| Secret::new(ip.to_string()))),
browser_java_enabled: browser_details
.as_ref()
.and_then(|details| details.java_enabled),
browser_language: browser_details
.as_ref()
.and_then(|details| details.language.clone()),
browser_color_depth: browser_details
.as_ref()
.and_then(|details| details.color_depth.map(|a| a.to_string())),
browser_screen_height: browser_details
.as_ref()
.and_then(|details| details.screen_height.map(|a| a.to_string())),
browser_screen_width: browser_details
.as_ref()
.and_then(|details| details.screen_width.map(|a| a.to_string())),
browser_tz: browser_details
.as_ref()
.and_then(|details| details.time_zone.map(|a| a.to_string())),
browser_user_agent: browser_details
.as_ref()
.and_then(|details| details.user_agent.clone().map(|a| a.to_string())),
mcc: connector_meta_data.mcc,
merchant_country_code: connector_meta_data.merchant_country_code,
merchant_name: connector_meta_data.merchant_name,
message_type: "AReq".to_string(),
message_version: pre_authentication_data.message_version.to_string(),
purchase_amount: item.amount.clone(),
purchase_currency: purchase_currency.numeric().to_string(),
trans_type: "01".to_string(),
purchase_exponent: purchase_currency
.exponent()
.ok_or(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("missing purchase_exponent")?
.to_string(),
purchase_date: date_time::DateTime::<date_time::YYYYMMDDHHmmss>::from(date_time::now())
.to_string(),
sdk_app_id: sdk_information
.as_ref()
.map(|sdk_info| sdk_info.sdk_app_id.clone()),
sdk_enc_data: sdk_information
.as_ref()
.map(|sdk_info| sdk_info.sdk_enc_data.clone()),
sdk_ephem_pub_key: sdk_information
.as_ref()
.map(|sdk_info| sdk_info.sdk_ephem_pub_key.clone()),
sdk_reference_number: sdk_information
.as_ref()
.map(|sdk_info| sdk_info.sdk_reference_number.clone()),
sdk_trans_id: sdk_information
.as_ref()
.map(|sdk_info| sdk_info.sdk_trans_id.clone()),
sdk_max_timeout: sdk_information
.as_ref()
.map(|sdk_info| sdk_info.sdk_max_timeout.to_string()),
device_render_options: match request.device_channel {
DeviceChannel::App => Some(DeviceRenderOptions {
// SDK Interface types that the device supports for displaying specific challenge user interfaces within the SDK, 01 for Native
sdk_interface: "01".to_string(),
// UI types that the device supports for displaying specific challenge user interfaces within the SDK, 01 for Text
sdk_ui_type: vec!["01".to_string()],
}),
DeviceChannel::Browser => None,
},
cardholder_name: card_holder_name,
email: request.email.clone(),
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreedsecureioErrorResponse {
pub error_code: String,
pub error_component: Option<String>,
pub error_description: Option<String>,
pub error_detail: Option<String>,
pub error_message_type: Option<String>,
pub message_type: Option<String>,
pub message_version: Option<String>,
pub three_dsserver_trans_id: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ThreedsecureioErrorResponseWrapper {
ErrorResponse(ThreedsecureioErrorResponse),
ErrorString(String),
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ThreedsecureioAuthenticationResponse {
Success(Box<ThreedsecureioAuthenticationSuccessResponse>),
Error(Box<ThreedsecureioErrorResponseWrapper>),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreedsecureioAuthenticationSuccessResponse {
#[serde(rename = "acsChallengeMandated")]
pub acs_challenge_mandated: Option<String>,
#[serde(rename = "acsOperatorID")]
pub acs_operator_id: Option<String>,
#[serde(rename = "acsReferenceNumber")]
pub acs_reference_number: String,
#[serde(rename = "acsTransID")]
pub acs_trans_id: String,
#[serde(rename = "acsURL")]
pub acs_url: Option<url::Url>,
#[serde(rename = "authenticationType")]
pub authentication_type: Option<String>,
#[serde(rename = "dsReferenceNumber")]
pub ds_reference_number: String,
#[serde(rename = "dsTransID")]
pub ds_trans_id: String,
#[serde(rename = "messageType")]
pub message_type: Option<String>,
#[serde(rename = "messageVersion")]
pub message_version: String,
#[serde(rename = "threeDSServerTransID")]
pub three_dsserver_trans_id: String,
#[serde(rename = "transStatus")]
pub trans_status: ThreedsecureioTransStatus,
#[serde(rename = "acsSignedContent")]
pub acs_signed_content: Option<String>,
#[serde(rename = "authenticationValue")]
pub authentication_value: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum ThreeDSecureIoThreeDsCompletionIndicator {
Y,
N,
U,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreedsecureioAuthenticationRequest {
pub ds_start_protocol_version: String,
pub ds_end_protocol_version: String,
pub acs_start_protocol_version: String,
pub acs_end_protocol_version: String,
pub three_dsserver_trans_id: String,
pub acct_number: cards::CardNumber,
pub notification_url: String,
pub three_dscomp_ind: ThreeDSecureIoThreeDsCompletionIndicator,
pub three_dsrequestor_url: String,
pub acquirer_bin: String,
pub acquirer_merchant_id: String,
pub card_expiry_date: String,
pub bill_addr_city: String,
pub bill_addr_country: Secret<String>,
pub bill_addr_line1: Secret<String>,
pub bill_addr_post_code: Secret<String>,
pub bill_addr_state: Secret<String>,
pub email: Option<common_utils::pii::Email>,
pub three_dsrequestor_authentication_ind: String,
pub cardholder_name: Option<Secret<String>>,
pub device_channel: String,
pub browser_javascript_enabled: Option<bool>,
pub browser_accept_header: Option<String>,
pub browser_ip: Option<Secret<String, common_utils::pii::IpAddress>>,
pub browser_java_enabled: Option<bool>,
pub browser_language: Option<String>,
pub browser_color_depth: Option<String>,
pub browser_screen_height: Option<String>,
pub browser_screen_width: Option<String>,
pub browser_tz: Option<String>,
pub browser_user_agent: Option<String>,
pub sdk_app_id: Option<String>,
pub sdk_enc_data: Option<String>,
pub sdk_ephem_pub_key: Option<std::collections::HashMap<String, String>>,
pub sdk_reference_number: Option<String>,
pub sdk_trans_id: Option<String>,
pub mcc: String,
pub merchant_country_code: String,
pub merchant_name: String,
pub message_category: String,
pub message_type: String,
pub message_version: String,
pub purchase_amount: String,
pub purchase_currency: String,
pub purchase_exponent: String,
pub purchase_date: String,
pub trans_type: String,
pub sdk_max_timeout: Option<String>,
pub device_render_options: Option<DeviceRenderOptions>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ThreeDSecureIoMetaData {
pub mcc: String,
pub merchant_country_code: String,
pub merchant_name: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ThreeDSecureIoConnectorMetaData {
pub ds_start_protocol_version: String,
pub ds_end_protocol_version: String,
pub acs_start_protocol_version: String,
pub acs_end_protocol_version: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeviceRenderOptions {
pub sdk_interface: String,
pub sdk_ui_type: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreedsecureioPreAuthenticationRequest {
acct_number: cards::CardNumber,
ds: Option<DirectoryServer>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreedsecureioPostAuthenticationRequest {
pub three_ds_server_trans_id: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreedsecureioPostAuthenticationResponse {
pub authentication_value: Option<Secret<String>>,
pub trans_status: ThreedsecureioTransStatus,
pub eci: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub enum ThreedsecureioTransStatus {
/// Authentication/ Account Verification Successful
Y,
/// Not Authenticated /Account Not Verified; Transaction denied
N,
/// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in ARes or RReq
U,
/// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided
A,
/// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted.
R,
C,
}
impl From<ThreeDsCompletionIndicator> for ThreeDSecureIoThreeDsCompletionIndicator {
fn from(value: ThreeDsCompletionIndicator) -> Self {
match value {
ThreeDsCompletionIndicator::Success => Self::Y,
ThreeDsCompletionIndicator::Failure => Self::N,
ThreeDsCompletionIndicator::NotAvailable => Self::U,
}
}
}
impl From<ThreedsecureioTransStatus> for common_enums::TransactionStatus {
fn from(value: ThreedsecureioTransStatus) -> Self {
match value {
ThreedsecureioTransStatus::Y => Self::Success,
ThreedsecureioTransStatus::N => Self::Failure,
ThreedsecureioTransStatus::U => Self::VerificationNotPerformed,
ThreedsecureioTransStatus::A => Self::NotVerified,
ThreedsecureioTransStatus::R => Self::Rejected,
ThreedsecureioTransStatus::C => Self::ChallengeRequired,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum DirectoryServer {
Standin,
Visa,
Mastercard,
Jcb,
Upi,
Amex,
Protectbuy,
Sbn,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ThreedsecureioPreAuthenticationResponse {
Success(Box<ThreedsecureioPreAuthenticationResponseData>),
Failure(Box<ThreedsecureioErrorResponse>),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreedsecureioPreAuthenticationResponseData {
pub ds_start_protocol_version: String,
pub ds_end_protocol_version: String,
pub acs_start_protocol_version: String,
pub acs_end_protocol_version: String,
#[serde(rename = "threeDSMethodURL")]
pub threeds_method_url: Option<String>,
#[serde(rename = "threeDSServerTransID")]
pub threeds_server_trans_id: String,
pub scheme: Option<String>,
pub message_type: Option<String>,
}
impl TryFrom<&ThreedsecureioRouterData<&PreAuthNRouterData>>
for ThreedsecureioPreAuthenticationRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: &ThreedsecureioRouterData<&PreAuthNRouterData>,
) -> Result<Self, Self::Error> {
let router_data = value.router_data;
Ok(Self {
acct_number: router_data.request.card.card_number.clone(),
ds: None,
})
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5779
}
|
large_file_-3596741344949106
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs
</path>
<file>
use common_utils::{
crypto::{self, GenerateDigest},
errors::ParsingError,
pii,
request::Method,
types::{AmountConvertor, MinorUnit, StringMinorUnit, StringMinorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},
router_flow_types::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefreshTokenRouterData, RefundExecuteRouterData, RefundsRouterData,
TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
consts::{self, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use rand::distributions::DistString;
use serde::{Deserialize, Serialize};
use url::Url;
use super::{
requests::{
self, ApmProvider, GlobalPayRouterData, GlobalpayCancelRouterData,
GlobalpayPaymentsRequest, GlobalpayRefreshTokenRequest, Initiator, PaymentMethodData,
Sequence, StoredCredential,
},
response::{GlobalpayPaymentStatus, GlobalpayPaymentsResponse, GlobalpayRefreshTokenResponse},
};
use crate::{
connectors::globalpay::{
requests::CommonPaymentMethodData, response::GlobalpayPaymentMethodsResponse,
},
types::{PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, construct_captures_response_hashmap, CardData, ForeignTryFrom,
MultipleCaptureSyncResponse, PaymentMethodTokenizationRequestData,
PaymentsAuthorizeRequestData, RouterData as _, WalletData,
},
};
impl<T> From<(StringMinorUnit, T)> for GlobalPayRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
impl<T> From<(Option<StringMinorUnit>, T)> for GlobalpayCancelRouterData<T> {
fn from((amount, item): (Option<StringMinorUnit>, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
type Error = error_stack::Report<errors::ConnectorError>;
#[derive(Debug, Serialize, Deserialize)]
pub struct GlobalPayMeta {
account_name: Secret<String>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for GlobalPayMeta {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
impl TryFrom<&GlobalPayRouterData<&PaymentsAuthorizeRouterData>> for GlobalpayPaymentsRequest {
type Error = Error;
fn try_from(
item: &GlobalPayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if item.router_data.is_three_ds() {
return Err(errors::ConnectorError::NotSupported {
message: "3DS flow".to_string(),
connector: "Globalpay",
}
.into());
}
let metadata = GlobalPayMeta::try_from(&item.router_data.connector_meta_data)?;
let account_name = metadata.account_name;
let (initiator, stored_credential, connector_mandate_id) =
if item.router_data.request.is_mandate_payment() {
let connector_mandate_id =
item.router_data
.request
.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_ids,
)) => connector_mandate_ids.get_connector_mandate_id(),
_ => None,
});
let initiator = Some(match item.router_data.request.off_session {
Some(true) => Initiator::Merchant,
_ => Initiator::Payer,
});
let stored_credential = Some(StoredCredential {
model: Some(if connector_mandate_id.is_some() {
requests::Model::Recurring
} else {
requests::Model::Unscheduled
}),
sequence: Some(if connector_mandate_id.is_some() {
Sequence::Subsequent
} else {
Sequence::First
}),
});
(initiator, stored_credential, connector_mandate_id)
} else {
(None, None, None)
};
let payment_method = match &item.router_data.request.payment_method_data {
payment_method_data::PaymentMethodData::Card(ccard) => {
requests::GlobalPayPaymentMethodData::Common(CommonPaymentMethodData {
payment_method_data: PaymentMethodData::Card(requests::Card {
number: ccard.card_number.clone(),
expiry_month: ccard.card_exp_month.clone(),
expiry_year: ccard.get_card_expiry_year_2_digit()?,
cvv: ccard.card_cvc.clone(),
}),
entry_mode: Default::default(),
})
}
payment_method_data::PaymentMethodData::Wallet(wallet_data) => {
requests::GlobalPayPaymentMethodData::Common(CommonPaymentMethodData {
payment_method_data: get_wallet_data(wallet_data)?,
entry_mode: Default::default(),
})
}
payment_method_data::PaymentMethodData::BankRedirect(bank_redirect) => {
requests::GlobalPayPaymentMethodData::Common(CommonPaymentMethodData {
payment_method_data: PaymentMethodData::try_from(bank_redirect)?,
entry_mode: Default::default(),
})
}
payment_method_data::PaymentMethodData::MandatePayment => {
requests::GlobalPayPaymentMethodData::Mandate(requests::MandatePaymentMethodData {
entry_mode: Default::default(),
id: connector_mandate_id,
})
}
_ => Err(errors::ConnectorError::NotImplemented(
"Payment methods".to_string(),
))?,
};
Ok(Self {
account_name,
amount: Some(item.amount.to_owned()),
currency: item.router_data.request.currency.to_string(),
reference: item.router_data.connector_request_reference_id.to_string(),
country: item.router_data.get_billing_country()?,
capture_mode: Some(requests::CaptureMode::from(
item.router_data.request.capture_method,
)),
payment_method,
notifications: Some(requests::Notifications {
return_url: get_return_url(item.router_data),
status_url: item.router_data.request.webhook_url.clone(),
cancel_url: get_return_url(item.router_data),
}),
stored_credential,
channel: Default::default(),
initiator,
})
}
}
impl TryFrom<&GlobalPayRouterData<&PaymentsCaptureRouterData>>
for requests::GlobalpayCaptureRequest
{
type Error = Error;
fn try_from(
value: &GlobalPayRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: Some(value.amount.to_owned()),
capture_sequence: value
.router_data
.request
.multiple_capture_data
.clone()
.map(|mcd| {
if mcd.capture_sequence == 1 {
Sequence::First
} else {
Sequence::Subsequent
}
}),
reference: value
.router_data
.request
.multiple_capture_data
.as_ref()
.map(|mcd| mcd.capture_reference.clone()),
})
}
}
impl TryFrom<&TokenizationRouterData> for requests::GlobalPayPaymentMethodsRequest {
type Error = Error;
fn try_from(item: &TokenizationRouterData) -> Result<Self, Self::Error> {
if !item.request.is_mandate_payment() {
return Err(errors::ConnectorError::FlowNotSupported {
flow: "Tokenization apart from Mandates".to_string(),
connector: "Globalpay".to_string(),
}
.into());
}
Ok(Self {
reference: item.connector_request_reference_id.clone(),
usage_mode: Some(requests::UsageMode::Multiple),
card: match &item.request.payment_method_data {
payment_method_data::PaymentMethodData::Card(card_data) => Some(requests::Card {
number: card_data.card_number.clone(),
expiry_month: card_data.card_exp_month.clone(),
expiry_year: card_data.get_card_expiry_year_2_digit()?,
cvv: card_data.card_cvc.clone(),
}),
_ => None,
},
})
}
}
impl TryFrom<&GlobalpayCancelRouterData<&PaymentsCancelRouterData>>
for requests::GlobalpayCancelRequest
{
type Error = Error;
fn try_from(
value: &GlobalpayCancelRouterData<&PaymentsCancelRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: value.amount.clone(),
})
}
}
pub struct GlobalpayAuthType {
pub app_id: Secret<String>,
pub key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for GlobalpayAuthType {
type Error = Error;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
app_id: key1.to_owned(),
key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<GlobalpayRefreshTokenResponse> for AccessToken {
type Error = error_stack::Report<ParsingError>;
fn try_from(item: GlobalpayRefreshTokenResponse) -> Result<Self, Self::Error> {
Ok(Self {
token: item.token,
expires: item.seconds_to_expire,
})
}
}
impl TryFrom<&RefreshTokenRouterData> for GlobalpayRefreshTokenRequest {
type Error = Error;
fn try_from(item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
let globalpay_auth = GlobalpayAuthType::try_from(&item.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)
.attach_printable("Could not convert connector_auth to globalpay_auth")?;
let nonce = rand::distributions::Alphanumeric.sample_string(&mut rand::thread_rng(), 12);
let nonce_with_api_key = format!("{}{}", nonce, globalpay_auth.key.peek());
let secret_vec = crypto::Sha512
.generate_digest(nonce_with_api_key.as_bytes())
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("error creating request nonce")?;
let secret = hex::encode(secret_vec);
Ok(Self {
app_id: globalpay_auth.app_id,
nonce: Secret::new(nonce),
secret: Secret::new(secret),
grant_type: "client_credentials".to_string(),
})
}
}
impl From<GlobalpayPaymentStatus> for common_enums::AttemptStatus {
fn from(item: GlobalpayPaymentStatus) -> Self {
match item {
GlobalpayPaymentStatus::Captured | GlobalpayPaymentStatus::Funded => Self::Charged,
GlobalpayPaymentStatus::Declined | GlobalpayPaymentStatus::Rejected => Self::Failure,
GlobalpayPaymentStatus::Preauthorized => Self::Authorized,
GlobalpayPaymentStatus::Reversed => Self::Voided,
GlobalpayPaymentStatus::Initiated => Self::AuthenticationPending,
GlobalpayPaymentStatus::Pending => Self::Pending,
}
}
}
impl From<GlobalpayPaymentStatus> for common_enums::RefundStatus {
fn from(item: GlobalpayPaymentStatus) -> Self {
match item {
GlobalpayPaymentStatus::Captured | GlobalpayPaymentStatus::Funded => Self::Success,
GlobalpayPaymentStatus::Declined | GlobalpayPaymentStatus::Rejected => Self::Failure,
GlobalpayPaymentStatus::Initiated | GlobalpayPaymentStatus::Pending => Self::Pending,
_ => Self::Pending,
}
}
}
impl From<Option<common_enums::CaptureMethod>> for requests::CaptureMode {
fn from(capture_method: Option<common_enums::CaptureMethod>) -> Self {
match capture_method {
Some(common_enums::CaptureMethod::Manual) => Self::Later,
Some(common_enums::CaptureMethod::ManualMultiple) => Self::Multiple,
_ => Self::Auto,
}
}
}
// }
impl<F, T> TryFrom<ResponseRouterData<F, GlobalpayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, GlobalpayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = common_enums::AttemptStatus::from(item.response.status);
let redirect_url = item
.response
.payment_method
.as_ref()
.and_then(|payment_method| {
payment_method
.apm
.as_ref()
.and_then(|apm| apm.redirect_url.as_ref())
})
.filter(|redirect_str| !redirect_str.is_empty())
.map(|url| {
Url::parse(url).change_context(errors::ConnectorError::FailedToObtainIntegrationUrl)
})
.transpose()?;
let redirection_data = redirect_url.map(|url| RedirectForm::from((url, Method::Get)));
let payment_method_token = item.data.get_payment_method_token();
let status_code = item.http_code;
let mandate_reference = payment_method_token.ok().and_then(|token| match token {
PaymentMethodToken::Token(token_string) => Some(MandateReference {
connector_mandate_id: Some(token_string.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}),
_ => None,
});
let response = match status {
common_enums::AttemptStatus::Failure => Err(Box::new(ErrorResponse {
message: item
.response
.payment_method
.as_ref()
.and_then(|payment_method| payment_method.message.clone())
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
code: item
.response
.payment_method
.as_ref()
.and_then(|payment_method| payment_method.result.clone())
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
reason: item
.response
.payment_method
.as_ref()
.and_then(|payment_method| payment_method.message.clone()),
status_code,
attempt_status: Some(status),
connector_transaction_id: Some(item.response.id.clone()),
network_decline_code: item
.response
.payment_method
.as_ref()
.and_then(|payment_method| payment_method.result.clone()),
network_advice_code: None,
network_error_message: item
.response
.payment_method
.as_ref()
.and_then(|payment_method| payment_method.message.clone()),
connector_metadata: None,
})),
_ => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.reference.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
};
Ok(Self {
status,
response: response.map_err(|err| *err),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, GlobalpayPaymentMethodsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, GlobalpayPaymentMethodsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let token = item
.response
.payment_method_token_id
.clone()
.unwrap_or_default();
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: token.expose(),
}),
..item.data
})
}
}
impl
ForeignTryFrom<(
PaymentsSyncResponseRouterData<GlobalpayPaymentsResponse>,
bool,
)> for PaymentsSyncRouterData
{
type Error = Error;
fn foreign_try_from(
(value, is_multiple_capture_sync): (
PaymentsSyncResponseRouterData<GlobalpayPaymentsResponse>,
bool,
),
) -> Result<Self, Self::Error> {
if is_multiple_capture_sync {
let capture_sync_response_list =
construct_captures_response_hashmap(vec![value.response])?;
Ok(Self {
response: Ok(PaymentsResponseData::MultipleCaptureResponse {
capture_sync_response_list,
}),
..value.data
})
} else {
Self::try_from(value)
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, GlobalpayRefreshTokenResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<ParsingError>;
fn try_from(
item: ResponseRouterData<F, GlobalpayRefreshTokenResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.token,
expires: item.response.seconds_to_expire,
}),
..item.data
})
}
}
impl<F> TryFrom<&GlobalPayRouterData<&RefundsRouterData<F>>> for requests::GlobalpayRefundRequest {
type Error = Error;
fn try_from(item: &GlobalPayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
impl TryFrom<RefundsResponseRouterData<Execute, GlobalpayPaymentsResponse>>
for RefundExecuteRouterData
{
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<Execute, GlobalpayPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status: common_enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, GlobalpayPaymentsResponse>>
for RefundsRouterData<RSync>
{
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<RSync, GlobalpayPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status: common_enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct GlobalpayErrorResponse {
pub error_code: String,
pub detailed_error_code: String,
pub detailed_error_description: String,
}
fn get_return_url(item: &PaymentsAuthorizeRouterData) -> Option<String> {
match item.request.payment_method_data.clone() {
payment_method_data::PaymentMethodData::Wallet(
payment_method_data::WalletData::PaypalRedirect(_),
) => {
// Return URL handling for PayPal via Globalpay:
// - PayPal inconsistency: Return URLs work with HTTP, but cancel URLs require HTTPS
// - Local development: When testing locally, expose your server via HTTPS and replace
// the base URL with an HTTPS URL to ensure proper cancellation flow
// - Refer to commit 6499d429da87 for more information
item.request.complete_authorize_url.clone()
}
_ => item.request.router_return_url.clone(),
}
}
fn get_wallet_data(
wallet_data: &payment_method_data::WalletData,
) -> Result<PaymentMethodData, Error> {
match wallet_data {
payment_method_data::WalletData::PaypalRedirect(_) => {
Ok(PaymentMethodData::Apm(requests::Apm {
provider: Some(ApmProvider::Paypal),
}))
}
payment_method_data::WalletData::GooglePay(_) => {
Ok(PaymentMethodData::DigitalWallet(requests::DigitalWallet {
provider: Some(requests::DigitalWalletProvider::PayByGoogle),
payment_token: wallet_data.get_wallet_token_as_json("Google Pay".to_string())?,
}))
}
_ => Err(errors::ConnectorError::NotImplemented(
"Payment method".to_string(),
))?,
}
}
impl TryFrom<&payment_method_data::BankRedirectData> for PaymentMethodData {
type Error = Error;
fn try_from(value: &payment_method_data::BankRedirectData) -> Result<Self, Self::Error> {
match value {
payment_method_data::BankRedirectData::Eps { .. } => Ok(Self::Apm(requests::Apm {
provider: Some(ApmProvider::Eps),
})),
payment_method_data::BankRedirectData::Giropay { .. } => Ok(Self::Apm(requests::Apm {
provider: Some(ApmProvider::Giropay),
})),
payment_method_data::BankRedirectData::Ideal { .. } => Ok(Self::Apm(requests::Apm {
provider: Some(ApmProvider::Ideal),
})),
payment_method_data::BankRedirectData::Sofort { .. } => Ok(Self::Apm(requests::Apm {
provider: Some(ApmProvider::Sofort),
})),
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
impl MultipleCaptureSyncResponse for GlobalpayPaymentsResponse {
fn get_connector_capture_id(&self) -> String {
self.id.clone()
}
fn get_capture_attempt_status(&self) -> common_enums::AttemptStatus {
common_enums::AttemptStatus::from(self.status)
}
fn is_capture_response(&self) -> bool {
true
}
fn get_amount_captured(&self) -> Result<Option<MinorUnit>, error_stack::Report<ParsingError>> {
match self.amount.clone() {
Some(amount) => {
let minor_amount = StringMinorUnitForConnector::convert_back(
&StringMinorUnitForConnector,
amount,
self.currency.unwrap_or_default(), //it is ignored in convert_back function
)?;
Ok(Some(minor_amount))
}
None => Ok(None),
}
}
fn get_connector_reference_id(&self) -> Option<String> {
self.reference.clone()
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4999
}
|
large_file_-6500069652880430456
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs
</path>
<file>
use common_utils::types::StringMinorUnit;
use masking::Secret;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize)]
pub struct GlobalPayRouterData<T> {
pub amount: StringMinorUnit,
pub router_data: T,
}
#[derive(Debug, Serialize)]
pub struct GlobalpayCancelRouterData<T> {
pub amount: Option<StringMinorUnit>,
pub router_data: T,
}
#[derive(Debug, Serialize)]
pub struct GlobalpayPaymentsRequest {
pub account_name: Secret<String>,
pub amount: Option<StringMinorUnit>,
pub currency: String,
pub reference: String,
pub country: api_models::enums::CountryAlpha2,
pub capture_mode: Option<CaptureMode>,
pub notifications: Option<Notifications>,
pub payment_method: GlobalPayPaymentMethodData,
pub channel: Channel,
pub initiator: Option<Initiator>,
pub stored_credential: Option<StoredCredential>,
}
#[derive(Debug, Serialize)]
pub struct GlobalpayRefreshTokenRequest {
pub app_id: Secret<String>,
pub nonce: Secret<String>,
pub secret: Secret<String>,
pub grant_type: String,
}
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Notifications {
pub return_url: Option<String>,
pub status_url: Option<String>,
pub cancel_url: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PaymentMethodData {
Card(Card),
Apm(Apm),
DigitalWallet(DigitalWallet),
Token(TokenizationData),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CommonPaymentMethodData {
#[serde(flatten)]
pub payment_method_data: PaymentMethodData,
pub entry_mode: PaymentMethodEntryMode,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MandatePaymentMethodData {
pub entry_mode: PaymentMethodEntryMode,
pub id: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GlobalPayPaymentMethodData {
Common(CommonPaymentMethodData),
Mandate(MandatePaymentMethodData),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Apm {
/// A string used to identify the payment method provider being used to execute this
/// transaction.
pub provider: Option<ApmProvider>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Card {
pub cvv: Secret<String>,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
pub number: cards::CardNumber,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct TokenizationData {
pub brand_reference: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct DigitalWallet {
/// Identifies who provides the digital wallet for the Payer.
pub provider: Option<DigitalWalletProvider>,
/// A token that represents, or is the payment method, stored with the digital wallet.
pub payment_token: Option<serde_json::Value>,
}
/// Stored data information used to create a transaction.
#[derive(Debug, Serialize, Deserialize)]
pub struct StoredCredential {
/// Indicates the transaction processing model being executed when using stored
/// credentials.
pub model: Option<Model>,
/// Indicates the order of this transaction in the sequence of a planned repeating
/// transaction processing model.
pub sequence: Option<Sequence>,
}
/// Indicates whether the transaction is to be captured automatically, later or later using
/// more than 1 partial capture.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CaptureMode {
/// If a transaction is authorized, funds will exchange between the payer and
/// merchant automatically and as soon as possible.
Auto,
/// If a transaction is authorized, funds will not exchange between the payer and
/// merchant automatically and will require a subsequent separate action to capture that
/// transaction and start the funding process. Only one successful capture is permitted.
Later,
/// If a transaction is authorized, funds will not exchange between the payer
/// and merchant automatically. One or more subsequent separate capture actions are required
/// to capture that transaction in parts and start the funding process for the part captured.
/// One or many successful capture are permitted once the total amount captured is within a
/// range of the original authorized amount.'
Multiple,
}
/// Describes whether the transaction was processed in a face to face(CP) scenario or a
/// Customer Not Present (CNP) scenario.
#[derive(Debug, Default, Serialize, Deserialize)]
pub enum Channel {
#[default]
#[serde(rename = "CNP")]
/// A Customer NOT Present transaction is when the payer and the merchant are not
/// together when exchanging payment method information to fulfill a transaction. e.g. a
/// transaction executed from a merchant's website or over the phone
CustomerNotPresent,
#[serde(rename = "CP")]
/// A Customer Present transaction is when the payer and the merchant are in direct
/// face to face contact when exchanging payment method information to fulfill a transaction.
/// e.g. in a store and paying at the counter that is attended by a clerk.
CustomerPresent,
}
/// Indicates whether the Merchant or the Payer initiated the creation of a transaction.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Initiator {
/// The transaction was initiated by the merchant, who is getting paid by the
/// payer.'
Merchant,
/// The transaction was initiated by the customer who is paying the merchant.
Payer,
}
/// A string used to identify the payment method provider being used to execute this
/// transaction.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApmProvider {
Giropay,
Ideal,
Paypal,
Sofort,
Eps,
Testpay,
}
/// Identifies who provides the digital wallet for the Payer.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DigitalWalletProvider {
Applepay,
PayByGoogle,
}
/// Indicates how the payment method information was obtained by the Merchant for this
/// transaction.
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentMethodEntryMode {
/// A CP channel entry mode where the payment method information was obtained from a
/// chip. E.g. card is inserted into a device to read the chip.
Chip,
/// A CP channel entry mode where the payment method information was
/// obtained by bringing the payment method to close proximity of a device. E.g. tap a cardon
/// or near a device to exchange card information.
ContactlessChip,
/// A CP channel entry mode where the payment method information was
/// obtained by bringing the payment method to close proximity of a device and also swiping
/// the card. E.g. tap a card on or near a device and swipe it through device to exchange
/// card information
ContactlessSwipe,
#[default]
/// A CNP channel entry mode where the payment method was obtained via a browser.
Ecom,
/// A CNP channel entry mode where the payment method was obtained via an
/// application and applies to digital wallets only.
InApp,
/// A CNP channel entry mode where the payment method was obtained via postal mail.
Mail,
/// A CP channel entry mode where the payment method information was obtained by
/// manually keying the payment method information into the device.
Manual,
/// A CNP channel entry mode where the payment method information was obtained over
/// the phone or via postal mail.
Moto,
/// A CNP channel entry mode where the payment method was obtained over the
/// phone.
Phone,
/// A CP channel entry mode where the payment method information was obtained from
/// swiping a magnetic strip. E.g. card's magnetic strip is swiped through a device to read
/// the card information.
Swipe,
}
/// Indicates the transaction processing model being executed when using stored
/// credentials.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Model {
/// The transaction is a repeat transaction initiated by the merchant and
/// taken using the payment method stored with the merchant, as part of an agreed schedule of
/// transactions and where the amount is known and agreed in advanced. For example the
/// payment in full of a good in fixed installments over a defined period of time.'
Installment,
/// The transaction is a repeat transaction initiated by the merchant and taken
/// using the payment method stored with the merchant, as part of an agreed schedule of
/// transactions.
Recurring,
/// The transaction is a repeat transaction initiated by the merchant and
/// taken using the payment method stored with the merchant, as part of an agreed schedule of
/// transactions. The amount taken is based on the usage by the payer of the good or service.
/// for example a monthly mobile phone bill.
Subscription,
/// the transaction is adhoc or unscheduled. For example a payer visiting a
/// merchant to make purchase using the payment method stored with the merchant.
Unscheduled,
}
/// Indicates the order of this transaction in the sequence of a planned repeating
/// transaction processing model.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Sequence {
First,
Last,
Subsequent,
}
#[derive(Default, Debug, Serialize)]
pub struct GlobalpayRefundRequest {
pub amount: StringMinorUnit,
}
#[derive(Default, Debug, Serialize)]
pub struct GlobalpayCaptureRequest {
pub amount: Option<StringMinorUnit>,
pub capture_sequence: Option<Sequence>,
pub reference: Option<String>,
}
#[derive(Default, Debug, Serialize)]
pub struct GlobalpayCancelRequest {
pub amount: Option<StringMinorUnit>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum UsageMode {
/// This value must be used if using the Hosted Fields or the Drop-in UI integration types.
/// When creating the payment method token, this option ensures the payment method token is temporary and will be removed once a transaction is executed or after a short period of time.
#[default]
Single,
/// When creating the payment method token, this indicates it is permanent and can be used to create many transactions.
Multiple,
/// When using the payment method token to transaction process, this indicates to use the card number also known as the PAN or FPAN when both the card number and the network token are available.
UseCardNumber,
/// When using the payment method token to transaction process, this indicates to use the network token instead of the card number if both are available.
UseNetworkToken,
}
#[derive(Default, Debug, Serialize)]
pub struct GlobalPayPaymentMethodsRequest {
pub reference: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub usage_mode: Option<UsageMode>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card: Option<Card>,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2400
}
|
large_file_6134357788359193514
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/finix/transformers.rs
</path>
<file>
pub mod request;
pub mod response;
use base64::Engine;
use common_enums::{enums, AttemptStatus, CaptureMethod, CountryAlpha2, CountryAlpha3};
use common_utils::types::MinorUnit;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},
router_flow_types::{
self as flows,
refunds::{Execute, RSync},
Authorize, Capture,
},
router_request_types::{
ConnectorCustomerData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCaptureData, RefundsData, ResponseId,
},
router_response_types::{
ConnectorCustomerResponseData, PaymentsResponseData, RefundsResponseData,
},
types::RefundsRouterData,
};
use hyperswitch_interfaces::{consts, errors::ConnectorError};
use masking::Secret;
pub use request::*;
pub use response::*;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
utils::{
get_unimplemented_payment_method_error_message, AddressDetailsData, CardData,
RouterData as _,
},
};
pub struct FinixRouterData<'a, Flow, Req, Res> {
pub amount: MinorUnit,
pub router_data: &'a RouterData<Flow, Req, Res>,
pub merchant_id: Secret<String>,
pub merchant_identity_id: Secret<String>,
}
impl<'a, Flow, Req, Res> TryFrom<(MinorUnit, &'a RouterData<Flow, Req, Res>)>
for FinixRouterData<'a, Flow, Req, Res>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(value: (MinorUnit, &'a RouterData<Flow, Req, Res>)) -> Result<Self, Self::Error> {
let (amount, router_data) = value;
let auth = FinixAuthType::try_from(&router_data.connector_auth_type)?;
Ok(Self {
amount,
router_data,
merchant_id: auth.merchant_id,
merchant_identity_id: auth.merchant_identity_id,
})
}
}
impl
TryFrom<
&FinixRouterData<
'_,
flows::CreateConnectorCustomer,
ConnectorCustomerData,
PaymentsResponseData,
>,
> for FinixCreateIdentityRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &FinixRouterData<
'_,
flows::CreateConnectorCustomer,
ConnectorCustomerData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let customer_data: &ConnectorCustomerData = &item.router_data.request;
let personal_address = item.router_data.get_optional_billing().and_then(|address| {
let billing = address.address.as_ref();
billing.map(|billing_address| FinixAddress {
line1: billing_address.get_optional_line1(),
line2: billing_address.get_optional_line2(),
city: billing_address.get_optional_city(),
region: billing_address.get_optional_state(),
postal_code: billing_address.get_optional_zip(),
country: billing_address
.get_optional_country()
.map(CountryAlpha2::from_alpha2_to_alpha3),
})
});
let entity = FinixIdentityEntity {
phone: customer_data.phone.clone(),
first_name: item.router_data.get_optional_billing_first_name(),
last_name: item.router_data.get_optional_billing_last_name(),
email: item.router_data.get_optional_billing_email(),
personal_address,
};
Ok(Self {
entity,
tags: None,
identity_type: FinixIdentityType::PERSONAL,
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FinixIdentityResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FinixIdentityResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(item.response.id),
)),
..item.data
})
}
}
impl TryFrom<&FinixRouterData<'_, Authorize, PaymentsAuthorizeData, PaymentsResponseData>>
for FinixPaymentsRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &FinixRouterData<'_, Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
if matches!(
item.router_data.auth_type,
enums::AuthenticationType::ThreeDs
) {
return Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("finix"),
)
.into());
}
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(_) => {
let source = item.router_data.get_payment_method_token()?;
Ok(Self {
amount: item.amount,
currency: item.router_data.request.currency,
source: match source {
PaymentMethodToken::Token(token) => token,
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Stax"),
)?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Stax"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Stax"))?
}
},
merchant: item.merchant_id.clone(),
tags: None,
three_d_secure: None,
})
}
PaymentMethodData::Wallet(WalletData::ApplePay(_) | WalletData::GooglePay(_)) => {
let source = item.router_data.get_payment_method_token()?;
Ok(Self {
amount: item.amount,
currency: item.router_data.request.currency,
source: match source {
PaymentMethodToken::Token(token) => token,
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Finix"),
)?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Finix"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Finix"))?
}
},
merchant: item.merchant_id.clone(),
tags: None,
three_d_secure: None,
})
}
PaymentMethodData::Wallet(_) => Err(ConnectorError::NotImplemented(
"Payment method not supported".to_string(),
)
.into()),
_ => Err(
ConnectorError::NotImplemented("Payment method not supported".to_string()).into(),
),
}
}
}
impl TryFrom<&FinixRouterData<'_, Capture, PaymentsCaptureData, PaymentsResponseData>>
for FinixCaptureRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &FinixRouterData<'_, Capture, PaymentsCaptureData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
capture_amount: item.router_data.request.minor_amount_to_capture,
})
}
}
impl
TryFrom<
&FinixRouterData<
'_,
flows::PaymentMethodToken,
PaymentMethodTokenizationData,
PaymentsResponseData,
>,
> for FinixCreatePaymentInstrumentRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &FinixRouterData<
'_,
flows::PaymentMethodToken,
PaymentMethodTokenizationData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let tokenization_data = &item.router_data.request;
match &tokenization_data.payment_method_data {
PaymentMethodData::Card(card_data) => {
Ok(Self {
instrument_type: FinixPaymentInstrumentType::PaymentCard,
name: card_data.card_holder_name.clone(),
number: Some(Secret::new(card_data.card_number.clone().get_card_no())),
security_code: Some(card_data.card_cvc.clone()),
expiration_month: Some(card_data.get_expiry_month_as_i8()?),
expiration_year: Some(card_data.get_expiry_year_as_4_digit_i32()?),
identity: item.router_data.get_connector_customer_id()?, // This would come from a previously created identity
tags: None,
address: None,
card_brand: None, // Finix determines this from the card number
card_type: None, // Finix determines this from the card number
additional_data: None,
merchant_identity: None,
third_party_token: None,
})
}
PaymentMethodData::Wallet(wallet) => match wallet {
WalletData::GooglePay(google_pay_wallet_data) => {
let third_party_token = google_pay_wallet_data
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(ConnectorError::MissingRequiredField {
field_name: "google_pay_token",
})?;
Ok(Self {
instrument_type: FinixPaymentInstrumentType::GOOGLEPAY,
name: item.router_data.get_optional_billing_full_name(),
identity: item.router_data.get_connector_customer_id()?,
number: None,
security_code: None,
expiration_month: None,
expiration_year: None,
tags: None,
address: None,
card_brand: None,
card_type: None,
additional_data: None,
merchant_identity: Some(item.merchant_identity_id.clone()),
third_party_token: Some(Secret::new(third_party_token)),
})
}
WalletData::ApplePay(apple_pay_wallet_data) => {
let applepay_encrypt_data = apple_pay_wallet_data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
let decoded_data = base64::prelude::BASE64_STANDARD
.decode(applepay_encrypt_data)
.change_context(ConnectorError::InvalidDataFormat {
field_name: "apple_pay_encrypted_data",
})?;
let apple_pay_token: FinixApplePayEncryptedData = serde_json::from_slice(
&decoded_data,
)
.change_context(ConnectorError::InvalidDataFormat {
field_name: "apple_pay_token_json",
})?;
let finix_token = FinixApplePayPaymentToken {
token: FinixApplePayToken {
payment_data: FinixApplePayEncryptedData {
data: apple_pay_token.data.clone(),
signature: apple_pay_token.signature.clone(),
header: FinixApplePayHeader {
public_key_hash: apple_pay_token.header.public_key_hash.clone(),
ephemeral_public_key: apple_pay_token
.header
.ephemeral_public_key
.clone(),
transaction_id: apple_pay_token.header.transaction_id.clone(),
},
version: apple_pay_token.version.clone(),
},
payment_method: FinixApplePayPaymentMethod {
display_name: Secret::new(
apple_pay_wallet_data.payment_method.display_name.clone(),
),
network: Secret::new(
apple_pay_wallet_data.payment_method.network.clone(),
),
method_type: Secret::new(
apple_pay_wallet_data.payment_method.pm_type.clone(),
),
},
transaction_identifier: apple_pay_wallet_data
.transaction_identifier
.clone(),
},
};
let third_party_token = serde_json::to_string(&finix_token).change_context(
ConnectorError::InvalidDataFormat {
field_name: "apple pay token",
},
)?;
Ok(Self {
instrument_type: FinixPaymentInstrumentType::ApplePay,
name: item.router_data.get_optional_billing_full_name(),
number: None,
security_code: None,
expiration_month: None,
expiration_year: None,
identity: item.router_data.get_connector_customer_id()?,
tags: None,
address: None,
card_brand: None,
card_type: None,
additional_data: None,
merchant_identity: Some(item.merchant_identity_id.clone()),
third_party_token: Some(Secret::new(third_party_token)),
})
}
_ => Err(ConnectorError::NotImplemented(
"Payment method not supported for tokenization".to_string(),
)
.into()),
},
_ => Err(ConnectorError::NotImplemented(
"Payment method not supported for tokenization".to_string(),
)
.into()),
}
}
}
// Implement response handling for tokenization
impl<F, T> TryFrom<ResponseRouterData<F, FinixInstrumentResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FinixInstrumentResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.id,
}),
..item.data
})
}
}
// Auth Struct
impl TryFrom<&ConnectorAuthType> for FinixAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Ok(Self {
finix_user_name: api_key.clone(),
finix_password: api_secret.clone(),
merchant_id: key1.clone(),
merchant_identity_id: key2.clone(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
fn get_attempt_status(state: FinixState, flow: FinixFlow, is_void: Option<bool>) -> AttemptStatus {
if is_void == Some(true) {
return match state {
FinixState::FAILED | FinixState::CANCELED | FinixState::UNKNOWN => {
AttemptStatus::VoidFailed
}
FinixState::PENDING => AttemptStatus::Voided,
FinixState::SUCCEEDED => AttemptStatus::Voided,
};
}
match (flow, state) {
(FinixFlow::Auth, FinixState::PENDING) => AttemptStatus::AuthenticationPending,
(FinixFlow::Auth, FinixState::SUCCEEDED) => AttemptStatus::Authorized,
(FinixFlow::Auth, FinixState::FAILED) => AttemptStatus::AuthorizationFailed,
(FinixFlow::Auth, FinixState::CANCELED) | (FinixFlow::Auth, FinixState::UNKNOWN) => {
AttemptStatus::AuthorizationFailed
}
(FinixFlow::Transfer, FinixState::PENDING) => AttemptStatus::Pending,
(FinixFlow::Transfer, FinixState::SUCCEEDED) => AttemptStatus::Charged,
(FinixFlow::Transfer, FinixState::FAILED)
| (FinixFlow::Transfer, FinixState::CANCELED)
| (FinixFlow::Transfer, FinixState::UNKNOWN) => AttemptStatus::Failure,
(FinixFlow::Capture, FinixState::PENDING) => AttemptStatus::Pending,
(FinixFlow::Capture, FinixState::SUCCEEDED) => AttemptStatus::Pending, // Psync with Transfer id can determine actuall success
(FinixFlow::Capture, FinixState::FAILED)
| (FinixFlow::Capture, FinixState::CANCELED)
| (FinixFlow::Capture, FinixState::UNKNOWN) => AttemptStatus::Failure,
}
}
pub(crate) fn get_finix_response<F, T>(
router_data: ResponseRouterData<F, FinixPaymentsResponse, T, PaymentsResponseData>,
finix_flow: FinixFlow,
) -> Result<RouterData<F, T, PaymentsResponseData>, error_stack::Report<ConnectorError>> {
let status = get_attempt_status(
router_data.response.state.clone(),
finix_flow,
router_data.response.is_void,
);
Ok(RouterData {
status,
response: if router_data.response.state.is_failure() {
Err(ErrorResponse {
code: router_data
.response
.failure_code
.unwrap_or(consts::NO_ERROR_CODE.to_string()),
message: router_data
.response
.messages
.map_or(consts::NO_ERROR_MESSAGE.to_string(), |msg| msg.join(",")),
reason: router_data.response.failure_message,
status_code: router_data.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(router_data.response.id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
router_data
.response
.transfer
.unwrap_or(router_data.response.id),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
},
..router_data.data
})
}
impl<F> TryFrom<&FinixRouterData<'_, F, RefundsData, RefundsResponseData>>
for FinixCreateRefundRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &FinixRouterData<'_, F, RefundsData, RefundsResponseData>,
) -> Result<Self, Self::Error> {
let refund_amount = item.router_data.request.minor_refund_amount;
Ok(Self::new(refund_amount))
}
}
impl From<FinixState> for enums::RefundStatus {
fn from(item: FinixState) -> Self {
match item {
FinixState::PENDING => Self::Pending,
FinixState::SUCCEEDED => Self::Success,
FinixState::FAILED | FinixState::CANCELED | FinixState::UNKNOWN => Self::Failure,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, FinixPaymentsResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, FinixPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.state),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, FinixPaymentsResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, FinixPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.state),
}),
..item.data
})
}
}
impl FinixErrorResponse {
pub fn get_message(&self) -> String {
self.embedded
.as_ref()
.and_then(|embedded| embedded.errors.as_ref())
.and_then(|errors| errors.first())
.and_then(|error| error.message.clone())
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string())
}
pub fn get_code(&self) -> String {
self.embedded
.as_ref()
.and_then(|embedded| embedded.errors.as_ref())
.and_then(|errors| errors.first())
.and_then(|error| error.code.clone())
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string())
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/finix/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4377
}
|
large_file_9028571912603708401
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
</path>
<file>
use std::collections::HashMap;
use cards::CardNumber;
use common_enums::{
AttemptStatus, CaptureMethod, CountryAlpha2, CountryAlpha3, Currency, RefundStatus,
};
use common_utils::{
errors::CustomResult, ext_traits::ValueExt, request::Method, types::StringMinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
refunds::{Execute, RSync},
SetupMandate,
},
router_request_types::{
CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
PaymentsPreProcessingData, PaymentsSyncData, ResponseId, SetupMandateRequestData,
},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{consts::NO_ERROR_CODE, errors};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use strum::Display;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
get_unimplemented_payment_method_error_message, to_connector_meta,
to_connector_meta_from_secret, CardData, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData,
PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RouterData as _,
},
};
#[derive(Clone, Copy, Debug)]
enum AddressKind {
Billing,
Shipping,
}
trait AddressConstructor {
fn new(
name: Option<Secret<String>>,
street: Option<Secret<String>>,
city: Option<String>,
post_code: Option<Secret<String>>,
country: Option<CountryAlpha3>,
) -> Self;
}
impl AddressConstructor for BillingAddress {
fn new(
name: Option<Secret<String>>,
street: Option<Secret<String>>,
city: Option<String>,
post_code: Option<Secret<String>>,
country: Option<CountryAlpha3>,
) -> Self {
Self {
name,
street,
city,
post_code,
country,
}
}
}
impl AddressConstructor for ShippingAddress {
fn new(
name: Option<Secret<String>>,
street: Option<Secret<String>>,
city: Option<String>,
post_code: Option<Secret<String>>,
country: Option<CountryAlpha3>,
) -> Self {
Self {
name,
street,
city,
post_code,
country,
}
}
}
fn get_validated_address_details_generic<RouterContextDataAlias, AddressOutput>(
data: &RouterContextDataAlias,
address_kind: AddressKind,
) -> Result<Option<AddressOutput>, error_stack::Report<errors::ConnectorError>>
where
RouterContextDataAlias: crate::utils::RouterData,
AddressOutput: AddressConstructor + Sized,
{
let (
opt_line1,
opt_line2,
opt_full_name,
opt_city,
opt_zip,
opt_country,
has_address_details_check,
address_type_str,
max_name_len,
max_street_len,
max_city_len,
max_post_code_len,
max_country_len,
) = match address_kind {
AddressKind::Billing => (
data.get_optional_billing_line1(),
data.get_optional_billing_line2(),
data.get_optional_billing_full_name(),
data.get_optional_billing_city(),
data.get_optional_billing_zip(),
data.get_optional_billing_country()
.map(CountryAlpha2::from_alpha2_to_alpha3),
data.get_optional_billing().is_some(),
"billing",
MAX_BILLING_ADDRESS_NAME_LENGTH,
MAX_BILLING_ADDRESS_STREET_LENGTH,
MAX_BILLING_ADDRESS_CITY_LENGTH,
MAX_BILLING_ADDRESS_POST_CODE_LENGTH,
MAX_BILLING_ADDRESS_COUNTRY_LENGTH,
),
AddressKind::Shipping => (
data.get_optional_shipping_line1(),
data.get_optional_shipping_line2(),
data.get_optional_shipping_full_name(),
data.get_optional_shipping_city(),
data.get_optional_shipping_zip(),
data.get_optional_shipping_country()
.map(CountryAlpha2::from_alpha2_to_alpha3),
data.get_optional_shipping().is_some(),
"shipping",
MAX_BILLING_ADDRESS_NAME_LENGTH,
MAX_BILLING_ADDRESS_STREET_LENGTH,
MAX_BILLING_ADDRESS_CITY_LENGTH,
MAX_BILLING_ADDRESS_POST_CODE_LENGTH,
MAX_BILLING_ADDRESS_COUNTRY_LENGTH,
),
};
let street_val = match (opt_line1.clone(), opt_line2.clone()) {
(Some(l1), Some(l2)) => Some(Secret::new(format!("{}, {}", l1.expose(), l2.expose()))),
(Some(l1), None) => Some(l1),
(None, Some(l2)) => Some(l2),
(None, None) => None,
};
if has_address_details_check {
let name_val = opt_full_name;
if let Some(ref val) = name_val {
let length = val.clone().expose().len();
if length > max_name_len {
return Err(error_stack::Report::from(
errors::ConnectorError::MaxFieldLengthViolated {
field_name: format!(
"{address_type_str}.address.first_name & {address_type_str}.address.last_name",
),
connector: "Nexixpay".to_string(),
max_length: max_name_len,
received_length: length,
},
));
}
}
if let Some(ref val) = street_val {
let length = val.clone().expose().len();
if length > max_street_len {
return Err(error_stack::Report::from(
errors::ConnectorError::MaxFieldLengthViolated {
field_name: format!(
"{address_type_str}.address.line1 & {address_type_str}.address.line2",
),
connector: "Nexixpay".to_string(),
max_length: max_street_len,
received_length: length,
},
));
}
}
let city_val = opt_city;
if let Some(ref val) = city_val {
let length = val.len();
if length > max_city_len {
return Err(error_stack::Report::from(
errors::ConnectorError::MaxFieldLengthViolated {
field_name: format!("{address_type_str}.address.city"),
connector: "Nexixpay".to_string(),
max_length: max_city_len,
received_length: length,
},
));
}
}
let post_code_val = opt_zip;
if let Some(ref val) = post_code_val {
let length = val.clone().expose().len();
if length > max_post_code_len {
return Err(error_stack::Report::from(
errors::ConnectorError::MaxFieldLengthViolated {
field_name: format!("{address_type_str}.address.zip"),
connector: "Nexixpay".to_string(),
max_length: max_post_code_len,
received_length: length,
},
));
}
}
let country_val = opt_country;
if let Some(ref val) = country_val {
let length = val.to_string().len();
if length > max_country_len {
return Err(error_stack::Report::from(
errors::ConnectorError::MaxFieldLengthViolated {
field_name: format!("{address_type_str}.address.country"),
connector: "Nexixpay".to_string(),
max_length: max_country_len,
received_length: length,
},
));
}
}
Ok(Some(AddressOutput::new(
name_val,
street_val,
city_val,
post_code_val,
country_val,
)))
} else {
Ok(None)
}
}
const MAX_ORDER_ID_LENGTH: usize = 18;
const MAX_CARD_HOLDER_LENGTH: usize = 255;
const MAX_BILLING_ADDRESS_NAME_LENGTH: usize = 50;
const MAX_BILLING_ADDRESS_STREET_LENGTH: usize = 50;
const MAX_BILLING_ADDRESS_CITY_LENGTH: usize = 40;
const MAX_BILLING_ADDRESS_POST_CODE_LENGTH: usize = 16;
const MAX_BILLING_ADDRESS_COUNTRY_LENGTH: usize = 3;
pub struct NexixpayRouterData<T> {
pub amount: StringMinorUnit,
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for NexixpayRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexixpayRecurringAction {
NoRecurring,
SubsequentPayment,
ContractCreation,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ContractType {
MitUnscheduled,
MitScheduled,
Cit,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecurrenceRequest {
action: NexixpayRecurringAction,
contract_id: Option<Secret<String>>,
contract_type: Option<ContractType>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayNonMandatePaymentRequest {
card: NexixpayCard,
recurrence: RecurrenceRequest,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayMandatePaymentRequest {
contract_id: Secret<String>,
capture_type: Option<NexixpayCaptureType>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum NexixpayPaymentsRequestData {
NexixpayNonMandatePaymentRequest(Box<NexixpayNonMandatePaymentRequest>),
NexixpayMandatePaymentRequest(Box<NexixpayMandatePaymentRequest>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayPaymentsRequest {
order: Order,
#[serde(flatten)]
payment_data: NexixpayPaymentsRequestData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexixpayCaptureType {
Implicit,
Explicit,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayCompleteAuthorizeRequest {
order: Order,
card: NexixpayCard,
operation_id: String,
capture_type: Option<NexixpayCaptureType>,
three_d_s_auth_data: ThreeDSAuthData,
recurrence: RecurrenceRequest,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OperationData {
operation_id: String,
operation_currency: Currency,
operation_result: NexixpayPaymentStatus,
operation_type: NexixpayOperationType,
order_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayCompleteAuthorizeResponse {
operation: OperationData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayPreProcessingRequest {
operation_id: Option<String>,
three_d_s_auth_response: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Order {
order_id: String,
amount: StringMinorUnit,
currency: Currency,
description: Option<String>,
customer_info: CustomerInfo,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomerInfo {
card_holder_name: Secret<String>,
billing_address: Option<BillingAddress>,
shipping_address: Option<ShippingAddress>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BillingAddress {
name: Option<Secret<String>>,
street: Option<Secret<String>>,
city: Option<String>,
post_code: Option<Secret<String>>,
country: Option<CountryAlpha3>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ShippingAddress {
name: Option<Secret<String>>,
street: Option<Secret<String>>,
city: Option<String>,
post_code: Option<Secret<String>>,
country: Option<CountryAlpha3>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayCard {
pan: CardNumber,
expiry_date: Secret<String>,
cvv: Secret<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentsResponse {
operation: Operation,
three_d_s_auth_request: String,
three_d_s_auth_url: Secret<url::Url>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayMandateResponse {
operation: Operation,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum NexixpayPaymentsResponse {
PaymentResponse(Box<PaymentsResponse>),
MandateResponse(Box<NexixpayMandateResponse>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSAuthResult {
authentication_value: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum NexixpayPaymentIntent {
Capture,
Cancel,
Authorize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayRedirectionRequest {
pub three_d_s_auth_url: String,
pub three_ds_request: String,
pub return_url: String,
pub transaction_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayConnectorMetaData {
pub three_d_s_auth_result: Option<ThreeDSAuthResult>,
pub three_d_s_auth_response: Option<Secret<String>>,
pub authorization_operation_id: Option<String>,
pub capture_operation_id: Option<String>,
pub cancel_operation_id: Option<String>,
pub psync_flow: NexixpayPaymentIntent,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateNexixpayConnectorMetaData {
pub three_d_s_auth_result: Option<ThreeDSAuthResult>,
pub three_d_s_auth_response: Option<Secret<String>>,
pub authorization_operation_id: Option<String>,
pub capture_operation_id: Option<String>,
pub cancel_operation_id: Option<String>,
pub psync_flow: Option<NexixpayPaymentIntent>,
pub meta_data: serde_json::Value,
pub is_auto_capture: bool,
}
fn update_nexi_meta_data(
update_request: UpdateNexixpayConnectorMetaData,
) -> CustomResult<serde_json::Value, errors::ConnectorError> {
let nexixpay_meta_data =
serde_json::from_value::<NexixpayConnectorMetaData>(update_request.meta_data)
.change_context(errors::ConnectorError::ParsingFailed)?;
Ok(serde_json::json!(NexixpayConnectorMetaData {
three_d_s_auth_result: nexixpay_meta_data
.three_d_s_auth_result
.or(update_request.three_d_s_auth_result),
three_d_s_auth_response: nexixpay_meta_data
.three_d_s_auth_response
.or(update_request.three_d_s_auth_response),
authorization_operation_id: nexixpay_meta_data
.authorization_operation_id
.clone()
.or(update_request.authorization_operation_id.clone()),
capture_operation_id: {
nexixpay_meta_data
.capture_operation_id
.or(if update_request.is_auto_capture {
nexixpay_meta_data
.authorization_operation_id
.or(update_request.authorization_operation_id.clone())
} else {
update_request.capture_operation_id
})
},
cancel_operation_id: nexixpay_meta_data
.cancel_operation_id
.or(update_request.cancel_operation_id),
psync_flow: update_request
.psync_flow
.unwrap_or(nexixpay_meta_data.psync_flow)
}))
}
pub fn get_error_response(
operation_result: NexixpayPaymentStatus,
status_code: u16,
) -> ErrorResponse {
ErrorResponse {
status_code,
code: NO_ERROR_CODE.to_string(),
message: operation_result.to_string(),
reason: Some(operation_result.to_string()),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
fn get_nexi_order_id(payment_id: &str) -> CustomResult<String, errors::ConnectorError> {
if payment_id.len() > MAX_ORDER_ID_LENGTH {
if payment_id.starts_with("pay_") {
Ok(payment_id
.chars()
.take(MAX_ORDER_ID_LENGTH)
.collect::<String>())
} else {
Err(error_stack::Report::from(
errors::ConnectorError::MaxFieldLengthViolated {
field_name: "payment_id".to_string(),
connector: "Nexixpay".to_string(),
max_length: MAX_ORDER_ID_LENGTH,
received_length: payment_id.len(),
},
))
}
} else {
Ok(payment_id.to_string())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSAuthData {
three_d_s_auth_response: Option<Secret<String>>,
authentication_value: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayPreProcessingResponse {
operation: Operation,
three_d_s_auth_result: ThreeDSAuthResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Operation {
additional_data: AdditionalData,
channel: Option<Channel>,
customer_info: CustomerInfo,
operation_amount: StringMinorUnit,
operation_currency: Currency,
operation_id: String,
operation_result: NexixpayPaymentStatus,
operation_time: String,
operation_type: NexixpayOperationType,
order_id: String,
payment_method: String,
warnings: Option<Vec<DetailedWarnings>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Channel {
Ecommerce,
Pos,
Backoffice,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DetailedWarnings {
code: Option<String>,
description: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdditionalData {
masked_pan: String,
card_id: Secret<String>,
card_id4: Option<Secret<String>>,
card_expiry_date: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RedirectPayload {
#[serde(rename = "PaRes")]
pa_res: Option<Secret<String>>,
#[serde(rename = "paymentId")]
payment_id: Option<String>,
}
impl TryFrom<&PaymentsPreProcessingRouterData> for NexixpayPreProcessingRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> {
let redirect_response = item.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let redirect_payload = redirect_response
.payload
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
})?
.expose();
let customer_details_encrypted: RedirectPayload =
serde_json::from_value::<RedirectPayload>(redirect_payload.clone()).change_context(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "redirection_payload",
},
)?;
Ok(Self {
operation_id: customer_details_encrypted.payment_id,
three_d_s_auth_response: customer_details_encrypted.pa_res,
})
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
NexixpayPreProcessingResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
NexixpayPreProcessingResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let three_ds_data = item.response.three_d_s_auth_result;
let customer_details_encrypted: RedirectPayload = item
.data
.request
.redirect_response
.as_ref()
.and_then(|res| res.payload.to_owned())
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
})?
.expose()
.parse_value("RedirectPayload")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let is_auto_capture = item.data.request.is_auto_capture()?;
let meta_data = to_connector_meta_from_secret(item.data.request.metadata.clone())?;
let connector_metadata = Some(update_nexi_meta_data(UpdateNexixpayConnectorMetaData {
three_d_s_auth_result: Some(three_ds_data),
three_d_s_auth_response: customer_details_encrypted.pa_res,
authorization_operation_id: None,
capture_operation_id: None,
cancel_operation_id: None,
psync_flow: None,
meta_data,
is_auto_capture,
})?);
let status = AttemptStatus::from(item.response.operation.operation_result.clone());
match status {
AttemptStatus::Failure => {
let response = Err(get_error_response(
item.response.operation.operation_result.clone(),
item.http_code,
));
Ok(Self {
response,
..item.data
})
}
_ => Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.operation.order_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(item.response.operation.order_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
}
}
}
impl TryFrom<&NexixpayRouterData<&PaymentsAuthorizeRouterData>> for NexixpayPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &NexixpayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let order_id = get_nexi_order_id(&item.router_data.payment_id)?;
let billing_address = get_validated_billing_address(item.router_data)?;
let shipping_address = get_validated_shipping_address(item.router_data)?;
let customer_info = CustomerInfo {
card_holder_name: match item.router_data.get_billing_full_name()? {
name if name.clone().expose().len() <= MAX_CARD_HOLDER_LENGTH => name,
_ => {
return Err(error_stack::Report::from(
errors::ConnectorError::MaxFieldLengthViolated {
field_name: "billing.address.first_name & billing.address.last_name"
.to_string(),
connector: "Nexixpay".to_string(),
max_length: MAX_CARD_HOLDER_LENGTH,
received_length: item
.router_data
.get_billing_full_name()?
.expose()
.len(),
},
))
}
},
billing_address: billing_address.clone(),
shipping_address: shipping_address.clone(),
};
let order = Order {
order_id,
amount: item.amount.clone(),
currency: item.router_data.request.currency,
description: item.router_data.description.clone(),
customer_info,
};
let payment_data = NexixpayPaymentsRequestData::try_from(item)?;
Ok(Self {
order,
payment_data,
})
}
}
impl TryFrom<&NexixpayRouterData<&PaymentsAuthorizeRouterData>> for NexixpayPaymentsRequestData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &NexixpayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item
.router_data
.request
.mandate_id
.clone()
.and_then(|mandate_id| mandate_id.mandate_reference_id)
{
None => {
let recurrence_request_obj = if item.router_data.request.is_mandate_payment() {
let contract_id = item
.router_data
.connector_mandate_request_reference_id
.clone()
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_request_reference_id",
})?;
RecurrenceRequest {
action: NexixpayRecurringAction::ContractCreation,
contract_id: Some(Secret::new(contract_id)),
contract_type: Some(ContractType::MitUnscheduled),
}
} else {
RecurrenceRequest {
action: NexixpayRecurringAction::NoRecurring,
contract_id: None,
contract_type: None,
}
};
match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref req_card) => {
if item.router_data.is_three_ds() {
Ok(Self::NexixpayNonMandatePaymentRequest(Box::new(
NexixpayNonMandatePaymentRequest {
card: NexixpayCard {
pan: req_card.card_number.clone(),
expiry_date: req_card.get_expiry_date_as_mmyy()?,
cvv: req_card.card_cvc.clone(),
},
recurrence: recurrence_request_obj,
},
)))
} else {
Err(errors::ConnectorError::NotSupported {
message: "No threeds is not supported".to_string(),
connector: "nexixpay",
}
.into())
}
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("nexixpay"),
))?
}
}
}
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(mandate_data)) => {
let contract_id = Secret::new(
mandate_data
.get_connector_mandate_request_reference_id()
.ok_or(errors::ConnectorError::MissingConnectorMandateID)?,
);
let capture_type =
get_nexixpay_capture_type(item.router_data.request.capture_method)?;
Ok(Self::NexixpayMandatePaymentRequest(Box::new(
NexixpayMandatePaymentRequest {
contract_id,
capture_type,
},
)))
}
Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_))
| Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("nexixpay"),
)
.into())
}
}
}
}
pub struct NexixpayAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for NexixpayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Display, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexixpayPaymentStatus {
Authorized,
Executed,
Declined,
DeniedByRisk,
ThreedsValidated,
ThreedsFailed,
Pending,
Canceled,
Voided,
Refunded,
Failed,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexixpayOperationType {
Authorization,
Capture,
Void,
Refund,
CardVerification,
Noshow,
Incremental,
DelayCharge,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexixpayRefundOperationType {
Refund,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexixpayRefundResultStatus {
Pending,
Voided,
Refunded,
Failed,
Executed,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayTransactionResponse {
order_id: String,
operation_id: String,
operation_result: NexixpayPaymentStatus,
operation_type: NexixpayOperationType,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayRSyncResponse {
order_id: String,
operation_id: String,
operation_result: NexixpayRefundResultStatus,
operation_type: NexixpayRefundOperationType,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayPaymentsCaptureRequest {
amount: StringMinorUnit,
currency: Currency,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayPaymentsCancelRequest {
description: Option<String>,
amount: StringMinorUnit,
currency: Currency,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayOperationResponse {
operation_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NexixpayRefundRequest {
pub amount: StringMinorUnit,
pub currency: Currency,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
operation_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayErrorBody {
pub code: Option<String>,
pub description: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayErrorResponse {
pub errors: Vec<NexixpayErrorBody>,
}
impl From<NexixpayPaymentStatus> for AttemptStatus {
fn from(item: NexixpayPaymentStatus) -> Self {
match item {
NexixpayPaymentStatus::Declined
| NexixpayPaymentStatus::DeniedByRisk
| NexixpayPaymentStatus::ThreedsFailed
| NexixpayPaymentStatus::Failed => Self::Failure,
NexixpayPaymentStatus::Authorized => Self::Authorized,
NexixpayPaymentStatus::ThreedsValidated => Self::AuthenticationSuccessful,
NexixpayPaymentStatus::Executed => Self::Charged,
NexixpayPaymentStatus::Pending => Self::AuthenticationPending, // this is being used in authorization calls only.
NexixpayPaymentStatus::Canceled | NexixpayPaymentStatus::Voided => Self::Voided,
NexixpayPaymentStatus::Refunded => Self::AutoRefunded,
}
}
}
fn get_nexixpay_capture_type(
item: Option<CaptureMethod>,
) -> CustomResult<Option<NexixpayCaptureType>, errors::ConnectorError> {
match item {
Some(CaptureMethod::Manual) => Ok(Some(NexixpayCaptureType::Explicit)),
Some(CaptureMethod::Automatic) | Some(CaptureMethod::SequentialAutomatic) | None => {
Ok(Some(NexixpayCaptureType::Implicit))
}
Some(item) => Err(errors::ConnectorError::FlowNotSupported {
flow: item.to_string(),
connector: "Nexixpay".to_string(),
}
.into()),
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
NexixpayPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
NexixpayPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
NexixpayPaymentsResponse::PaymentResponse(ref response_body) => {
let complete_authorize_url = item.data.request.get_complete_authorize_url()?;
let operation_id: String = response_body.operation.operation_id.clone();
let redirection_form = nexixpay_threeds_link(NexixpayRedirectionRequest {
three_d_s_auth_url: response_body
.three_d_s_auth_url
.clone()
.expose()
.to_string(),
three_ds_request: response_body.three_d_s_auth_request.clone(),
return_url: complete_authorize_url.clone(),
transaction_id: operation_id.clone(),
})?;
let is_auto_capture = item.data.request.is_auto_capture()?;
let connector_metadata = Some(serde_json::json!(NexixpayConnectorMetaData {
three_d_s_auth_result: None,
three_d_s_auth_response: None,
authorization_operation_id: Some(operation_id.clone()),
cancel_operation_id: None,
capture_operation_id: {
if is_auto_capture {
Some(operation_id)
} else {
None
}
},
psync_flow: NexixpayPaymentIntent::Authorize
}));
let mandate_reference = if item.data.request.is_mandate_payment() {
Box::new(Some(MandateReference {
connector_mandate_id: item
.data
.connector_mandate_request_reference_id
.clone(),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}))
} else {
Box::new(None)
};
let status = AttemptStatus::from(response_body.operation.operation_result.clone());
match status {
AttemptStatus::Failure => {
let response = Err(get_error_response(
response_body.operation.operation_result.clone(),
item.http_code,
));
Ok(Self {
response,
..item.data
})
}
_ => Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response_body.operation.order_id.clone(),
),
redirection_data: Box::new(Some(redirection_form.clone())),
mandate_reference,
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(
response_body.operation.order_id.clone(),
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
}
}
NexixpayPaymentsResponse::MandateResponse(ref mandate_response) => {
let status =
AttemptStatus::from(mandate_response.operation.operation_result.clone());
let is_auto_capture = item.data.request.is_auto_capture()?;
let operation_id = mandate_response.operation.operation_id.clone();
let connector_metadata = Some(serde_json::json!(NexixpayConnectorMetaData {
three_d_s_auth_result: None,
three_d_s_auth_response: None,
authorization_operation_id: Some(operation_id.clone()),
cancel_operation_id: None,
capture_operation_id: {
if is_auto_capture {
Some(operation_id)
} else {
None
}
},
psync_flow: NexixpayPaymentIntent::Authorize
}));
match status {
AttemptStatus::Failure => {
let response = Err(get_error_response(
mandate_response.operation.operation_result.clone(),
item.http_code,
));
Ok(Self {
response,
..item.data
})
}
_ => Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
mandate_response.operation.order_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(
mandate_response.operation.order_id.clone(),
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
}
}
}
}
}
fn nexixpay_threeds_link(
request: NexixpayRedirectionRequest,
) -> CustomResult<RedirectForm, errors::ConnectorError> {
let mut form_fields = HashMap::<String, String>::new();
form_fields.insert(String::from("ThreeDsRequest"), request.three_ds_request);
form_fields.insert(String::from("ReturnUrl"), request.return_url);
form_fields.insert(String::from("transactionId"), request.transaction_id);
Ok(RedirectForm::Form {
endpoint: request.three_d_s_auth_url,
method: Method::Post,
form_fields,
})
}
impl<F> TryFrom<&NexixpayRouterData<&RefundsRouterData<F>>> for NexixpayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &NexixpayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
currency: item.router_data.request.currency,
})
}
}
impl From<NexixpayRefundResultStatus> for RefundStatus {
fn from(item: NexixpayRefundResultStatus) -> Self {
match item {
NexixpayRefundResultStatus::Voided
| NexixpayRefundResultStatus::Refunded
| NexixpayRefundResultStatus::Executed => Self::Success,
NexixpayRefundResultStatus::Pending => Self::Pending,
NexixpayRefundResultStatus::Failed => Self::Failure,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.operation_id,
refund_status: RefundStatus::Pending, // Refund call do not return status in their response.
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, NexixpayRSyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, NexixpayRSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.operation_id,
refund_status: RefundStatus::from(item.response.operation_result),
}),
..item.data
})
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
NexixpayCompleteAuthorizeResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
NexixpayCompleteAuthorizeResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let is_auto_capture = item.data.request.is_auto_capture()?;
let meta_data = to_connector_meta(item.data.request.connector_meta.clone())?;
let connector_metadata = Some(update_nexi_meta_data(UpdateNexixpayConnectorMetaData {
three_d_s_auth_result: None,
three_d_s_auth_response: None,
authorization_operation_id: Some(item.response.operation.operation_id.clone()),
capture_operation_id: None,
cancel_operation_id: None,
psync_flow: Some(NexixpayPaymentIntent::Authorize),
meta_data,
is_auto_capture,
})?);
let mandate_reference = if item.data.request.is_mandate_payment() {
Box::new(Some(MandateReference {
connector_mandate_id: item.data.connector_mandate_request_reference_id.clone(),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}))
} else {
Box::new(None)
};
let status = if item.data.request.amount == 0
&& item.response.operation.operation_result == NexixpayPaymentStatus::Authorized
{
AttemptStatus::Charged
} else {
AttemptStatus::from(item.response.operation.operation_result.clone())
};
match status {
AttemptStatus::Failure => {
let response = Err(get_error_response(
item.response.operation.operation_result.clone(),
item.http_code,
));
Ok(Self {
response,
..item.data
})
}
_ => Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.operation.order_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference,
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(item.response.operation.order_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
}
}
}
impl TryFrom<&NexixpayRouterData<&PaymentsCompleteAuthorizeRouterData>>
for NexixpayCompleteAuthorizeRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &NexixpayRouterData<&PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payment_method_data: PaymentMethodData =
item.router_data.request.payment_method_data.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "payment_method_data",
},
)?;
let capture_type = get_nexixpay_capture_type(item.router_data.request.capture_method)?;
let order_id = get_nexi_order_id(&item.router_data.payment_id)?;
let amount = item.amount.clone();
let billing_address = get_validated_billing_address(item.router_data)?;
let shipping_address = get_validated_shipping_address(item.router_data)?;
let customer_info = CustomerInfo {
card_holder_name: item.router_data.get_billing_full_name()?,
billing_address: billing_address.clone(),
shipping_address: shipping_address.clone(),
};
let order_data = Order {
order_id,
amount,
currency: item.router_data.request.currency,
description: item.router_data.description.clone(),
customer_info,
};
let connector_metadata =
to_connector_meta(item.router_data.request.connector_meta.clone())?;
let nexixpay_meta_data =
serde_json::from_value::<NexixpayConnectorMetaData>(connector_metadata)
.change_context(errors::ConnectorError::ParsingFailed)?;
let operation_id = nexixpay_meta_data.authorization_operation_id.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "authorization_operation_id",
},
)?;
let authentication_value = nexixpay_meta_data
.three_d_s_auth_result
.and_then(|data| data.authentication_value);
let three_d_s_auth_data = ThreeDSAuthData {
three_d_s_auth_response: nexixpay_meta_data.three_d_s_auth_response,
authentication_value,
};
let card: Result<NexixpayCard, error_stack::Report<errors::ConnectorError>> =
match payment_method_data {
PaymentMethodData::Card(req_card) => Ok(NexixpayCard {
pan: req_card.card_number.clone(),
expiry_date: req_card.get_expiry_date_as_mmyy()?,
cvv: req_card.card_cvc.clone(),
}),
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("nexixpay"),
)
.into())
}
};
let recurrence_request_obj = if item.router_data.request.is_mandate_payment() {
let contract_id = Secret::new(
item.router_data
.connector_mandate_request_reference_id
.clone()
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_request_reference_id",
})?,
);
RecurrenceRequest {
action: NexixpayRecurringAction::ContractCreation,
contract_id: Some(contract_id),
contract_type: Some(ContractType::MitUnscheduled),
}
} else {
RecurrenceRequest {
action: NexixpayRecurringAction::NoRecurring,
contract_id: None,
contract_type: None,
}
};
Ok(Self {
order: order_data,
card: card?,
operation_id,
capture_type,
three_d_s_auth_data,
recurrence: recurrence_request_obj,
})
}
}
fn get_validated_shipping_address<RouterContextDataAlias>(
data: &RouterContextDataAlias,
) -> Result<Option<ShippingAddress>, error_stack::Report<errors::ConnectorError>>
where
RouterContextDataAlias: crate::utils::RouterData,
{
get_validated_address_details_generic(data, AddressKind::Shipping)
}
fn get_validated_billing_address<RouterContextDataAlias>(
data: &RouterContextDataAlias,
) -> Result<Option<BillingAddress>, error_stack::Report<errors::ConnectorError>>
where
RouterContextDataAlias: crate::utils::RouterData,
{
get_validated_address_details_generic(data, AddressKind::Billing)
}
impl<F>
TryFrom<
ResponseRouterData<F, NexixpayTransactionResponse, PaymentsSyncData, PaymentsResponseData>,
> for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
NexixpayTransactionResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = AttemptStatus::from(item.response.operation_result.clone());
let mandate_reference = if item.data.request.is_mandate_payment() {
Box::new(Some(MandateReference {
connector_mandate_id: item.data.connector_mandate_request_reference_id.clone(),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}))
} else {
Box::new(None)
};
match status {
AttemptStatus::Failure => {
let response = Err(get_error_response(
item.response.operation_result.clone(),
item.http_code,
));
Ok(Self {
response,
..item.data
})
}
_ => Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()),
redirection_data: Box::new(None),
mandate_reference,
connector_metadata: item.data.request.connector_meta.clone(),
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
}
}
}
impl TryFrom<&NexixpayRouterData<&PaymentsCaptureRouterData>> for NexixpayPaymentsCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &NexixpayRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.clone(),
currency: item.router_data.request.currency,
})
}
}
impl<F>
TryFrom<
ResponseRouterData<F, NexixpayOperationResponse, PaymentsCaptureData, PaymentsResponseData>,
> for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
NexixpayOperationResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let meta_data = to_connector_meta(item.data.request.connector_meta.clone())?;
let connector_metadata = Some(update_nexi_meta_data(UpdateNexixpayConnectorMetaData {
three_d_s_auth_result: None,
three_d_s_auth_response: None,
authorization_operation_id: None,
capture_operation_id: Some(item.response.operation_id.clone()),
cancel_operation_id: None,
psync_flow: Some(NexixpayPaymentIntent::Capture),
meta_data,
is_auto_capture: false,
})?);
Ok(Self {
status: AttemptStatus::Pending, // Capture call do not return status in their response.
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.data.request.connector_transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(
item.data.request.connector_transaction_id.clone(),
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<NexixpayRouterData<&PaymentsCancelRouterData>> for NexixpayPaymentsCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: NexixpayRouterData<&PaymentsCancelRouterData>) -> Result<Self, Self::Error> {
let description = item.router_data.request.cancellation_reason.clone();
let currency = item.router_data.request.currency.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "currency",
},
)?;
Ok(Self {
amount: item.amount,
currency,
description,
})
}
}
impl<F>
TryFrom<
ResponseRouterData<F, NexixpayOperationResponse, PaymentsCancelData, PaymentsResponseData>,
> for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
NexixpayOperationResponse,
PaymentsCancelData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let meta_data = to_connector_meta(item.data.request.connector_meta.clone())?;
let connector_metadata = Some(update_nexi_meta_data(UpdateNexixpayConnectorMetaData {
three_d_s_auth_result: None,
three_d_s_auth_response: None,
authorization_operation_id: None,
capture_operation_id: None,
cancel_operation_id: Some(item.response.operation_id.clone()),
psync_flow: Some(NexixpayPaymentIntent::Cancel),
meta_data,
is_auto_capture: false,
})?);
Ok(Self {
status: AttemptStatus::Pending, // Cancel call do not return status in their response.
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.data.request.connector_transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(
item.data.request.connector_transaction_id.clone(),
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl
TryFrom<
ResponseRouterData<
SetupMandate,
PaymentsResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
> for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
SetupMandate,
PaymentsResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let complete_authorize_url = item.data.request.get_complete_authorize_url()?;
let operation_id: String = item.response.operation.operation_id.clone();
let redirection_form = nexixpay_threeds_link(NexixpayRedirectionRequest {
three_d_s_auth_url: item
.response
.three_d_s_auth_url
.clone()
.expose()
.to_string(),
three_ds_request: item.response.three_d_s_auth_request.clone(),
return_url: complete_authorize_url.clone(),
transaction_id: operation_id.clone(),
})?;
let is_auto_capture = item.data.request.is_auto_capture()?;
let connector_metadata = Some(serde_json::json!(NexixpayConnectorMetaData {
three_d_s_auth_result: None,
three_d_s_auth_response: None,
authorization_operation_id: Some(operation_id.clone()),
cancel_operation_id: None,
capture_operation_id: {
if is_auto_capture {
Some(operation_id)
} else {
None
}
},
psync_flow: NexixpayPaymentIntent::Authorize
}));
let status = AttemptStatus::from(item.response.operation.operation_result.clone());
match status {
AttemptStatus::Failure => {
let response = Err(get_error_response(
item.response.operation.operation_result.clone(),
item.http_code,
));
Ok(Self {
response,
..item.data
})
}
_ => Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.operation.order_id.clone(),
),
redirection_data: Box::new(Some(redirection_form.clone())),
mandate_reference: Box::new(Some(MandateReference {
connector_mandate_id: item
.data
.connector_mandate_request_reference_id
.clone(),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(item.response.operation.order_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 12311
}
|
large_file_-8107452768042537392
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
</path>
<file>
use std::collections::HashMap;
use api_models::webhooks::IncomingWebhookEvent;
use cards::CardNumber;
use common_enums::{enums, enums as api_enums};
use common_utils::{
consts,
ext_traits::OptionExt,
pii::Email,
request::Method,
types::{MinorUnit, StringMinorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{
BankDebitData, PaymentMethodData, WalletData as WalletDataPaymentMethod,
},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData, ResponseId},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use strum::Display;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressData, AddressDetailsData, ApplePay, PaymentsAuthorizeRequestData,
PaymentsCancelRequestData, PaymentsCaptureRequestData, PaymentsSetupMandateRequestData,
PaymentsSyncRequestData, RefundsRequestData, RouterData as _,
},
};
pub struct NovalnetRouterData<T> {
pub amount: StringMinorUnit,
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for NovalnetRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
const MINIMAL_CUSTOMER_DATA_PASSED: i64 = 1;
const CREATE_TOKEN_REQUIRED: i8 = 1;
const TEST_MODE_ENABLED: i8 = 1;
const TEST_MODE_DISABLED: i8 = 0;
fn get_test_mode(item: Option<bool>) -> i8 {
match item {
Some(true) => TEST_MODE_ENABLED,
Some(false) | None => TEST_MODE_DISABLED,
}
}
#[derive(Debug, Copy, Serialize, Deserialize, Clone)]
pub enum NovalNetPaymentTypes {
CREDITCARD,
PAYPAL,
GOOGLEPAY,
APPLEPAY,
#[serde(rename = "DIRECT_DEBIT_SEPA")]
DirectDebitSepa,
#[serde(rename = "GUARANTEED_DIRECT_DEBIT_SEPA")]
GuaranteedDirectDebitSepa,
}
#[derive(Default, Debug, Serialize, Clone)]
pub struct NovalnetPaymentsRequestMerchant {
signature: Secret<String>,
tariff: Secret<String>,
}
#[derive(Default, Debug, Serialize, Clone)]
pub struct NovalnetPaymentsRequestBilling {
house_no: Option<Secret<String>>,
street: Option<Secret<String>>,
city: Option<Secret<String>>,
zip: Option<Secret<String>>,
country_code: Option<api_enums::CountryAlpha2>,
}
#[derive(Default, Debug, Serialize, Clone)]
pub struct NovalnetPaymentsRequestCustomer {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
email: Email,
mobile: Option<Secret<String>>,
billing: Option<NovalnetPaymentsRequestBilling>,
no_nc: i64,
birth_date: Option<String>, // Mandatory for SEPA Guarentee Payment
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetCard {
card_number: CardNumber,
card_expiry_month: Secret<String>,
card_expiry_year: Secret<String>,
card_cvc: Secret<String>,
card_holder: Secret<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetRawCardDetails {
card_number: CardNumber,
card_expiry_month: Secret<String>,
card_expiry_year: Secret<String>,
scheme_tid: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NovalnetMandate {
token: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NovalnetSepaDebit {
account_holder: Secret<String>,
iban: Secret<String>,
birth_date: Option<String>, // Mandatory for SEPA Guarantee Payment
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetGooglePay {
wallet_data: Secret<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetApplePay {
wallet_data: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum NovalNetPaymentData {
Card(NovalnetCard),
RawCardForNTI(NovalnetRawCardDetails),
GooglePay(NovalnetGooglePay),
ApplePay(NovalnetApplePay),
MandatePayment(NovalnetMandate),
Sepa(NovalnetSepaDebit),
}
#[derive(Default, Debug, Serialize, Clone)]
pub struct NovalnetCustom {
lang: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum NovalNetAmount {
StringMinor(StringMinorUnit),
Int(i64),
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NovalnetPaymentsRequestTransaction {
test_mode: i8,
payment_type: NovalNetPaymentTypes,
amount: NovalNetAmount,
currency: common_enums::Currency,
order_no: String,
payment_data: Option<NovalNetPaymentData>,
hook_url: Option<String>,
return_url: Option<String>,
error_return_url: Option<String>,
enforce_3d: Option<i8>, //NOTE: Needed for CREDITCARD, GOOGLEPAY
create_token: Option<i8>,
}
#[derive(Debug, Serialize, Clone)]
pub struct NovalnetPaymentsRequest {
merchant: NovalnetPaymentsRequestMerchant,
customer: NovalnetPaymentsRequestCustomer,
transaction: NovalnetPaymentsRequestTransaction,
custom: NovalnetCustom,
}
impl TryFrom<&api_enums::PaymentMethodType> for NovalNetPaymentTypes {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &api_enums::PaymentMethodType) -> Result<Self, Self::Error> {
match item {
api_enums::PaymentMethodType::ApplePay => Ok(Self::APPLEPAY),
api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => {
Ok(Self::CREDITCARD)
}
api_enums::PaymentMethodType::GooglePay => Ok(Self::GOOGLEPAY),
api_enums::PaymentMethodType::Paypal => Ok(Self::PAYPAL),
api_enums::PaymentMethodType::Sepa => Ok(Self::DirectDebitSepa),
api_enums::PaymentMethodType::SepaGuarenteedDebit => {
Ok(Self::GuaranteedDirectDebitSepa)
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Novalnet"),
)
.into()),
}
}
}
impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &NovalnetRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let auth = NovalnetAuthType::try_from(&item.router_data.connector_auth_type)?;
let merchant = NovalnetPaymentsRequestMerchant {
signature: auth.product_activation_key,
tariff: auth.tariff_id,
};
let enforce_3d = match item.router_data.auth_type {
enums::AuthenticationType::ThreeDs => Some(1),
enums::AuthenticationType::NoThreeDs => None,
};
let test_mode = get_test_mode(item.router_data.test_mode);
let billing = NovalnetPaymentsRequestBilling {
house_no: item.router_data.get_optional_billing_line1(),
street: item.router_data.get_optional_billing_line2(),
city: item
.router_data
.get_optional_billing_city()
.map(Secret::new),
zip: item.router_data.get_optional_billing_zip(),
country_code: item.router_data.get_optional_billing_country(),
};
let customer = NovalnetPaymentsRequestCustomer {
first_name: item.router_data.get_optional_billing_first_name(),
last_name: item.router_data.get_optional_billing_last_name(),
email: item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?,
mobile: item.router_data.get_optional_billing_phone_number(),
billing: Some(billing),
// no_nc is used to indicate if minimal customer data is passed or not
no_nc: MINIMAL_CUSTOMER_DATA_PASSED,
birth_date: Some(String::from("1992-06-10")),
};
let lang = item
.router_data
.request
.get_optional_language_from_browser_info()
.unwrap_or(consts::DEFAULT_LOCALE.to_string().to_string());
let custom = NovalnetCustom { lang };
let hook_url = item.router_data.request.get_webhook_url()?;
let return_url = item.router_data.request.get_router_return_url()?;
let create_token = if item.router_data.request.is_mandate_payment() {
Some(CREATE_TOKEN_REQUIRED)
} else {
None
};
match item
.router_data
.request
.mandate_id
.clone()
.and_then(|mandate_id| mandate_id.mandate_reference_id)
{
None => match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref req_card) => {
let novalnet_card = NovalNetPaymentData::Card(NovalnetCard {
card_number: req_card.card_number.clone(),
card_expiry_month: req_card.card_exp_month.clone(),
card_expiry_year: req_card.card_exp_year.clone(),
card_cvc: req_card.card_cvc.clone(),
card_holder: item.router_data.get_billing_full_name()?,
});
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type: NovalNetPaymentTypes::CREDITCARD,
amount: NovalNetAmount::StringMinor(item.amount.clone()),
currency: item.router_data.request.currency,
order_no: item.router_data.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: Some(return_url.clone()),
error_return_url: Some(return_url.clone()),
payment_data: Some(novalnet_card),
enforce_3d,
create_token,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletDataPaymentMethod::GooglePay(ref req_wallet) => {
let novalnet_google_pay: NovalNetPaymentData =
NovalNetPaymentData::GooglePay(NovalnetGooglePay {
wallet_data: Secret::new(
req_wallet
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(
errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
},
)?
.clone(),
),
});
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type: NovalNetPaymentTypes::GOOGLEPAY,
amount: NovalNetAmount::StringMinor(item.amount.clone()),
currency: item.router_data.request.currency,
order_no: item.router_data.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: None,
error_return_url: None,
payment_data: Some(novalnet_google_pay),
enforce_3d,
create_token,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
WalletDataPaymentMethod::ApplePay(payment_method_data) => {
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type: NovalNetPaymentTypes::APPLEPAY,
amount: NovalNetAmount::StringMinor(item.amount.clone()),
currency: item.router_data.request.currency,
order_no: item.router_data.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: None,
error_return_url: None,
payment_data: Some(NovalNetPaymentData::ApplePay(NovalnetApplePay {
wallet_data: payment_method_data
.get_applepay_decoded_payment_data()?,
})),
enforce_3d: None,
create_token,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
WalletDataPaymentMethod::AliPayQr(_)
| WalletDataPaymentMethod::AliPayRedirect(_)
| WalletDataPaymentMethod::AliPayHkRedirect(_)
| WalletDataPaymentMethod::AmazonPay(_)
| WalletDataPaymentMethod::AmazonPayRedirect(_)
| WalletDataPaymentMethod::Paysera(_)
| WalletDataPaymentMethod::Skrill(_)
| WalletDataPaymentMethod::BluecodeRedirect {}
| WalletDataPaymentMethod::MomoRedirect(_)
| WalletDataPaymentMethod::KakaoPayRedirect(_)
| WalletDataPaymentMethod::GoPayRedirect(_)
| WalletDataPaymentMethod::GcashRedirect(_)
| WalletDataPaymentMethod::ApplePayRedirect(_)
| WalletDataPaymentMethod::ApplePayThirdPartySdk(_)
| WalletDataPaymentMethod::DanaRedirect {}
| WalletDataPaymentMethod::GooglePayRedirect(_)
| WalletDataPaymentMethod::GooglePayThirdPartySdk(_)
| WalletDataPaymentMethod::MbWayRedirect(_)
| WalletDataPaymentMethod::MobilePayRedirect(_)
| WalletDataPaymentMethod::RevolutPay(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("novalnet"),
)
.into())
}
WalletDataPaymentMethod::PaypalRedirect(_) => {
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type: NovalNetPaymentTypes::PAYPAL,
amount: NovalNetAmount::StringMinor(item.amount.clone()),
currency: item.router_data.request.currency,
order_no: item.router_data.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: Some(return_url.clone()),
error_return_url: Some(return_url.clone()),
payment_data: None,
enforce_3d: None,
create_token,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
WalletDataPaymentMethod::PaypalSdk(_)
| WalletDataPaymentMethod::Paze(_)
| WalletDataPaymentMethod::SamsungPay(_)
| WalletDataPaymentMethod::TwintRedirect {}
| WalletDataPaymentMethod::VippsRedirect {}
| WalletDataPaymentMethod::TouchNGoRedirect(_)
| WalletDataPaymentMethod::WeChatPayRedirect(_)
| WalletDataPaymentMethod::CashappQr(_)
| WalletDataPaymentMethod::SwishQr(_)
| WalletDataPaymentMethod::WeChatPayQr(_)
| WalletDataPaymentMethod::Mifinity(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("novalnet"),
)
.into())
}
},
PaymentMethodData::BankDebit(bank_debit_data) => {
let payment_type = NovalNetPaymentTypes::try_from(
&item
.router_data
.request
.payment_method_type
.ok_or(errors::ConnectorError::MissingPaymentMethodType)?,
)?;
let (iban, account_holder, dob) = match bank_debit_data {
BankDebitData::SepaBankDebit {
iban,
bank_account_holder_name,
} => {
let account_holder = match bank_account_holder_name {
Some(name) => name.clone(),
None => item.router_data.get_billing_full_name()?,
};
(iban, account_holder, None)
}
BankDebitData::SepaGuarenteedBankDebit {
iban,
bank_account_holder_name,
} => {
let account_holder = match bank_account_holder_name {
Some(name) => name.clone(),
None => item.router_data.get_billing_full_name()?,
};
(iban, account_holder, Some(String::from("1992-06-10")))
}
_ => {
return Err(
errors::ConnectorError::NotImplemented("SEPA".to_string()).into()
);
}
};
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type,
amount: NovalNetAmount::StringMinor(item.amount.clone()),
currency: item.router_data.request.currency,
order_no: item.router_data.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: Some(return_url.clone()),
error_return_url: Some(return_url.clone()),
payment_data: Some(NovalNetPaymentData::Sepa(NovalnetSepaDebit {
account_holder: account_holder.clone(),
iban: iban.clone(),
birth_date: dob,
})),
enforce_3d,
create_token,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("novalnet"),
)
.into()),
},
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(mandate_data)) => {
let connector_mandate_id = mandate_data.get_connector_mandate_id().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
},
)?;
let novalnet_mandate_data = NovalNetPaymentData::MandatePayment(NovalnetMandate {
token: Secret::new(connector_mandate_id),
});
let payment_type = match item.router_data.request.payment_method_type {
Some(pm_type) => NovalNetPaymentTypes::try_from(&pm_type)?,
None => NovalNetPaymentTypes::CREDITCARD,
};
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type,
amount: NovalNetAmount::StringMinor(item.amount.clone()),
currency: item.router_data.request.currency,
order_no: item.router_data.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: None,
error_return_url: None,
payment_data: Some(novalnet_mandate_data),
enforce_3d,
create_token: None,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
Some(api_models::payments::MandateReferenceId::NetworkMandateId(
network_transaction_id,
)) => match item.router_data.request.payment_method_data {
PaymentMethodData::CardDetailsForNetworkTransactionId(ref raw_card_details) => {
let novalnet_card =
NovalNetPaymentData::RawCardForNTI(NovalnetRawCardDetails {
card_number: raw_card_details.card_number.clone(),
card_expiry_month: raw_card_details.card_exp_month.clone(),
card_expiry_year: raw_card_details.card_exp_year.clone(),
scheme_tid: network_transaction_id.into(),
});
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type: NovalNetPaymentTypes::CREDITCARD,
amount: NovalNetAmount::StringMinor(item.amount.clone()),
currency: item.router_data.request.currency,
order_no: item.router_data.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: Some(return_url.clone()),
error_return_url: Some(return_url.clone()),
payment_data: Some(novalnet_card),
enforce_3d,
create_token,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("novalnet"),
)
.into()),
},
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("novalnet"),
)
.into()),
}
}
}
// Auth Struct
pub struct NovalnetAuthType {
pub(super) product_activation_key: Secret<String>,
pub(super) payment_access_key: Secret<String>,
pub(super) tariff_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for NovalnetAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
product_activation_key: api_key.to_owned(),
payment_access_key: key1.to_owned(),
tariff_id: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
#[derive(Debug, Display, Copy, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NovalnetTransactionStatus {
Success,
Failure,
Confirmed,
OnHold,
Pending,
Deactivated,
Progress,
}
#[derive(Debug, Copy, Display, Clone, Serialize, Deserialize, PartialEq)]
#[strum(serialize_all = "UPPERCASE")]
#[serde(rename_all = "UPPERCASE")]
pub enum NovalnetAPIStatus {
Success,
Failure,
}
impl From<NovalnetTransactionStatus> for common_enums::AttemptStatus {
fn from(item: NovalnetTransactionStatus) -> Self {
match item {
NovalnetTransactionStatus::Success | NovalnetTransactionStatus::Confirmed => {
Self::Charged
}
NovalnetTransactionStatus::OnHold => Self::Authorized,
NovalnetTransactionStatus::Pending => Self::Pending,
NovalnetTransactionStatus::Progress => Self::AuthenticationPending,
NovalnetTransactionStatus::Deactivated => Self::Voided,
NovalnetTransactionStatus::Failure => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResultData {
pub redirect_url: Option<Secret<url::Url>>,
pub status: NovalnetAPIStatus,
pub status_code: u64,
pub status_text: String,
pub additional_message: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetPaymentsResponseTransactionData {
pub amount: Option<MinorUnit>,
pub currency: Option<common_enums::Currency>,
pub date: Option<String>,
pub order_no: Option<String>,
pub payment_data: Option<NovalnetResponsePaymentData>,
pub payment_type: Option<String>,
pub status_code: Option<u64>,
pub txn_secret: Option<Secret<String>>,
pub tid: Option<Secret<i64>>,
pub test_mode: Option<i8>,
pub status: Option<NovalnetTransactionStatus>,
pub authorization: Option<NovalnetAuthorizationResponse>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetPaymentsResponse {
result: ResultData,
transaction: Option<NovalnetPaymentsResponseTransactionData>,
}
pub fn get_error_response(result: ResultData, status_code: u16) -> ErrorResponse {
let error_code = result.status;
let error_reason = result.status_text.clone();
ErrorResponse {
code: error_code.to_string(),
message: error_reason.clone(),
reason: Some(error_reason),
status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
impl NovalnetPaymentsResponseTransactionData {
pub fn get_token(transaction_data: Option<&Self>) -> Option<String> {
if let Some(data) = transaction_data {
match &data.payment_data {
Some(NovalnetResponsePaymentData::Card(card_data)) => {
card_data.token.clone().map(|token| token.expose())
}
Some(NovalnetResponsePaymentData::Paypal(paypal_data)) => {
paypal_data.token.clone().map(|token| token.expose())
}
None => None,
}
} else {
None
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, NovalnetPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, NovalnetPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.result.status {
NovalnetAPIStatus::Success => {
let redirection_data: Option<RedirectForm> =
item.response
.result
.redirect_url
.map(|url| RedirectForm::Form {
endpoint: url.expose().to_string(),
method: Method::Get,
form_fields: HashMap::new(),
});
let transaction_id = item
.response
.transaction
.clone()
.and_then(|data| data.tid.map(|tid| tid.expose().to_string()));
let mandate_reference_id = NovalnetPaymentsResponseTransactionData::get_token(
item.response.transaction.clone().as_ref(),
);
let transaction_status = item
.response
.transaction
.as_ref()
.and_then(|transaction_data| transaction_data.status)
.unwrap_or(if redirection_data.is_some() {
NovalnetTransactionStatus::Progress
// NOTE: Novalnet does not send us the transaction.status for redirection flow
// so status is mapped to Progress if flow has redirection data
} else {
NovalnetTransactionStatus::Pending
});
Ok(Self {
status: common_enums::AttemptStatus::from(transaction_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: transaction_id
.clone()
.map(ResponseId::ConnectorTransactionId)
.unwrap_or(ResponseId::NoResponseId),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference_id.as_ref().map(|id| {
MandateReference {
connector_mandate_id: Some(id.clone()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}
})),
connector_metadata: None,
network_txn_id: item.response.transaction.and_then(|data| {
data.payment_data
.and_then(|payment_data| match payment_data {
NovalnetResponsePaymentData::Card(card) => {
card.scheme_tid.map(|tid| tid.expose())
}
NovalnetResponsePaymentData::Paypal(_) => None,
})
}),
connector_response_reference_id: transaction_id.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
NovalnetAPIStatus::Failure => {
let response = Err(get_error_response(item.response.result, item.http_code));
Ok(Self {
response,
..item.data
})
}
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct NovalnetResponseCustomer {
pub billing: Option<NovalnetResponseBilling>,
pub customer_ip: Option<Secret<String>>,
pub email: Option<Email>,
pub first_name: Option<Secret<String>>,
pub gender: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub mobile: Option<Secret<String>>,
pub tel: Option<Secret<String>>,
pub fax: Option<Secret<String>>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct NovalnetResponseBilling {
pub city: Option<Secret<String>>,
pub country_code: Option<Secret<String>>,
pub house_no: Option<Secret<String>>,
pub street: Option<Secret<String>>,
pub zip: Option<Secret<String>>,
pub state: Option<Secret<String>>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct NovalnetResponseMerchant {
pub project: Option<Secret<i64>>,
pub project_name: Option<Secret<String>>,
pub project_url: Option<url::Url>,
pub vendor: Option<Secret<i64>>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct NovalnetAuthorizationResponse {
expiry_date: Option<String>,
auto_action: Option<String>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct NovalnetSyncResponseTransactionData {
pub amount: Option<MinorUnit>,
pub currency: Option<common_enums::Currency>,
pub date: Option<String>,
pub order_no: Option<String>,
pub payment_data: Option<NovalnetResponsePaymentData>,
pub payment_type: String,
pub status: NovalnetTransactionStatus,
pub status_code: u64,
pub test_mode: u8,
pub tid: Option<Secret<i64>>,
pub txn_secret: Option<Secret<String>>,
pub authorization: Option<NovalnetAuthorizationResponse>,
pub reason: Option<String>,
pub reason_code: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum NovalnetResponsePaymentData {
Card(NovalnetResponseCard),
Paypal(NovalnetResponsePaypal),
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct NovalnetResponseCard {
pub card_brand: Option<Secret<String>>,
pub card_expiry_month: Secret<u8>,
pub card_expiry_year: Secret<u16>,
pub card_holder: Secret<String>,
pub card_number: Secret<String>,
pub cc_3d: Option<Secret<u8>>,
pub last_four: Option<Secret<String>>,
pub token: Option<Secret<String>>,
pub scheme_tid: Option<Secret<String>>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct NovalnetResponsePaypal {
pub paypal_account: Option<Email>,
pub paypal_transaction_id: Option<Secret<String>>,
pub token: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetPSyncResponse {
pub customer: Option<NovalnetResponseCustomer>,
pub merchant: Option<NovalnetResponseMerchant>,
pub result: ResultData,
pub transaction: Option<NovalnetSyncResponseTransactionData>,
}
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum CaptureType {
#[default]
Partial,
Final,
}
#[derive(Default, Debug, Serialize)]
pub struct Capture {
#[serde(rename = "type")]
cap_type: CaptureType,
reference: String,
}
#[derive(Default, Debug, Serialize)]
pub struct NovalnetTransaction {
tid: String,
amount: Option<StringMinorUnit>,
capture: Capture,
}
#[derive(Default, Debug, Serialize)]
pub struct NovalnetCaptureRequest {
pub transaction: NovalnetTransaction,
pub custom: NovalnetCustom,
}
impl TryFrom<&NovalnetRouterData<&PaymentsCaptureRouterData>> for NovalnetCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &NovalnetRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let capture_type = CaptureType::Final;
let reference = item.router_data.connector_request_reference_id.clone();
let capture = Capture {
cap_type: capture_type,
reference,
};
let transaction = NovalnetTransaction {
tid: item.router_data.request.connector_transaction_id.clone(),
capture,
amount: Some(item.amount.to_owned()),
};
let custom = NovalnetCustom {
lang: item
.router_data
.request
.get_optional_language_from_browser_info()
.unwrap_or(consts::DEFAULT_LOCALE.to_string()),
};
Ok(Self {
transaction,
custom,
})
}
}
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct NovalnetRefundTransaction {
tid: String,
amount: Option<StringMinorUnit>,
}
#[derive(Default, Debug, Serialize)]
pub struct NovalnetRefundRequest {
pub transaction: NovalnetRefundTransaction,
pub custom: NovalnetCustom,
}
impl<F> TryFrom<&NovalnetRouterData<&RefundsRouterData<F>>> for NovalnetRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &NovalnetRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let transaction = NovalnetRefundTransaction {
tid: item.router_data.request.connector_transaction_id.clone(),
amount: Some(item.amount.to_owned()),
};
let custom = NovalnetCustom {
lang: item
.router_data
.request
.get_optional_language_from_browser_info()
.unwrap_or(consts::DEFAULT_LOCALE.to_string().to_string()),
};
Ok(Self {
transaction,
custom,
})
}
}
impl From<NovalnetTransactionStatus> for enums::RefundStatus {
fn from(item: NovalnetTransactionStatus) -> Self {
match item {
NovalnetTransactionStatus::Success | NovalnetTransactionStatus::Confirmed => {
Self::Success
}
NovalnetTransactionStatus::Pending => Self::Pending,
NovalnetTransactionStatus::Failure
| NovalnetTransactionStatus::OnHold
| NovalnetTransactionStatus::Deactivated
| NovalnetTransactionStatus::Progress => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetRefundSyncResponse {
result: ResultData,
transaction: Option<NovalnetSyncResponseTransactionData>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetRefundsTransactionData {
pub amount: Option<MinorUnit>,
pub date: Option<String>,
pub currency: Option<common_enums::Currency>,
pub order_no: Option<String>,
pub payment_type: String,
pub refund: RefundData,
pub refunded_amount: Option<u64>,
pub status: NovalnetTransactionStatus,
pub status_code: u64,
pub test_mode: u8,
pub tid: Option<Secret<i64>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundData {
amount: u64,
currency: common_enums::Currency,
payment_type: Option<String>,
tid: Option<Secret<i64>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetRefundResponse {
pub customer: Option<NovalnetResponseCustomer>,
pub merchant: Option<NovalnetResponseMerchant>,
pub result: ResultData,
pub transaction: Option<NovalnetRefundsTransactionData>,
}
impl TryFrom<RefundsResponseRouterData<Execute, NovalnetRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, NovalnetRefundResponse>,
) -> Result<Self, Self::Error> {
match item.response.result.status {
NovalnetAPIStatus::Success => {
let refund_id = item
.response
.transaction
.clone()
.and_then(|data| {
data.refund
.tid
.or(data.tid)
.map(|tid| tid.expose().to_string())
})
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let transaction_status = item
.response
.transaction
.map(|transaction| transaction.status)
.unwrap_or(NovalnetTransactionStatus::Pending);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: refund_id,
refund_status: enums::RefundStatus::from(transaction_status),
}),
..item.data
})
}
NovalnetAPIStatus::Failure => {
let response = Err(get_error_response(item.response.result, item.http_code));
Ok(Self {
response,
..item.data
})
}
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NovolnetRedirectionResponse {
status: NovalnetTransactionStatus,
tid: Secret<String>,
}
impl TryFrom<&PaymentsSyncRouterData> for NovalnetSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let transaction = if item
.request
.encoded_data
.clone()
.get_required_value("encoded_data")
.is_ok()
{
let encoded_data = item
.request
.encoded_data
.clone()
.get_required_value("encoded_data")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let novalnet_redirection_response =
serde_urlencoded::from_str::<NovolnetRedirectionResponse>(encoded_data.as_str())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
NovalnetSyncTransaction {
tid: novalnet_redirection_response.tid.expose(),
}
} else {
NovalnetSyncTransaction {
tid: item
.request
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
}
};
let custom = NovalnetCustom {
lang: consts::DEFAULT_LOCALE.to_string().to_string(),
};
Ok(Self {
transaction,
custom,
})
}
}
impl NovalnetSyncResponseTransactionData {
pub fn get_token(transaction_data: Option<&Self>) -> Option<String> {
if let Some(data) = transaction_data {
match &data.payment_data {
Some(NovalnetResponsePaymentData::Card(card_data)) => {
card_data.token.clone().map(|token| token.expose())
}
Some(NovalnetResponsePaymentData::Paypal(paypal_data)) => {
paypal_data.token.clone().map(|token| token.expose())
}
None => None,
}
} else {
None
}
}
}
impl<F>
TryFrom<ResponseRouterData<F, NovalnetPSyncResponse, PaymentsSyncData, PaymentsResponseData>>
for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, NovalnetPSyncResponse, PaymentsSyncData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.result.status {
NovalnetAPIStatus::Success => {
let transaction_id = item
.response
.transaction
.clone()
.and_then(|data| data.tid)
.map(|tid| tid.expose().to_string());
let transaction_status = item
.response
.transaction
.clone()
.map(|transaction_data| transaction_data.status)
.unwrap_or(NovalnetTransactionStatus::Pending);
let mandate_reference_id = NovalnetSyncResponseTransactionData::get_token(
item.response.transaction.as_ref(),
);
Ok(Self {
status: common_enums::AttemptStatus::from(transaction_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: transaction_id
.clone()
.map(ResponseId::ConnectorTransactionId)
.unwrap_or(ResponseId::NoResponseId),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference_id.as_ref().map(|id| {
MandateReference {
connector_mandate_id: Some(id.clone()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}
})),
connector_metadata: None,
network_txn_id: item.response.transaction.and_then(|data| {
data.payment_data
.and_then(|payment_data| match payment_data {
NovalnetResponsePaymentData::Card(card) => {
card.scheme_tid.map(|tid| tid.expose())
}
NovalnetResponsePaymentData::Paypal(_) => None,
})
}),
connector_response_reference_id: transaction_id.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
NovalnetAPIStatus::Failure => {
let response = Err(get_error_response(item.response.result, item.http_code));
Ok(Self {
response,
..item.data
})
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetCaptureTransactionData {
pub amount: Option<MinorUnit>,
pub capture: Option<CaptureData>, // only for credit card and paypal it is sent back in response
pub currency: Option<common_enums::Currency>,
pub order_no: Option<String>,
pub payment_type: Option<String>,
pub status: Option<NovalnetTransactionStatus>, // required for CreditCard/ApplePay/GooglePay/Paypal
pub status_code: Option<u64>,
pub test_mode: Option<u8>,
pub tid: Option<Secret<i64>>, // mandatory in docs but not being sent back in sepa response -> need to double check
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CaptureData {
amount: Option<u64>,
payment_type: Option<String>,
status: Option<String>,
status_code: u64,
tid: Option<Secret<i64>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetCaptureResponse {
pub result: ResultData,
pub transaction: Option<NovalnetCaptureTransactionData>,
}
impl<F>
TryFrom<
ResponseRouterData<F, NovalnetCaptureResponse, PaymentsCaptureData, PaymentsResponseData>,
> for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
NovalnetCaptureResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.result.status {
NovalnetAPIStatus::Success => {
let transaction_id = item
.response
.transaction
.clone()
.and_then(|data| data.tid.map(|tid| tid.expose().to_string()));
let transaction_status = item
.response
.transaction
.map(|transaction_data| transaction_data.status)
.unwrap_or(Some(NovalnetTransactionStatus::Pending));
Ok(Self {
status: transaction_status
.map(common_enums::AttemptStatus::from)
.unwrap_or(common_enums::AttemptStatus::Pending),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: transaction_id
.clone()
.map(ResponseId::ConnectorTransactionId)
.unwrap_or(ResponseId::NoResponseId),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: transaction_id.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
NovalnetAPIStatus::Failure => {
let response = Err(get_error_response(item.response.result, item.http_code));
Ok(Self {
response,
..item.data
})
}
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct NovalnetSyncTransaction {
tid: String,
}
#[derive(Default, Debug, Serialize)]
pub struct NovalnetSyncRequest {
pub transaction: NovalnetSyncTransaction,
pub custom: NovalnetCustom,
}
impl TryFrom<&RefundSyncRouterData> for NovalnetSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> {
let transaction = NovalnetSyncTransaction {
tid: item.request.connector_transaction_id.clone(),
};
let custom = NovalnetCustom {
lang: item
.request
.get_optional_language_from_browser_info()
.unwrap_or(consts::DEFAULT_LOCALE.to_string().to_string()),
};
Ok(Self {
transaction,
custom,
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, NovalnetRefundSyncResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, NovalnetRefundSyncResponse>,
) -> Result<Self, Self::Error> {
match item.response.result.status {
NovalnetAPIStatus::Success => {
let refund_id = item
.response
.transaction
.clone()
.and_then(|data| data.tid)
.map(|tid| tid.expose().to_string())
.unwrap_or("".to_string());
//NOTE: Mapping refund_id with "" incase we dont get any tid
let transaction_status = item
.response
.transaction
.map(|transaction_data| transaction_data.status)
.unwrap_or(NovalnetTransactionStatus::Pending);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: refund_id,
refund_status: enums::RefundStatus::from(transaction_status),
}),
..item.data
})
}
NovalnetAPIStatus::Failure => {
let response = Err(get_error_response(item.response.result, item.http_code));
Ok(Self {
response,
..item.data
})
}
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct NovalnetCancelTransaction {
tid: String,
}
#[derive(Default, Debug, Serialize)]
pub struct NovalnetCancelRequest {
pub transaction: NovalnetCancelTransaction,
pub custom: NovalnetCustom,
}
impl TryFrom<&PaymentsCancelRouterData> for NovalnetCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let transaction = NovalnetCancelTransaction {
tid: item.request.connector_transaction_id.clone(),
};
let custom = NovalnetCustom {
lang: item
.request
.get_optional_language_from_browser_info()
.unwrap_or(consts::DEFAULT_LOCALE.to_string().to_string()),
};
Ok(Self {
transaction,
custom,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetCancelResponse {
result: ResultData,
transaction: Option<NovalnetPaymentsResponseTransactionData>,
}
impl<F>
TryFrom<ResponseRouterData<F, NovalnetCancelResponse, PaymentsCancelData, PaymentsResponseData>>
for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
NovalnetCancelResponse,
PaymentsCancelData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.result.status {
NovalnetAPIStatus::Success => {
let transaction_id = item
.response
.transaction
.clone()
.and_then(|data| data.tid.map(|tid| tid.expose().to_string()));
let transaction_status = item
.response
.transaction
.and_then(|transaction_data| transaction_data.status)
.unwrap_or(NovalnetTransactionStatus::Pending);
Ok(Self {
status: if transaction_status == NovalnetTransactionStatus::Deactivated {
enums::AttemptStatus::Voided
} else {
enums::AttemptStatus::VoidFailed
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: transaction_id
.clone()
.map(ResponseId::ConnectorTransactionId)
.unwrap_or(ResponseId::NoResponseId),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: transaction_id.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
NovalnetAPIStatus::Failure => {
let response = Err(get_error_response(item.response.result, item.http_code));
Ok(Self {
response,
..item.data
})
}
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct NovalnetErrorResponse {
pub status_code: u64,
pub code: String,
pub message: String,
pub reason: Option<String>,
}
#[derive(Display, Debug, Serialize, Deserialize)]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum WebhookEventType {
Payment,
TransactionCapture,
TransactionCancel,
TransactionRefund,
Chargeback,
Credit,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct NovalnetWebhookEvent {
pub checksum: String,
pub tid: i64,
pub parent_tid: Option<i64>,
#[serde(rename = "type")]
pub event_type: WebhookEventType,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum NovalnetWebhookTransactionData {
SyncTransactionData(NovalnetSyncResponseTransactionData),
CaptureTransactionData(NovalnetCaptureTransactionData),
CancelTransactionData(NovalnetPaymentsResponseTransactionData),
RefundsTransactionData(NovalnetRefundsTransactionData),
}
#[derive(Serialize, Deserialize, Debug)]
pub struct NovalnetWebhookNotificationResponse {
pub event: NovalnetWebhookEvent,
pub result: ResultData,
pub transaction: NovalnetWebhookTransactionData,
}
pub fn is_refund_event(event_code: &WebhookEventType) -> bool {
matches!(event_code, WebhookEventType::TransactionRefund)
}
pub fn get_incoming_webhook_event(
status: WebhookEventType,
transaction_status: NovalnetTransactionStatus,
) -> IncomingWebhookEvent {
match status {
WebhookEventType::Payment => match transaction_status {
NovalnetTransactionStatus::Confirmed | NovalnetTransactionStatus::Success => {
IncomingWebhookEvent::PaymentIntentSuccess
}
NovalnetTransactionStatus::OnHold => {
IncomingWebhookEvent::PaymentIntentAuthorizationSuccess
}
NovalnetTransactionStatus::Pending => IncomingWebhookEvent::PaymentIntentProcessing,
NovalnetTransactionStatus::Progress => IncomingWebhookEvent::EventNotSupported,
_ => IncomingWebhookEvent::PaymentIntentFailure,
},
WebhookEventType::TransactionCapture => match transaction_status {
NovalnetTransactionStatus::Confirmed | NovalnetTransactionStatus::Success => {
IncomingWebhookEvent::PaymentIntentCaptureSuccess
}
_ => IncomingWebhookEvent::PaymentIntentCaptureFailure,
},
WebhookEventType::TransactionCancel => match transaction_status {
NovalnetTransactionStatus::Deactivated => IncomingWebhookEvent::PaymentIntentCancelled,
_ => IncomingWebhookEvent::PaymentIntentCancelFailure,
},
WebhookEventType::TransactionRefund => match transaction_status {
NovalnetTransactionStatus::Confirmed | NovalnetTransactionStatus::Success => {
IncomingWebhookEvent::RefundSuccess
}
_ => IncomingWebhookEvent::RefundFailure,
},
WebhookEventType::Chargeback => IncomingWebhookEvent::DisputeOpened,
WebhookEventType::Credit => IncomingWebhookEvent::DisputeWon,
}
}
pub fn reverse_string(s: &str) -> String {
s.chars().rev().collect()
}
#[derive(Display, Debug, Serialize, Deserialize)]
pub enum WebhookDisputeStatus {
DisputeOpened,
DisputeWon,
Unknown,
}
pub fn get_novalnet_dispute_status(status: WebhookEventType) -> WebhookDisputeStatus {
match status {
WebhookEventType::Chargeback => WebhookDisputeStatus::DisputeOpened,
WebhookEventType::Credit => WebhookDisputeStatus::DisputeWon,
_ => WebhookDisputeStatus::Unknown,
}
}
pub fn option_to_result<T>(opt: Option<T>) -> Result<T, errors::ConnectorError> {
opt.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)
}
impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
let auth = NovalnetAuthType::try_from(&item.connector_auth_type)?;
let merchant = NovalnetPaymentsRequestMerchant {
signature: auth.product_activation_key,
tariff: auth.tariff_id,
};
let enforce_3d = match item.auth_type {
enums::AuthenticationType::ThreeDs => Some(1),
enums::AuthenticationType::NoThreeDs => None,
};
let test_mode = get_test_mode(item.test_mode);
let req_address = item.get_optional_billing();
let billing = NovalnetPaymentsRequestBilling {
house_no: item.get_optional_billing_line1(),
street: item.get_optional_billing_line2(),
city: item.get_optional_billing_city().map(Secret::new),
zip: item.get_optional_billing_zip(),
country_code: item.get_optional_billing_country(),
};
let email = item.get_billing_email().or(item.request.get_email())?;
let customer = NovalnetPaymentsRequestCustomer {
first_name: req_address.and_then(|addr| addr.get_optional_first_name()),
last_name: req_address.and_then(|addr| addr.get_optional_last_name()),
email,
mobile: item.get_optional_billing_phone_number(),
billing: Some(billing),
// no_nc is used to indicate if minimal customer data is passed or not
no_nc: MINIMAL_CUSTOMER_DATA_PASSED,
birth_date: Some(String::from("1992-06-10")),
};
let lang = item
.request
.get_optional_language_from_browser_info()
.unwrap_or(consts::DEFAULT_LOCALE.to_string().to_string());
let custom = NovalnetCustom { lang };
let hook_url = item.request.get_webhook_url()?;
let return_url = item.request.get_return_url()?;
let create_token = Some(CREATE_TOKEN_REQUIRED);
match item.request.payment_method_data {
PaymentMethodData::Card(ref req_card) => {
let novalnet_card = NovalNetPaymentData::Card(NovalnetCard {
card_number: req_card.card_number.clone(),
card_expiry_month: req_card.card_exp_month.clone(),
card_expiry_year: req_card.card_exp_year.clone(),
card_cvc: req_card.card_cvc.clone(),
card_holder: item.get_billing_address()?.get_full_name()?,
});
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type: NovalNetPaymentTypes::CREDITCARD,
amount: NovalNetAmount::Int(0),
currency: item.request.currency,
order_no: item.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: Some(return_url.clone()),
error_return_url: Some(return_url.clone()),
payment_data: Some(novalnet_card),
enforce_3d,
create_token,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletDataPaymentMethod::GooglePay(ref req_wallet) => {
let novalnet_google_pay: NovalNetPaymentData =
NovalNetPaymentData::GooglePay(NovalnetGooglePay {
wallet_data: Secret::new(
req_wallet
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?
.clone(),
),
});
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type: NovalNetPaymentTypes::GOOGLEPAY,
amount: NovalNetAmount::Int(0),
currency: item.request.currency,
order_no: item.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: None,
error_return_url: None,
payment_data: Some(novalnet_google_pay),
enforce_3d,
create_token,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
WalletDataPaymentMethod::ApplePay(payment_method_data) => {
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type: NovalNetPaymentTypes::APPLEPAY,
amount: NovalNetAmount::Int(0),
currency: item.request.currency,
order_no: item.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: None,
error_return_url: None,
payment_data: Some(NovalNetPaymentData::ApplePay(NovalnetApplePay {
wallet_data: payment_method_data.get_applepay_decoded_payment_data()?,
})),
enforce_3d: None,
create_token,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
WalletDataPaymentMethod::AliPayQr(_)
| WalletDataPaymentMethod::AliPayRedirect(_)
| WalletDataPaymentMethod::AliPayHkRedirect(_)
| WalletDataPaymentMethod::AmazonPay(_)
| WalletDataPaymentMethod::AmazonPayRedirect(_)
| WalletDataPaymentMethod::Paysera(_)
| WalletDataPaymentMethod::Skrill(_)
| WalletDataPaymentMethod::BluecodeRedirect {}
| WalletDataPaymentMethod::MomoRedirect(_)
| WalletDataPaymentMethod::KakaoPayRedirect(_)
| WalletDataPaymentMethod::GoPayRedirect(_)
| WalletDataPaymentMethod::GcashRedirect(_)
| WalletDataPaymentMethod::ApplePayRedirect(_)
| WalletDataPaymentMethod::ApplePayThirdPartySdk(_)
| WalletDataPaymentMethod::DanaRedirect {}
| WalletDataPaymentMethod::GooglePayRedirect(_)
| WalletDataPaymentMethod::GooglePayThirdPartySdk(_)
| WalletDataPaymentMethod::MbWayRedirect(_)
| WalletDataPaymentMethod::MobilePayRedirect(_)
| WalletDataPaymentMethod::RevolutPay(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("novalnet"),
))?
}
WalletDataPaymentMethod::PaypalRedirect(_) => {
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type: NovalNetPaymentTypes::PAYPAL,
amount: NovalNetAmount::Int(0),
currency: item.request.currency,
order_no: item.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: Some(return_url.clone()),
error_return_url: Some(return_url.clone()),
payment_data: None,
enforce_3d: None,
create_token,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
WalletDataPaymentMethod::PaypalSdk(_)
| WalletDataPaymentMethod::Paze(_)
| WalletDataPaymentMethod::SamsungPay(_)
| WalletDataPaymentMethod::TwintRedirect {}
| WalletDataPaymentMethod::VippsRedirect {}
| WalletDataPaymentMethod::TouchNGoRedirect(_)
| WalletDataPaymentMethod::WeChatPayRedirect(_)
| WalletDataPaymentMethod::CashappQr(_)
| WalletDataPaymentMethod::SwishQr(_)
| WalletDataPaymentMethod::WeChatPayQr(_)
| WalletDataPaymentMethod::Mifinity(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("novalnet"),
))?
}
},
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("novalnet"),
))?,
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 13307
}
|
large_file_-7231637076629492715
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs
</path>
<file>
use common_enums::enums;
use common_utils::types::MinorUnit;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::{
payments::Void,
refunds::{Execute, RSync},
},
router_request_types::{PaymentsCancelData, ResponseId},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, CardData},
};
//TODO: Fill the struct with respective fields
pub struct SilverflowRouterData<T> {
pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for SilverflowRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
}
}
}
// Basic structures for Silverflow API
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Amount {
value: MinorUnit,
currency: String,
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Card {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
holder_name: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MerchantAcceptorResolver {
merchant_acceptor_key: String,
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowPaymentsRequest {
merchant_acceptor_resolver: MerchantAcceptorResolver,
card: Card,
amount: Amount,
#[serde(rename = "type")]
payment_type: PaymentType,
clearing_mode: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentType {
intent: String,
card_entry: String,
order: String,
}
impl TryFrom<&SilverflowRouterData<&PaymentsAuthorizeRouterData>> for SilverflowPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &SilverflowRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
// Check if 3DS is being requested - Silverflow doesn't support 3DS
if matches!(
item.router_data.auth_type,
enums::AuthenticationType::ThreeDs
) {
return Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("silverflow"),
)
.into());
}
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
// Extract merchant acceptor key from connector auth
let auth = SilverflowAuthType::try_from(&item.router_data.connector_auth_type)?;
let card = Card {
number: req_card.card_number.clone(),
expiry_month: req_card.card_exp_month.clone(),
expiry_year: req_card.card_exp_year.clone(),
cvc: req_card.card_cvc.clone(),
holder_name: req_card.get_cardholder_name().ok(),
};
// Determine clearing mode based on capture method
let clearing_mode = match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual) => "manual".to_string(),
Some(enums::CaptureMethod::Automatic) | None => "auto".to_string(),
Some(enums::CaptureMethod::ManualMultiple)
| Some(enums::CaptureMethod::Scheduled)
| Some(enums::CaptureMethod::SequentialAutomatic) => {
return Err(errors::ConnectorError::NotSupported {
message: "Capture method not supported by Silverflow".to_string(),
connector: "Silverflow",
}
.into());
}
};
Ok(Self {
merchant_acceptor_resolver: MerchantAcceptorResolver {
merchant_acceptor_key: auth.merchant_acceptor_key.expose(),
},
card,
amount: Amount {
value: item.amount,
currency: item.router_data.request.currency.to_string(),
},
payment_type: PaymentType {
intent: "purchase".to_string(),
card_entry: "e-commerce".to_string(),
order: "checkout".to_string(),
},
clearing_mode,
})
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("silverflow"),
)
.into()),
}
}
}
// Auth Struct for HTTP Basic Authentication
pub struct SilverflowAuthType {
pub(super) api_key: Secret<String>,
pub(super) api_secret: Secret<String>,
pub(super) merchant_acceptor_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for SilverflowAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
api_key: api_key.clone(),
api_secret: api_secret.clone(),
merchant_acceptor_key: key1.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// Enum for Silverflow payment authorization status
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SilverflowAuthorizationStatus {
Approved,
Declined,
Failed,
#[default]
Pending,
}
// Enum for Silverflow payment clearing status
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SilverflowClearingStatus {
Cleared,
#[default]
Pending,
Failed,
}
// Payment Authorization Response Structures
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PaymentStatus {
pub authentication: String,
pub authorization: SilverflowAuthorizationStatus,
pub clearing: SilverflowClearingStatus,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct MerchantAcceptorRef {
pub key: String,
pub version: i32,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CardResponse {
pub masked_number: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Authentication {
pub sca: SCA,
pub cvc: Secret<String>,
pub avs: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SCA {
pub compliance: String,
pub compliance_reason: String,
pub method: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<SCAResult>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SCAResult {
pub version: String,
pub directory_server_trans_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizationIsoFields {
pub response_code: String,
pub response_code_description: String,
pub authorization_code: String,
pub network_code: String,
pub system_trace_audit_number: Secret<String>,
pub retrieval_reference_number: String,
pub eci: String,
pub network_specific_fields: NetworkSpecificFields,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct NetworkSpecificFields {
pub transaction_identifier: String,
pub cvv2_result_code: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowPaymentsResponse {
pub key: String,
pub merchant_acceptor_ref: MerchantAcceptorRef,
pub card: CardResponse,
pub amount: Amount,
#[serde(rename = "type")]
pub payment_type: PaymentType,
pub clearing_mode: String,
pub status: PaymentStatus,
pub authentication: Authentication,
pub local_transaction_date_time: String,
pub fraud_liability: String,
pub authorization_iso_fields: Option<AuthorizationIsoFields>,
pub created: String,
pub version: i32,
}
impl From<&PaymentStatus> for common_enums::AttemptStatus {
fn from(status: &PaymentStatus) -> Self {
match (&status.authorization, &status.clearing) {
(SilverflowAuthorizationStatus::Approved, SilverflowClearingStatus::Cleared) => {
Self::Charged
}
(SilverflowAuthorizationStatus::Approved, SilverflowClearingStatus::Pending) => {
Self::Authorized
}
(SilverflowAuthorizationStatus::Approved, SilverflowClearingStatus::Failed) => {
Self::Failure
}
(SilverflowAuthorizationStatus::Declined, _) => Self::Failure,
(SilverflowAuthorizationStatus::Failed, _) => Self::Failure,
(SilverflowAuthorizationStatus::Pending, _) => Self::Pending,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, SilverflowPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SilverflowPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(&item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.key.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: item
.response
.authorization_iso_fields
.as_ref()
.map(|fields| {
fields
.network_specific_fields
.transaction_identifier
.clone()
}),
connector_response_reference_id: Some(item.response.key.clone()),
incremental_authorization_allowed: Some(false),
charges: None,
}),
..item.data
})
}
}
// CAPTURE:
// Type definition for CaptureRequest based on Silverflow API documentation
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowCaptureRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub close_charge: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reference: Option<String>,
}
impl TryFrom<&PaymentsCaptureRouterData> for SilverflowCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
// amount_to_capture is directly an i64, representing the amount in minor units
let amount_to_capture = Some(item.request.amount_to_capture);
Ok(Self {
amount: amount_to_capture,
close_charge: Some(true), // Default to closing charge after capture
reference: Some(format!("capture-{}", item.payment_id)),
})
}
}
// Enum for Silverflow capture status
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SilverflowCaptureStatus {
Completed,
#[default]
Pending,
Failed,
}
// Type definition for CaptureResponse based on Silverflow clearing action response
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowCaptureResponse {
#[serde(rename = "type")]
pub action_type: String,
pub key: String,
pub charge_key: String,
pub status: SilverflowCaptureStatus,
#[serde(skip_serializing_if = "Option::is_none")]
pub reference: Option<String>,
pub amount: Amount,
pub created: String,
pub last_modified: String,
pub version: i32,
}
impl From<&SilverflowCaptureResponse> for common_enums::AttemptStatus {
fn from(response: &SilverflowCaptureResponse) -> Self {
match response.status {
SilverflowCaptureStatus::Completed => Self::Charged,
SilverflowCaptureStatus::Pending => Self::Pending,
SilverflowCaptureStatus::Failed => Self::Failure,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, SilverflowCaptureResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SilverflowCaptureResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(&item.response),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.charge_key.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.key.clone()),
incremental_authorization_allowed: Some(false),
charges: None,
}),
..item.data
})
}
}
// VOID/REVERSE:
// Type definition for Reverse Charge Request based on Silverflow API documentation
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowVoidRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub replacement_amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reference: Option<String>,
}
impl TryFrom<&RouterData<Void, PaymentsCancelData, PaymentsResponseData>>
for SilverflowVoidRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
replacement_amount: Some(0), // Default to 0 for full reversal
reference: Some(format!("void-{}", item.payment_id)),
})
}
}
// Enum for Silverflow void authorization status
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SilverflowVoidAuthorizationStatus {
Approved,
Declined,
Failed,
#[default]
Pending,
}
// Type definition for Void Status (only authorization, no clearing)
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct VoidStatus {
pub authorization: SilverflowVoidAuthorizationStatus,
}
// Type definition for Reverse Charge Response based on Silverflow API documentation
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowVoidResponse {
#[serde(rename = "type")]
pub action_type: String,
pub key: String,
pub charge_key: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub reference: Option<String>,
pub replacement_amount: Amount,
pub status: VoidStatus,
pub authorization_response: Option<AuthorizationResponse>,
pub created: String,
pub last_modified: String,
pub version: i32,
}
impl From<&SilverflowVoidResponse> for common_enums::AttemptStatus {
fn from(response: &SilverflowVoidResponse) -> Self {
match response.status.authorization {
SilverflowVoidAuthorizationStatus::Approved => Self::Voided,
SilverflowVoidAuthorizationStatus::Declined
| SilverflowVoidAuthorizationStatus::Failed => Self::VoidFailed,
SilverflowVoidAuthorizationStatus::Pending => Self::Pending,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, SilverflowVoidResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SilverflowVoidResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(&item.response),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.charge_key.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.key.clone()),
incremental_authorization_allowed: Some(false),
charges: None,
}),
..item.data
})
}
}
// REFUND :
// Type definition for DynamicDescriptor
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DynamicDescriptor {
pub merchant_name: String,
pub merchant_city: String,
}
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct SilverflowRefundRequest {
#[serde(rename = "refundAmount")]
pub refund_amount: MinorUnit,
pub reference: String,
}
impl<F> TryFrom<&SilverflowRouterData<&RefundsRouterData<F>>> for SilverflowRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SilverflowRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
refund_amount: item.amount,
reference: format!("refund-{}", item.router_data.request.refund_id),
})
}
}
// Type definition for Authorization Response
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizationResponse {
pub network: String,
pub response_code: String,
pub response_code_description: String,
}
// Enum for Silverflow refund authorization status
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SilverflowRefundAuthorizationStatus {
Approved,
Declined,
Failed,
Pending,
}
// Enum for Silverflow refund status
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SilverflowRefundStatus {
Success,
Failure,
#[default]
Pending,
}
impl From<&SilverflowRefundStatus> for enums::RefundStatus {
fn from(item: &SilverflowRefundStatus) -> Self {
match item {
SilverflowRefundStatus::Success => Self::Success,
SilverflowRefundStatus::Failure => Self::Failure,
SilverflowRefundStatus::Pending => Self::Pending,
}
}
}
// Type definition for Refund Response
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
#[serde(rename = "type")]
pub action_type: String,
pub key: String,
pub charge_key: String,
pub reference: String,
pub amount: Amount,
pub status: SilverflowRefundStatus,
pub clear_after: Option<String>,
pub authorization_response: Option<AuthorizationResponse>,
pub created: String,
pub last_modified: String,
pub version: i32,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.key.clone(),
refund_status: enums::RefundStatus::from(&item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.key.clone(),
refund_status: enums::RefundStatus::from(&item.response.status),
}),
..item.data
})
}
}
// TOKENIZATION:
// Type definition for TokenizationRequest
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowTokenizationRequest {
pub reference: String,
pub card_data: SilverflowCardData,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowCardData {
pub number: String,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
pub cvc: String,
pub holder_name: String,
}
impl TryFrom<&PaymentsAuthorizeRouterData> for SilverflowTokenizationRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card_data = SilverflowCardData {
number: req_card.card_number.peek().to_string(),
expiry_month: req_card.card_exp_month.clone(),
expiry_year: req_card.card_exp_year.clone(),
cvc: req_card.card_cvc.clone().expose(),
holder_name: req_card
.get_cardholder_name()
.unwrap_or(Secret::new("".to_string()))
.expose(),
};
Ok(Self {
reference: format!("CUSTOMER_ID_{}", item.payment_id),
card_data,
})
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("silverflow"),
)
.into()),
}
}
}
// Add TryFrom implementation for direct tokenization router data
impl
TryFrom<
&RouterData<
hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken,
hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData,
PaymentsResponseData,
>,
> for SilverflowTokenizationRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RouterData<
hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken,
hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card_data = SilverflowCardData {
number: req_card.card_number.peek().to_string(),
expiry_month: req_card.card_exp_month.clone(),
expiry_year: req_card.card_exp_year.clone(),
cvc: req_card.card_cvc.clone().expose(),
holder_name: req_card
.get_cardholder_name()
.unwrap_or(Secret::new("".to_string()))
.expose(),
};
Ok(Self {
reference: format!("CUSTOMER_ID_{}", item.payment_id),
card_data,
})
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("silverflow"),
)
.into()),
}
}
}
// Type definition for TokenizationResponse
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SilverflowTokenizationResponse {
pub key: String,
#[serde(rename = "agentKey")]
pub agent_key: String,
pub last4: String,
pub status: String,
pub reference: String,
#[serde(rename = "cardInfo")]
pub card_info: Vec<CardInfo>,
pub created: String,
#[serde(rename = "cvcPresent")]
pub cvc_present: bool,
pub version: i32,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CardInfo {
#[serde(rename = "infoSource")]
pub info_source: String,
pub network: String,
#[serde(rename = "primaryNetwork")]
pub primary_network: bool,
}
impl<F, T> TryFrom<ResponseRouterData<F, SilverflowTokenizationResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SilverflowTokenizationResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.key,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCardDetails {
pub masked_card_number: String,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
pub card_brand: String,
}
// WEBHOOKS:
// Type definition for Webhook Event structures
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowWebhookEvent {
pub event_type: String,
pub event_data: SilverflowWebhookEventData,
pub event_id: String,
pub created: String,
pub version: i32,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowWebhookEventData {
pub charge_key: Option<String>,
pub refund_key: Option<String>,
pub status: Option<PaymentStatus>,
pub amount: Option<Amount>,
pub transaction_reference: Option<String>,
}
// Error Response Structures based on Silverflow API format
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct ErrorDetails {
pub field: String,
pub issue: String,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct SilverflowErrorResponse {
pub error: SilverflowError,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct SilverflowError {
pub code: String,
pub message: String,
pub details: Option<ErrorDetails>,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5868
}
|
large_file_3603368203943058272
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/celero/transformers.rs
</path>
<file>
use common_enums::{enums, Currency};
use common_utils::{id_type::CustomerId, pii::Email, types::MinorUnit};
use hyperswitch_domain_models::{
address::Address as DomainAddress,
payment_method_data::PaymentMethodData,
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
RouterData,
},
router_flow_types::{
payments::Capture,
refunds::{Execute, RSync},
},
router_request_types::{PaymentsCaptureData, ResponseId},
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
consts,
errors::{self},
};
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
get_unimplemented_payment_method_error_message, AddressDetailsData,
PaymentsAuthorizeRequestData, RefundsRequestData, RouterData as _,
},
};
//TODO: Fill the struct with respective fields
pub struct CeleroRouterData<T> {
pub amount: MinorUnit, // CeleroCommerce expects integer cents
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for CeleroRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
// CeleroCommerce Search Request for sync operations - POST /api/transaction/search
#[derive(Debug, Serialize, PartialEq)]
pub struct CeleroSearchRequest {
transaction_id: String,
}
impl TryFrom<&PaymentsSyncRouterData> for CeleroSearchRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let transaction_id = match &item.request.connector_transaction_id {
ResponseId::ConnectorTransactionId(id) => id.clone(),
_ => {
return Err(errors::ConnectorError::MissingConnectorTransactionID.into());
}
};
Ok(Self { transaction_id })
}
}
impl TryFrom<&RefundSyncRouterData> for CeleroSearchRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> {
Ok(Self {
transaction_id: item.request.get_connector_refund_id()?,
})
}
}
// CeleroCommerce Payment Request according to API specs
#[derive(Debug, Serialize, PartialEq)]
pub struct CeleroPaymentsRequest {
idempotency_key: String,
#[serde(rename = "type")]
transaction_type: TransactionType,
amount: MinorUnit, // CeleroCommerce expects integer cents
currency: Currency,
payment_method: CeleroPaymentMethod,
#[serde(skip_serializing_if = "Option::is_none")]
billing_address: Option<CeleroAddress>,
#[serde(skip_serializing_if = "Option::is_none")]
shipping_address: Option<CeleroAddress>,
#[serde(skip_serializing_if = "Option::is_none")]
create_vault_record: Option<bool>,
// CIT/MIT fields
#[serde(skip_serializing_if = "Option::is_none")]
card_on_file_indicator: Option<CardOnFileIndicator>,
#[serde(skip_serializing_if = "Option::is_none")]
initiated_by: Option<InitiatedBy>,
#[serde(skip_serializing_if = "Option::is_none")]
initial_transaction_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
stored_credential_indicator: Option<StoredCredentialIndicator>,
#[serde(skip_serializing_if = "Option::is_none")]
billing_method: Option<BillingMethod>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CeleroAddress {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address_line_1: Option<Secret<String>>,
address_line_2: Option<Secret<String>>,
city: Option<String>,
state: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
country: Option<common_enums::CountryAlpha2>,
phone: Option<Secret<String>>,
email: Option<Email>,
}
impl TryFrom<&DomainAddress> for CeleroAddress {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(address: &DomainAddress) -> Result<Self, Self::Error> {
let address_details = address.address.as_ref();
match address_details {
Some(address_details) => Ok(Self {
first_name: address_details.get_optional_first_name(),
last_name: address_details.get_optional_last_name(),
address_line_1: address_details.get_optional_line1(),
address_line_2: address_details.get_optional_line2(),
city: address_details.get_optional_city(),
state: address_details.get_optional_state(),
postal_code: address_details.get_optional_zip(),
country: address_details.get_optional_country(),
phone: address
.phone
.as_ref()
.and_then(|phone| phone.number.clone()),
email: address.email.clone(),
}),
None => Err(errors::ConnectorError::MissingRequiredField {
field_name: "address_details",
}
.into()),
}
}
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CeleroPaymentMethod {
Card(CeleroCard),
Customer(CeleroCustomer),
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CeleroCustomer {
id: Option<CustomerId>,
payment_method_id: Option<String>,
}
#[derive(Debug, Serialize, PartialEq, Clone, Copy)]
#[serde(rename_all = "lowercase")]
pub enum CeleroEntryType {
Keyed,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CeleroCard {
entry_type: CeleroEntryType,
number: cards::CardNumber,
expiration_date: Secret<String>,
cvc: Secret<String>,
}
impl TryFrom<&PaymentMethodData> for CeleroPaymentMethod {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentMethodData) -> Result<Self, Self::Error> {
match item {
PaymentMethodData::Card(req_card) => {
let card = CeleroCard {
entry_type: CeleroEntryType::Keyed,
number: req_card.card_number.clone(),
expiration_date: Secret::new(format!(
"{}/{}",
req_card.card_exp_month.peek(),
req_card.card_exp_year.peek()
)),
cvc: req_card.card_cvc.clone(),
};
Ok(Self::Card(card))
}
PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::MobilePayment(_) => Err(errors::ConnectorError::NotImplemented(
"Selected payment method through celero".to_string(),
)
.into()),
}
}
}
// Implementation for handling 3DS specifically
impl TryFrom<(&PaymentMethodData, bool)> for CeleroPaymentMethod {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((item, is_three_ds): (&PaymentMethodData, bool)) -> Result<Self, Self::Error> {
// If 3DS is requested, return an error
if is_three_ds {
return Err(errors::ConnectorError::NotSupported {
message: "Cards 3DS".to_string(),
connector: "celero",
}
.into());
}
// Otherwise, delegate to the standard implementation
Self::try_from(item)
}
}
impl TryFrom<&CeleroRouterData<&PaymentsAuthorizeRouterData>> for CeleroPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CeleroRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let is_auto_capture = item.router_data.request.is_auto_capture()?;
let transaction_type = if is_auto_capture {
TransactionType::Sale
} else {
TransactionType::Authorize
};
let billing_address: Option<CeleroAddress> = item
.router_data
.get_optional_billing()
.and_then(|address| address.try_into().ok());
let shipping_address: Option<CeleroAddress> = item
.router_data
.get_optional_shipping()
.and_then(|address| address.try_into().ok());
// Determine CIT/MIT fields based on mandate data
let (mandate_fields, payment_method) = determine_cit_mit_fields(item.router_data)?;
let request = Self {
idempotency_key: item.router_data.connector_request_reference_id.clone(),
transaction_type,
amount: item.amount,
currency: item.router_data.request.currency,
payment_method,
billing_address,
shipping_address,
create_vault_record: Some(false),
card_on_file_indicator: mandate_fields.card_on_file_indicator,
initiated_by: mandate_fields.initiated_by,
initial_transaction_id: mandate_fields.initial_transaction_id,
stored_credential_indicator: mandate_fields.stored_credential_indicator,
billing_method: mandate_fields.billing_method,
};
Ok(request)
}
}
// Define a struct to hold CIT/MIT fields to avoid complex tuple return type
#[derive(Debug, Default)]
pub struct CeleroMandateFields {
pub card_on_file_indicator: Option<CardOnFileIndicator>,
pub initiated_by: Option<InitiatedBy>,
pub initial_transaction_id: Option<String>,
pub stored_credential_indicator: Option<StoredCredentialIndicator>,
pub billing_method: Option<BillingMethod>,
}
// Helper function to determine CIT/MIT fields based on mandate data
fn determine_cit_mit_fields(
router_data: &PaymentsAuthorizeRouterData,
) -> Result<(CeleroMandateFields, CeleroPaymentMethod), error_stack::Report<errors::ConnectorError>>
{
// Default null values
let mut mandate_fields = CeleroMandateFields::default();
// First check if there's a mandate_id in the request
match router_data
.request
.mandate_id
.clone()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id)
{
// If there's a connector mandate ID, this is a MIT (Merchant Initiated Transaction)
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_id,
)) => {
mandate_fields.card_on_file_indicator = Some(CardOnFileIndicator::RecurringPayment);
mandate_fields.initiated_by = Some(InitiatedBy::Merchant); // This is a MIT
mandate_fields.stored_credential_indicator = Some(StoredCredentialIndicator::Used);
mandate_fields.billing_method = Some(BillingMethod::Recurring);
mandate_fields.initial_transaction_id =
connector_mandate_id.get_connector_mandate_request_reference_id();
Ok((
mandate_fields,
CeleroPaymentMethod::Customer(CeleroCustomer {
id: Some(router_data.get_customer_id()?),
payment_method_id: connector_mandate_id.get_payment_method_id(),
}),
))
}
// For other mandate types that might not be supported
Some(api_models::payments::MandateReferenceId::NetworkMandateId(_))
| Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_)) => {
// These might need different handling or return an error
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Celero"),
)
.into())
}
// If no mandate ID is present, check if it's a mandate payment
None => {
if router_data.request.is_mandate_payment() {
// This is a customer-initiated transaction for a recurring payment
mandate_fields.initiated_by = Some(InitiatedBy::Customer);
mandate_fields.card_on_file_indicator = Some(CardOnFileIndicator::RecurringPayment);
mandate_fields.billing_method = Some(BillingMethod::Recurring);
mandate_fields.stored_credential_indicator = Some(StoredCredentialIndicator::Used);
}
let is_three_ds = router_data.is_three_ds();
Ok((
mandate_fields,
CeleroPaymentMethod::try_from((
&router_data.request.payment_method_data,
is_three_ds,
))?,
))
}
}
}
// Auth Struct for CeleroCommerce API key authentication
pub struct CeleroAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for CeleroAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// CeleroCommerce API Response Structures
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum CeleroResponseStatus {
#[serde(alias = "success", alias = "Success", alias = "SUCCESS")]
Success,
#[serde(alias = "error", alias = "Error", alias = "ERROR")]
Error,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum CeleroTransactionStatus {
Approved,
Declined,
Error,
Pending,
PendingSettlement,
Settled,
Voided,
Reversed,
}
impl From<CeleroTransactionStatus> for common_enums::AttemptStatus {
fn from(item: CeleroTransactionStatus) -> Self {
match item {
CeleroTransactionStatus::Approved => Self::Authorized,
CeleroTransactionStatus::Settled => Self::Charged,
CeleroTransactionStatus::Declined | CeleroTransactionStatus::Error => Self::Failure,
CeleroTransactionStatus::Pending | CeleroTransactionStatus::PendingSettlement => {
Self::Pending
}
CeleroTransactionStatus::Voided | CeleroTransactionStatus::Reversed => Self::Voided,
}
}
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CeleroCardResponse {
pub status: CeleroTransactionStatus,
pub auth_code: Option<String>,
pub processor_response_code: Option<String>,
pub avs_response_code: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CeleroPaymentMethodResponse {
Card(CeleroCardResponse),
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum TransactionType {
Sale,
Authorize,
}
// CIT/MIT related enums
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum CardOnFileIndicator {
#[serde(rename = "C")]
GeneralPurposeStorage,
#[serde(rename = "R")]
RecurringPayment,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum InitiatedBy {
Customer,
Merchant,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum StoredCredentialIndicator {
Used,
Stored,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum BillingMethod {
Straight,
#[serde(rename = "initial_recurring")]
InitialRecurring,
Recurring,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde_with::skip_serializing_none]
pub struct CeleroTransactionResponseData {
pub id: String,
#[serde(rename = "type")]
pub transaction_type: TransactionType,
pub amount: i64,
pub currency: String,
pub response: CeleroPaymentMethodResponse,
pub billing_address: Option<CeleroAddressResponse>,
pub shipping_address: Option<CeleroAddressResponse>,
// Additional fields from the sample response
pub status: Option<String>,
pub response_code: Option<i32>,
pub customer_id: Option<String>,
pub payment_method_id: Option<String>,
}
impl CeleroTransactionResponseData {
pub fn get_mandate_reference(&self) -> Box<Option<MandateReference>> {
if self.payment_method_id.is_some() {
Box::new(Some(MandateReference {
connector_mandate_id: None,
payment_method_id: self.payment_method_id.clone(),
mandate_metadata: None,
connector_mandate_request_reference_id: Some(self.id.clone()),
}))
} else {
Box::new(None)
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct CeleroAddressResponse {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address_line_1: Option<Secret<String>>,
address_line_2: Option<Secret<String>>,
city: Option<String>,
state: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
country: Option<common_enums::CountryAlpha2>,
phone: Option<Secret<String>>,
email: Option<Secret<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct CeleroPaymentsResponse {
pub status: CeleroResponseStatus,
pub msg: String,
pub data: Option<CeleroTransactionResponseData>,
}
impl<F, T> TryFrom<ResponseRouterData<F, CeleroPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CeleroPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.status {
CeleroResponseStatus::Success => {
if let Some(data) = item.response.data {
let CeleroPaymentMethodResponse::Card(response) = &data.response;
// Check if transaction itself failed despite successful API call
match response.status {
CeleroTransactionStatus::Declined | CeleroTransactionStatus::Error => {
// Transaction failed - create error response with transaction details
let error_details = CeleroErrorDetails::from_transaction_response(
response,
item.response.msg,
);
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(
hyperswitch_domain_models::router_data::ErrorResponse {
code: error_details
.error_code
.unwrap_or_else(|| "TRANSACTION_FAILED".to_string()),
message: error_details.error_message,
reason: error_details.decline_reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(data.id),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
},
),
..item.data
})
}
_ => {
let connector_response_data =
convert_to_additional_payment_method_connector_response(
response.avs_response_code.clone(),
)
.map(ConnectorResponseData::with_additional_payment_method_data);
let final_status: enums::AttemptStatus = response.status.into();
Ok(Self {
status: final_status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
data.id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: data.get_mandate_reference(),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: response.auth_code.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
connector_response: connector_response_data,
..item.data
})
}
}
} else {
// No transaction data in successful response
// We don't have a transaction ID in this case
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: "MISSING_DATA".to_string(),
message: "No transaction data in response".to_string(),
reason: Some(item.response.msg),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
CeleroResponseStatus::Error => {
// Top-level API error
let error_details =
CeleroErrorDetails::from_top_level_error(item.response.msg.clone());
// Extract transaction ID from the top-level data if available
let connector_transaction_id =
item.response.data.as_ref().map(|data| data.id.clone());
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: error_details
.error_code
.unwrap_or_else(|| "API_ERROR".to_string()),
message: error_details.error_message,
reason: error_details.decline_reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
}
// CAPTURE:
// Type definition for CaptureRequest
#[derive(Default, Debug, Serialize)]
pub struct CeleroCaptureRequest {
pub amount: MinorUnit,
#[serde(skip_serializing_if = "Option::is_none")]
pub order_id: Option<String>,
}
impl TryFrom<&CeleroRouterData<&PaymentsCaptureRouterData>> for CeleroCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &CeleroRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
order_id: Some(item.router_data.payment_id.clone()),
})
}
}
// CeleroCommerce Capture Response
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CeleroCaptureResponse {
pub status: CeleroResponseStatus,
pub msg: Option<String>,
pub data: Option<serde_json::Value>, // Usually null for capture responses
}
impl
TryFrom<
ResponseRouterData<
Capture,
CeleroCaptureResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
> for RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
Capture,
CeleroCaptureResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.status {
CeleroResponseStatus::Success => Ok(Self {
status: common_enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.data.request.connector_transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
CeleroResponseStatus::Error => Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: "CAPTURE_FAILED".to_string(),
message: item
.response
.msg
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: None,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(
item.data.request.connector_transaction_id.clone(),
),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
// CeleroCommerce Void Response - matches API spec format
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CeleroVoidResponse {
pub status: CeleroResponseStatus,
pub msg: String,
pub data: Option<serde_json::Value>, // Usually null for void responses
}
impl
TryFrom<
ResponseRouterData<
hyperswitch_domain_models::router_flow_types::payments::Void,
CeleroVoidResponse,
hyperswitch_domain_models::router_request_types::PaymentsCancelData,
PaymentsResponseData,
>,
>
for RouterData<
hyperswitch_domain_models::router_flow_types::payments::Void,
hyperswitch_domain_models::router_request_types::PaymentsCancelData,
PaymentsResponseData,
>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
hyperswitch_domain_models::router_flow_types::payments::Void,
CeleroVoidResponse,
hyperswitch_domain_models::router_request_types::PaymentsCancelData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.status {
CeleroResponseStatus::Success => Ok(Self {
status: common_enums::AttemptStatus::Voided,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.data.request.connector_transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
CeleroResponseStatus::Error => Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: "VOID_FAILED".to_string(),
message: item.response.msg.clone(),
reason: Some(item.response.msg),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(
item.data.request.connector_transaction_id.clone(),
),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct CeleroRefundRequest {
pub amount: MinorUnit,
pub surcharge: MinorUnit, // Required field as per API specification
}
impl<F> TryFrom<&CeleroRouterData<&RefundsRouterData<F>>> for CeleroRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &CeleroRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
surcharge: MinorUnit::zero(), // Default to 0 as per API specification
})
}
}
// CeleroCommerce Refund Response - matches API spec format
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CeleroRefundResponse {
pub status: CeleroResponseStatus,
pub msg: String,
pub data: Option<serde_json::Value>, // Usually null for refund responses
}
impl TryFrom<RefundsResponseRouterData<Execute, CeleroRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, CeleroRefundResponse>,
) -> Result<Self, Self::Error> {
match item.response.status {
CeleroResponseStatus::Success => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.data.request.refund_id.clone(),
refund_status: enums::RefundStatus::Success,
}),
..item.data
}),
CeleroResponseStatus::Error => Ok(Self {
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: "REFUND_FAILED".to_string(),
message: item.response.msg.clone(),
reason: Some(item.response.msg),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(
item.data.request.connector_transaction_id.clone(),
),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
impl TryFrom<RefundsResponseRouterData<RSync, CeleroRefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, CeleroRefundResponse>,
) -> Result<Self, Self::Error> {
match item.response.status {
CeleroResponseStatus::Success => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.data.request.refund_id.clone(),
refund_status: enums::RefundStatus::Success,
}),
..item.data
}),
CeleroResponseStatus::Error => Ok(Self {
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: "REFUND_SYNC_FAILED".to_string(),
message: item.response.msg.clone(),
reason: Some(item.response.msg),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(
item.data.request.connector_transaction_id.clone(),
),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
// CeleroCommerce Error Response Structures
// Main error response structure - matches API spec format
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CeleroErrorResponse {
pub status: CeleroResponseStatus,
pub msg: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<serde_json::Value>,
}
// Error details that can be extracted from various response fields
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CeleroErrorDetails {
pub error_code: Option<String>,
pub error_message: String,
pub processor_response_code: Option<String>,
pub decline_reason: Option<String>,
}
impl From<CeleroErrorResponse> for CeleroErrorDetails {
fn from(error_response: CeleroErrorResponse) -> Self {
Self {
error_code: Some("API_ERROR".to_string()),
error_message: error_response.msg,
processor_response_code: None,
decline_reason: None,
}
}
}
// Function to extract error details from transaction response data
impl CeleroErrorDetails {
pub fn from_transaction_response(response: &CeleroCardResponse, msg: String) -> Self {
// Map specific error codes based on common response patterns
let decline_reason = Self::map_processor_error(&response.processor_response_code, &msg);
Self {
error_code: None,
error_message: msg,
processor_response_code: response.processor_response_code.clone(),
decline_reason,
}
}
pub fn from_top_level_error(msg: String) -> Self {
// Map specific error codes from top-level API errors
Self {
error_code: None,
error_message: msg,
processor_response_code: None,
decline_reason: None,
}
}
/// Map processor response codes and messages to specific Hyperswitch error codes
fn map_processor_error(processor_code: &Option<String>, message: &str) -> Option<String> {
let message_lower = message.to_lowercase();
// Check processor response codes if available
if let Some(code) = processor_code {
match code.as_str() {
"05" => Some("TRANSACTION_DECLINED".to_string()),
"14" => Some("INVALID_CARD_DATA".to_string()),
"51" => Some("INSUFFICIENT_FUNDS".to_string()),
"54" => Some("EXPIRED_CARD".to_string()),
"55" => Some("INCORRECT_CVC".to_string()),
"61" => Some("Exceeds withdrawal amount limit".to_string()),
"62" => Some("TRANSACTION_DECLINED".to_string()),
"65" => Some("Exceeds withdrawal frequency limit".to_string()),
"78" => Some("INVALID_CARD_DATA".to_string()),
"91" => Some("PROCESSING_ERROR".to_string()),
"96" => Some("PROCESSING_ERROR".to_string()),
_ => {
router_env::logger::info!(
"Celero response error code ({:?}) is not mapped to any error state ",
code
);
Some("Transaction failed".to_string())
}
}
} else {
Some(message_lower)
}
}
}
pub fn get_avs_definition(code: &str) -> Option<&'static str> {
match code {
"0" => Some("AVS Not Available"),
"A" => Some("Address match only"),
"B" => Some("Address matches, ZIP not verified"),
"C" => Some("Incompatible format"),
"D" => Some("Exact match"),
"F" => Some("Exact match, UK-issued cards"),
"G" => Some("Non-U.S. Issuer does not participate"),
"I" => Some("Not verified"),
"M" => Some("Exact match"),
"N" => Some("No address or ZIP match"),
"P" => Some("Postal Code match"),
"R" => Some("Issuer system unavailable"),
"S" => Some("Service not supported"),
"U" => Some("Address unavailable"),
"W" => Some("9-character numeric ZIP match only"),
"X" => Some("Exact match, 9-character numeric ZIP"),
"Y" => Some("Exact match, 5-character numeric ZIP"),
"Z" => Some("5-character ZIP match only"),
"L" => Some("Partial match, Name and billing postal code match"),
"1" => Some("Cardholder name and ZIP match"),
"2" => Some("Cardholder name, address and ZIP match"),
"3" => Some("Cardholder name and address match"),
"4" => Some("Cardholder name matches"),
"5" => Some("Cardholder name incorrect, ZIP matches"),
"6" => Some("Cardholder name incorrect, address and zip match"),
"7" => Some("Cardholder name incorrect, address matches"),
"8" => Some("Cardholder name, address, and ZIP do not match"),
_ => {
router_env::logger::info!(
"Celero avs response code ({:?}) is not mapped to any definition.",
code
);
None
} // No definition found for the given code
}
}
fn convert_to_additional_payment_method_connector_response(
response_code: Option<String>,
) -> Option<AdditionalPaymentMethodConnectorResponse> {
match response_code {
None => None,
Some(code) => {
let description = get_avs_definition(&code);
let payment_checks = serde_json::json!({
"avs_result_code": code,
"description": description
});
Some(AdditionalPaymentMethodConnectorResponse::Card {
authentication_data: None,
payment_checks: Some(payment_checks),
card_network: None,
domestic_network: None,
})
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/celero/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 7910
}
|
large_file_1403921691105687175
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/opennode/transformers.rs
</path>
<file>
use std::collections::HashMap;
use common_enums::{enums, AttemptStatus};
use common_utils::{request::Method, types::MinorUnit};
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
#[derive(Debug, Serialize)]
pub struct OpennodeRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for OpennodeRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, router_data): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data,
})
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct OpennodePaymentsRequest {
amount: MinorUnit,
currency: String,
description: String,
auto_settle: bool,
success_url: String,
callback_url: String,
order_id: String,
}
impl TryFrom<&OpennodeRouterData<&PaymentsAuthorizeRouterData>> for OpennodePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &OpennodeRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
get_crypto_specific_payment_data(item)
}
}
//TODO: Fill the struct with respective fields
// Auth Struct
pub struct OpennodeAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for OpennodeAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
//TODO: Append the remaining status flags
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum OpennodePaymentStatus {
Unpaid,
Paid,
Expired,
#[default]
Processing,
Underpaid,
Refunded,
#[serde(other)]
Unknown,
}
impl From<OpennodePaymentStatus> for AttemptStatus {
fn from(item: OpennodePaymentStatus) -> Self {
match item {
OpennodePaymentStatus::Unpaid => Self::AuthenticationPending,
OpennodePaymentStatus::Paid => Self::Charged,
OpennodePaymentStatus::Expired => Self::Failure,
OpennodePaymentStatus::Underpaid => Self::Unresolved,
_ => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OpennodePaymentsResponseData {
id: String,
hosted_checkout_url: String,
status: OpennodePaymentStatus,
order_id: Option<String>,
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OpennodePaymentsResponse {
data: OpennodePaymentsResponseData,
}
impl<F, T> TryFrom<ResponseRouterData<F, OpennodePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, OpennodePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let form_fields = HashMap::new();
let redirection_data = RedirectForm::Form {
endpoint: item.response.data.hosted_checkout_url.to_string(),
method: Method::Get,
form_fields,
};
let connector_id = ResponseId::ConnectorTransactionId(item.response.data.id);
let attempt_status = item.response.data.status;
let response_data = if attempt_status != OpennodePaymentStatus::Underpaid {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: connector_id,
redirection_data: Box::new(Some(redirection_data)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.data.order_id,
incremental_authorization_allowed: None,
charges: None,
})
} else {
Ok(PaymentsResponseData::TransactionUnresolvedResponse {
resource_id: connector_id,
reason: Some(api_models::enums::UnresolvedResponseReason {
code: "UNDERPAID".to_string(),
message:
"Please check the transaction in opennode dashboard and resolve manually"
.to_string(),
}),
connector_response_reference_id: item.response.data.order_id,
})
};
Ok(Self {
status: AttemptStatus::from(attempt_status),
response: response_data,
..item.data
})
}
}
//TODO: Fill the struct with respective fields
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct OpennodeRefundRequest {
pub amount: i64,
}
impl<F> TryFrom<&OpennodeRouterData<&RefundsRouterData<F>>> for OpennodeRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &OpennodeRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.router_data.request.refund_amount,
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Refunded,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Refunded => Self::Success,
RefundStatus::Processing => Self::Pending,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
#[derive(Debug, Deserialize, Serialize)]
pub struct OpennodeErrorResponse {
pub message: String,
}
fn get_crypto_specific_payment_data(
item: &OpennodeRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<OpennodePaymentsRequest, error_stack::Report<errors::ConnectorError>> {
let amount = item.amount;
let currency = item.router_data.request.currency.to_string();
let description = item.router_data.get_description()?;
let auto_settle = true;
let success_url = item.router_data.request.get_router_return_url()?;
let callback_url = item.router_data.request.get_webhook_url()?;
let order_id = item.router_data.connector_request_reference_id.clone();
Ok(OpennodePaymentsRequest {
amount,
currency,
description,
auto_settle,
success_url,
callback_url,
order_id,
})
}
#[derive(Debug, Serialize, Deserialize)]
pub struct OpennodeWebhookDetails {
pub id: String,
pub callback_url: String,
pub success_url: String,
pub status: OpennodePaymentStatus,
pub payment_method: String,
pub missing_amt: String,
pub order_id: String,
pub description: String,
pub price: String,
pub fee: String,
pub auto_settle: String,
pub fiat_value: String,
pub net_fiat_value: String,
pub overpaid_by: String,
pub hashed_order: String,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/opennode/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2035
}
|
large_file_4029327214791944118
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs
</path>
<file>
use common_enums::enums;
use common_utils::types::StringMajorUnit;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::CardData as _,
};
//TODO: Fill the struct with respective fields
pub struct FiservemeaRouterData<T> {
pub amount: StringMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for FiservemeaRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize)]
pub struct FiservemeaTransactionAmount {
total: StringMajorUnit,
currency: common_enums::Currency,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaOrder {
order_id: String,
}
#[derive(Debug, Serialize)]
pub enum FiservemeaRequestType {
PaymentCardSaleTransaction,
PaymentCardPreAuthTransaction,
PostAuthTransaction,
VoidPreAuthTransactions,
ReturnTransaction,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaExpiryDate {
month: Secret<String>,
year: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaPaymentCard {
number: cards::CardNumber,
expiry_date: FiservemeaExpiryDate,
security_code: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum FiservemeaPaymentMethods {
PaymentCard(FiservemeaPaymentCard),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaPaymentsRequest {
request_type: FiservemeaRequestType,
merchant_transaction_id: String,
transaction_amount: FiservemeaTransactionAmount,
order: FiservemeaOrder,
payment_method: FiservemeaPaymentMethods,
}
impl TryFrom<&FiservemeaRouterData<&PaymentsAuthorizeRouterData>> for FiservemeaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &FiservemeaRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = FiservemeaPaymentCard {
number: req_card.card_number.clone(),
expiry_date: FiservemeaExpiryDate {
month: req_card.card_exp_month.clone(),
year: req_card.get_card_expiry_year_2_digit()?,
},
security_code: req_card.card_cvc,
};
let request_type = if matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
) {
FiservemeaRequestType::PaymentCardSaleTransaction
} else {
FiservemeaRequestType::PaymentCardPreAuthTransaction
};
Ok(Self {
request_type,
merchant_transaction_id: item
.router_data
.request
.merchant_order_reference_id
.clone()
.unwrap_or(item.router_data.connector_request_reference_id.clone()),
transaction_amount: FiservemeaTransactionAmount {
total: item.amount.clone(),
currency: item.router_data.request.currency,
},
order: FiservemeaOrder {
order_id: item.router_data.connector_request_reference_id.clone(),
},
payment_method: FiservemeaPaymentMethods::PaymentCard(card),
})
}
_ => Err(errors::ConnectorError::NotImplemented(
"Selected payment method through fiservemea".to_string(),
)
.into()),
}
}
}
// Auth Struct
#[derive(Clone)]
pub struct FiservemeaAuthType {
pub(super) api_key: Secret<String>,
pub(super) secret_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for FiservemeaAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
secret_key: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
#[derive(Debug, Serialize, Deserialize)]
pub enum ResponseType {
BadRequest,
Unauthenticated,
Unauthorized,
NotFound,
GatewayDeclined,
EndpointDeclined,
ServerError,
EndpointCommunicationError,
UnsupportedMediaType,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FiservemeaTransactionType {
Sale,
Preauth,
Credit,
ForcedTicket,
Void,
Return,
Postauth,
PayerAuth,
Disbursement,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FiservemeaTransactionOrigin {
Ecom,
Moto,
Mail,
Phone,
Retail,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FiservemeaPaymentStatus {
Approved,
Waiting,
Partial,
ValidationFailed,
ProcessingFailed,
Declined,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FiservemeaPaymentResult {
Approved,
Declined,
Failed,
Waiting,
Partial,
Fraud,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaPaymentCardResponse {
expiry_date: Option<FiservemeaExpiryDate>,
bin: Option<String>,
last4: Option<String>,
brand: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaPaymentMethodDetails {
payment_card: Option<FiservemeaPaymentCardResponse>,
payment_method_type: Option<String>,
payment_method_brand: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Components {
subtotal: Option<f64>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AmountDetails {
total: Option<f64>,
currency: Option<common_enums::Currency>,
components: Option<Components>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AvsResponse {
street_match: Option<String>,
postal_code_match: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Processor {
reference_number: Option<String>,
authorization_code: Option<String>,
response_code: Option<String>,
response_message: Option<String>,
avs_response: Option<AvsResponse>,
security_code_response: Option<String>,
}
fn map_status(
fiservemea_status: Option<FiservemeaPaymentStatus>,
fiservemea_result: Option<FiservemeaPaymentResult>,
transaction_type: FiservemeaTransactionType,
) -> common_enums::AttemptStatus {
match fiservemea_status {
Some(status) => match status {
FiservemeaPaymentStatus::Approved => match transaction_type {
FiservemeaTransactionType::Preauth => common_enums::AttemptStatus::Authorized,
FiservemeaTransactionType::Void => common_enums::AttemptStatus::Voided,
FiservemeaTransactionType::Sale | FiservemeaTransactionType::Postauth => {
common_enums::AttemptStatus::Charged
}
FiservemeaTransactionType::Credit
| FiservemeaTransactionType::ForcedTicket
| FiservemeaTransactionType::Return
| FiservemeaTransactionType::PayerAuth
| FiservemeaTransactionType::Disbursement => common_enums::AttemptStatus::Failure,
},
FiservemeaPaymentStatus::Waiting => common_enums::AttemptStatus::Pending,
FiservemeaPaymentStatus::Partial => common_enums::AttemptStatus::PartialCharged,
FiservemeaPaymentStatus::ValidationFailed
| FiservemeaPaymentStatus::ProcessingFailed
| FiservemeaPaymentStatus::Declined => common_enums::AttemptStatus::Failure,
},
None => match fiservemea_result {
Some(result) => match result {
FiservemeaPaymentResult::Approved => match transaction_type {
FiservemeaTransactionType::Preauth => common_enums::AttemptStatus::Authorized,
FiservemeaTransactionType::Void => common_enums::AttemptStatus::Voided,
FiservemeaTransactionType::Sale | FiservemeaTransactionType::Postauth => {
common_enums::AttemptStatus::Charged
}
FiservemeaTransactionType::Credit
| FiservemeaTransactionType::ForcedTicket
| FiservemeaTransactionType::Return
| FiservemeaTransactionType::PayerAuth
| FiservemeaTransactionType::Disbursement => {
common_enums::AttemptStatus::Failure
}
},
FiservemeaPaymentResult::Waiting => common_enums::AttemptStatus::Pending,
FiservemeaPaymentResult::Partial => common_enums::AttemptStatus::PartialCharged,
FiservemeaPaymentResult::Declined
| FiservemeaPaymentResult::Failed
| FiservemeaPaymentResult::Fraud => common_enums::AttemptStatus::Failure,
},
None => common_enums::AttemptStatus::Pending,
},
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaPaymentsResponse {
response_type: Option<ResponseType>,
#[serde(rename = "type")]
fiservemea_type: Option<String>,
client_request_id: Option<String>,
api_trace_id: Option<String>,
ipg_transaction_id: String,
order_id: Option<String>,
transaction_type: FiservemeaTransactionType,
transaction_origin: Option<FiservemeaTransactionOrigin>,
payment_method_details: Option<FiservemeaPaymentMethodDetails>,
country: Option<Secret<String>>,
terminal_id: Option<String>,
merchant_id: Option<String>,
merchant_transaction_id: Option<String>,
transaction_time: Option<i64>,
approved_amount: Option<AmountDetails>,
transaction_amount: Option<AmountDetails>,
transaction_status: Option<FiservemeaPaymentStatus>, // FiservEMEA Docs mention that this field is deprecated. We are using it for now because transaction_result is not present in the response.
transaction_result: Option<FiservemeaPaymentResult>,
approval_code: Option<String>,
error_message: Option<String>,
transaction_state: Option<String>,
scheme_transaction_id: Option<String>,
processor: Option<Processor>,
}
impl<F, T> TryFrom<ResponseRouterData<F, FiservemeaPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FiservemeaPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: map_status(
item.response.transaction_status,
item.response.transaction_result,
item.response.transaction_type,
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.ipg_transaction_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.order_id,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaCaptureRequest {
request_type: FiservemeaRequestType,
transaction_amount: FiservemeaTransactionAmount,
}
impl TryFrom<&FiservemeaRouterData<&PaymentsCaptureRouterData>> for FiservemeaCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &FiservemeaRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
request_type: FiservemeaRequestType::PostAuthTransaction,
transaction_amount: FiservemeaTransactionAmount {
total: item.amount.clone(),
currency: item.router_data.request.currency,
},
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaVoidRequest {
request_type: FiservemeaRequestType,
}
impl TryFrom<&PaymentsCancelRouterData> for FiservemeaVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(_item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Ok(Self {
request_type: FiservemeaRequestType::VoidPreAuthTransactions,
})
}
}
// REFUND :
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservemeaRefundRequest {
request_type: FiservemeaRequestType,
transaction_amount: FiservemeaTransactionAmount,
}
impl<F> TryFrom<&FiservemeaRouterData<&RefundsRouterData<F>>> for FiservemeaRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &FiservemeaRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
request_type: FiservemeaRequestType::ReturnTransaction,
transaction_amount: FiservemeaTransactionAmount {
total: item.amount.clone(),
currency: item.router_data.request.currency,
},
})
}
}
fn map_refund_status(
fiservemea_status: Option<FiservemeaPaymentStatus>,
fiservemea_result: Option<FiservemeaPaymentResult>,
) -> Result<enums::RefundStatus, errors::ConnectorError> {
match fiservemea_status {
Some(status) => match status {
FiservemeaPaymentStatus::Approved => Ok(enums::RefundStatus::Success),
FiservemeaPaymentStatus::Partial | FiservemeaPaymentStatus::Waiting => {
Ok(enums::RefundStatus::Pending)
}
FiservemeaPaymentStatus::ValidationFailed
| FiservemeaPaymentStatus::ProcessingFailed
| FiservemeaPaymentStatus::Declined => Ok(enums::RefundStatus::Failure),
},
None => match fiservemea_result {
Some(result) => match result {
FiservemeaPaymentResult::Approved => Ok(enums::RefundStatus::Success),
FiservemeaPaymentResult::Partial | FiservemeaPaymentResult::Waiting => {
Ok(enums::RefundStatus::Pending)
}
FiservemeaPaymentResult::Declined
| FiservemeaPaymentResult::Failed
| FiservemeaPaymentResult::Fraud => Ok(enums::RefundStatus::Failure),
},
None => Err(errors::ConnectorError::MissingRequiredField {
field_name: "transactionResult",
}),
},
}
}
impl TryFrom<RefundsResponseRouterData<Execute, FiservemeaPaymentsResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, FiservemeaPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.ipg_transaction_id,
refund_status: map_refund_status(
item.response.transaction_status,
item.response.transaction_result,
)?,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, FiservemeaPaymentsResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, FiservemeaPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.ipg_transaction_id,
refund_status: map_refund_status(
item.response.transaction_status,
item.response.transaction_result,
)?,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ErrorDetails {
pub field: Option<String>,
pub message: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FiservemeaError {
pub code: Option<String>,
pub message: Option<String>,
pub details: Option<Vec<ErrorDetails>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FiservemeaErrorResponse {
#[serde(rename = "type")]
fiservemea_type: Option<String>,
client_request_id: Option<String>,
api_trace_id: Option<String>,
pub response_type: Option<String>,
pub error: Option<FiservemeaError>,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4110
}
|
large_file_-6745100148752920937
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/boku/transformers.rs
</path>
<file>
use std::fmt;
use common_enums::enums;
use common_utils::{request::Method, types::MinorUnit};
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{self, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use url::Url;
use uuid::Uuid;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, AddressDetailsData, RouterData as _},
};
#[derive(Debug, Serialize)]
pub struct BokuRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for BokuRouterData<T> {
fn from((amount, router_data): (MinorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum BokuPaymentsRequest {
BeginSingleCharge(SingleChargeData),
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SingleChargeData {
total_amount: MinorUnit,
currency: String,
country: String,
merchant_id: Secret<String>,
merchant_transaction_id: Secret<String>,
merchant_request_id: String,
merchant_item_description: String,
notification_url: Option<String>,
payment_method: String,
charge_type: String,
hosted: Option<BokuHostedData>,
}
#[derive(Debug, Clone, Serialize)]
pub enum BokuPaymentType {
Dana,
Momo,
Gcash,
GoPay,
Kakaopay,
}
impl fmt::Display for BokuPaymentType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Dana => write!(f, "Dana"),
Self::Momo => write!(f, "Momo"),
Self::Gcash => write!(f, "Gcash"),
Self::GoPay => write!(f, "GoPay"),
Self::Kakaopay => write!(f, "Kakaopay"),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub enum BokuChargeType {
Hosted,
}
impl fmt::Display for BokuChargeType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Hosted => write!(f, "hosted"),
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "kebab-case")]
struct BokuHostedData {
forward_url: String,
}
impl TryFrom<&BokuRouterData<&types::PaymentsAuthorizeRouterData>> for BokuPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BokuRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Wallet(wallet_data) => Self::try_from((item, &wallet_data)),
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("boku"),
))?
}
}
}
}
impl
TryFrom<(
&BokuRouterData<&types::PaymentsAuthorizeRouterData>,
&WalletData,
)> for BokuPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (
&BokuRouterData<&types::PaymentsAuthorizeRouterData>,
&WalletData,
),
) -> Result<Self, Self::Error> {
let (item_router_data, wallet_data) = value;
let item = item_router_data.router_data;
let address = item.get_billing_address()?;
let country = address.get_country()?.to_string();
let payment_method = get_wallet_type(wallet_data)?;
let hosted = get_hosted_data(item);
let auth_type = BokuAuthType::try_from(&item.connector_auth_type)?;
let merchant_item_description = item.get_description()?;
let payment_data = SingleChargeData {
total_amount: item_router_data.amount,
currency: item.request.currency.to_string(),
country,
merchant_id: auth_type.merchant_id,
merchant_transaction_id: Secret::new(item.payment_id.to_string()),
merchant_request_id: Uuid::new_v4().to_string(),
merchant_item_description,
notification_url: item.request.webhook_url.clone(),
payment_method,
charge_type: BokuChargeType::Hosted.to_string(),
hosted,
};
Ok(Self::BeginSingleCharge(payment_data))
}
}
fn get_wallet_type(wallet_data: &WalletData) -> Result<String, errors::ConnectorError> {
match wallet_data {
WalletData::DanaRedirect { .. } => Ok(BokuPaymentType::Dana.to_string()),
WalletData::MomoRedirect { .. } => Ok(BokuPaymentType::Momo.to_string()),
WalletData::GcashRedirect { .. } => Ok(BokuPaymentType::Gcash.to_string()),
WalletData::GoPayRedirect { .. } => Ok(BokuPaymentType::GoPay.to_string()),
WalletData::KakaoPayRedirect { .. } => Ok(BokuPaymentType::Kakaopay.to_string()),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::GooglePay(_)
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("boku"),
)),
}
}
pub struct BokuAuthType {
pub(super) merchant_id: Secret<String>,
pub(super) key_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BokuAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
merchant_id: key1.to_owned(),
key_id: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename = "query-charge-request")]
#[serde(rename_all = "kebab-case")]
pub struct BokuPsyncRequest {
country: String,
merchant_id: Secret<String>,
merchant_transaction_id: Secret<String>,
}
impl TryFrom<&types::PaymentsSyncRouterData> for BokuPsyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let address = item.get_billing_address()?;
let country = address.get_country()?.to_string();
let auth_type = BokuAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
country,
merchant_id: auth_type.merchant_id,
merchant_transaction_id: Secret::new(item.payment_id.to_string()),
})
}
}
// Connector Meta Data
#[derive(Debug, Clone, Deserialize)]
pub struct BokuMetaData {
pub(super) country: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum BokuResponse {
BeginSingleChargeResponse(BokuPaymentsResponse),
QueryChargeResponse(BokuPsyncResponse),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct BokuPaymentsResponse {
charge_status: String, // xml parse only string to fields
charge_id: String,
hosted: Option<HostedUrlResponse>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct HostedUrlResponse {
redirect_url: Option<Url>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename = "query-charge-response")]
#[serde(rename_all = "kebab-case")]
pub struct BokuPsyncResponse {
charges: ChargeResponseData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct ChargeResponseData {
charge: SingleChargeResponseData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SingleChargeResponseData {
charge_status: String,
charge_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, BokuResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BokuResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, transaction_id, redirection_data) = match item.response {
BokuResponse::BeginSingleChargeResponse(response) => get_authorize_response(response),
BokuResponse::QueryChargeResponse(response) => get_psync_response(response),
}?;
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
fn get_response_status(status: String) -> enums::AttemptStatus {
match status.as_str() {
"Success" => enums::AttemptStatus::Charged,
"Failure" => enums::AttemptStatus::Failure,
_ => enums::AttemptStatus::Pending,
}
}
fn get_authorize_response(
response: BokuPaymentsResponse,
) -> Result<(enums::AttemptStatus, String, Option<RedirectForm>), errors::ConnectorError> {
let status = get_response_status(response.charge_status);
let redirection_data = match response.hosted {
Some(hosted_value) => Ok(hosted_value
.redirect_url
.map(|url| RedirectForm::from((url, Method::Get)))),
None => Err(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "redirect_url",
}),
}?;
Ok((status, response.charge_id, redirection_data))
}
fn get_psync_response(
response: BokuPsyncResponse,
) -> Result<(enums::AttemptStatus, String, Option<RedirectForm>), errors::ConnectorError> {
let status = get_response_status(response.charges.charge.charge_status);
Ok((status, response.charges.charge.charge_id, None))
}
// REFUND :
#[derive(Debug, Clone, Serialize)]
#[serde(rename = "refund-charge-request")]
pub struct BokuRefundRequest {
refund_amount: MinorUnit,
merchant_id: Secret<String>,
merchant_request_id: String,
merchant_refund_id: Secret<String>,
charge_id: String,
reason_code: String,
}
#[derive(Debug, Clone, Serialize)]
pub enum BokuRefundReasonCode {
NonFulfillment,
}
impl fmt::Display for BokuRefundReasonCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NonFulfillment => write!(f, "8"),
}
}
}
impl<F> TryFrom<&BokuRouterData<&RefundsRouterData<F>>> for BokuRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &BokuRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let auth_type = BokuAuthType::try_from(&item.router_data.connector_auth_type)?;
let payment_data = Self {
refund_amount: item.amount,
merchant_id: auth_type.merchant_id,
merchant_refund_id: Secret::new(item.router_data.request.refund_id.to_string()),
merchant_request_id: Uuid::new_v4().to_string(),
charge_id: item
.router_data
.request
.connector_transaction_id
.to_string(),
reason_code: BokuRefundReasonCode::NonFulfillment.to_string(),
};
Ok(payment_data)
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename = "refund-charge-response")]
pub struct RefundResponse {
charge_id: String,
refund_status: String,
}
fn get_refund_status(status: String) -> enums::RefundStatus {
match status.as_str() {
"Success" => enums::RefundStatus::Success,
"Failure" => enums::RefundStatus::Failure,
_ => enums::RefundStatus::Pending,
}
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.charge_id,
refund_status: get_refund_status(item.response.refund_status),
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename = "query-refund-request")]
#[serde(rename_all = "kebab-case")]
pub struct BokuRsyncRequest {
country: String,
merchant_id: Secret<String>,
merchant_transaction_id: Secret<String>,
}
impl TryFrom<&types::RefundSyncRouterData> for BokuRsyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
let address = item.get_billing_address()?;
let country = address.get_country()?.to_string();
let auth_type = BokuAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
country,
merchant_id: auth_type.merchant_id,
merchant_transaction_id: Secret::new(item.payment_id.to_string()),
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename = "query-refund-response")]
#[serde(rename_all = "kebab-case")]
pub struct BokuRsyncResponse {
refunds: RefundResponseData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct RefundResponseData {
refund: SingleRefundResponseData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SingleRefundResponseData {
refund_status: String, // quick-xml only parse string as a field
refund_id: String,
}
impl TryFrom<RefundsResponseRouterData<RSync, BokuRsyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, BokuRsyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refunds.refund.refund_id,
refund_status: get_refund_status(item.response.refunds.refund.refund_status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct BokuErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
}
fn get_hosted_data(item: &types::PaymentsAuthorizeRouterData) -> Option<BokuHostedData> {
item.request
.router_return_url
.clone()
.map(|url| BokuHostedData { forward_url: url })
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/boku/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3981
}
|
large_file_-1335163644294856096
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
</path>
<file>
use std::collections::HashMap;
use common_enums::enums;
use common_utils::{pii, request::Method, types::StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm},
types::{self, PaymentsAuthorizeRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData as OtherRouterData,
},
};
#[derive(Debug, Serialize)]
pub struct CoinbaseRouterData<T> {
amount: StringMajorUnit,
router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for CoinbaseRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
pub struct LocalPrice {
pub amount: StringMajorUnit,
pub currency: String,
}
#[derive(Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct Metadata {
pub customer_id: Option<String>,
pub customer_name: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct CoinbasePaymentsRequest {
pub name: Option<Secret<String>>,
pub description: Option<String>,
pub pricing_type: String,
pub local_price: LocalPrice,
pub redirect_url: String,
pub cancel_url: String,
}
impl TryFrom<&CoinbaseRouterData<&PaymentsAuthorizeRouterData>> for CoinbasePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CoinbaseRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
get_crypto_specific_payment_data(item)
}
}
// Auth Struct
pub struct CoinbaseAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for CoinbaseAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(_auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::HeaderKey { api_key } = _auth_type {
Ok(Self {
api_key: api_key.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum CoinbasePaymentStatus {
New,
#[default]
Pending,
Completed,
Expired,
Unresolved,
Resolved,
Canceled,
#[serde(rename = "PENDING REFUND")]
PendingRefund,
Refunded,
}
impl From<CoinbasePaymentStatus> for enums::AttemptStatus {
fn from(item: CoinbasePaymentStatus) -> Self {
match item {
CoinbasePaymentStatus::Completed | CoinbasePaymentStatus::Resolved => Self::Charged,
CoinbasePaymentStatus::Expired => Self::Failure,
CoinbasePaymentStatus::New => Self::AuthenticationPending,
CoinbasePaymentStatus::Unresolved => Self::Unresolved,
CoinbasePaymentStatus::Canceled => Self::Voided,
_ => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, strum::Display)]
#[serde(rename_all = "UPPERCASE")]
#[strum(serialize_all = "UPPERCASE")]
pub enum UnResolvedContext {
Underpaid,
Overpaid,
Delayed,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Timeline {
status: CoinbasePaymentStatus,
context: Option<UnResolvedContext>,
time: String,
pub payment: Option<TimelinePayment>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct CoinbasePaymentsResponse {
// status: CoinbasePaymentStatus,
// id: String,
data: CoinbasePaymentResponseData,
}
impl<F, T> TryFrom<ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let form_fields = HashMap::new();
let redirection_data = RedirectForm::Form {
endpoint: item.response.data.hosted_url.to_string(),
method: Method::Get,
form_fields,
};
let timeline = item
.response
.data
.timeline
.last()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?
.clone();
let connector_id = ResponseId::ConnectorTransactionId(item.response.data.id.clone());
let attempt_status = timeline.status.clone();
let response_data = timeline.context.map_or(
Ok(PaymentsResponseData::TransactionResponse {
resource_id: connector_id.clone(),
redirection_data: Box::new(Some(redirection_data)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.data.id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
|context| {
Ok(PaymentsResponseData::TransactionUnresolvedResponse{
resource_id: connector_id,
reason: Some(api_models::enums::UnresolvedResponseReason {
code: context.to_string(),
message: "Please check the transaction in coinbase dashboard and resolve manually"
.to_string(),
}),
connector_response_reference_id: Some(item.response.data.id),
})
},
);
Ok(Self {
status: enums::AttemptStatus::from(attempt_status),
response: response_data,
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct CoinbaseRefundRequest {}
impl<F> TryFrom<&types::RefundsRouterData<F>> for CoinbaseRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(_item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
Err(errors::ConnectorError::NotImplemented("try_from RefundsRouterData".to_string()).into())
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
_item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Err(errors::ConnectorError::NotImplemented(
"try_from RefundsResponseRouterData".to_string(),
)
.into())
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
_item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Err(errors::ConnectorError::NotImplemented(
"try_from RefundsResponseRouterData".to_string(),
)
.into())
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CoinbaseErrorData {
#[serde(rename = "type")]
pub error_type: String,
pub message: String,
pub code: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CoinbaseErrorResponse {
pub error: CoinbaseErrorData,
}
#[derive(Default, Debug, Deserialize, PartialEq)]
pub struct CoinbaseConnectorMeta {
pub pricing_type: String,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for CoinbaseConnectorMeta {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
utils::to_connector_meta_from_secret(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata" })
}
}
fn get_crypto_specific_payment_data(
item: &CoinbaseRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<CoinbasePaymentsRequest, error_stack::Report<errors::ConnectorError>> {
let billing_address = item
.router_data
.get_billing()
.ok()
.and_then(|billing_address| billing_address.address.as_ref());
let name =
billing_address.and_then(|add| add.get_first_name().ok().map(|name| name.to_owned()));
let description = item.router_data.get_description().ok();
let connector_meta = CoinbaseConnectorMeta::try_from(&item.router_data.connector_meta_data)
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "Merchant connector account metadata",
})?;
let pricing_type = connector_meta.pricing_type;
let local_price = get_local_price(item);
let redirect_url = item.router_data.request.get_router_return_url()?;
let cancel_url = item.router_data.request.get_router_return_url()?;
Ok(CoinbasePaymentsRequest {
name,
description,
pricing_type,
local_price,
redirect_url,
cancel_url,
})
}
fn get_local_price(item: &CoinbaseRouterData<&PaymentsAuthorizeRouterData>) -> LocalPrice {
LocalPrice {
amount: item.amount.clone(),
currency: item.router_data.request.currency.to_string(),
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CoinbaseWebhookDetails {
pub attempt_number: i64,
pub event: Event,
pub id: String,
pub scheduled_for: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Event {
pub api_version: String,
pub created_at: String,
pub data: CoinbasePaymentResponseData,
pub id: String,
pub resource: String,
#[serde(rename = "type")]
pub event_type: WebhookEventType,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum WebhookEventType {
#[serde(rename = "charge:confirmed")]
Confirmed,
#[serde(rename = "charge:created")]
Created,
#[serde(rename = "charge:pending")]
Pending,
#[serde(rename = "charge:failed")]
Failed,
#[serde(rename = "charge:resolved")]
Resolved,
#[serde(other)]
Unknown,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Redirects {
cancel_url: Option<String>,
success_url: Option<String>,
will_redirect_after_success: bool,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct CoinbasePaymentResponseData {
pub id: String,
pub code: String,
pub name: Option<Secret<String>>,
pub utxo: Option<bool>,
pub pricing: HashMap<String, OverpaymentAbsoluteThreshold>,
pub fee_rate: Option<f64>,
pub logo_url: Option<String>,
pub metadata: Option<Metadata>,
pub payments: Vec<PaymentElement>,
pub resource: Option<String>,
pub timeline: Vec<Timeline>,
pub pwcb_only: bool,
pub created_at: String,
pub expires_at: String,
pub hosted_url: String,
pub brand_color: String,
pub description: Option<String>,
pub confirmed_at: Option<String>,
pub fees_settled: Option<bool>,
pub pricing_type: String,
pub redirects: Redirects,
pub support_email: pii::Email,
pub brand_logo_url: String,
pub offchain_eligible: Option<bool>,
pub organization_name: String,
pub payment_threshold: Option<PaymentThreshold>,
pub coinbase_managed_merchant: Option<bool>,
}
#[derive(Debug, Serialize, Default, Deserialize)]
pub struct PaymentThreshold {
pub overpayment_absolute_threshold: OverpaymentAbsoluteThreshold,
pub overpayment_relative_threshold: String,
pub underpayment_absolute_threshold: OverpaymentAbsoluteThreshold,
pub underpayment_relative_threshold: String,
}
#[derive(Debug, Clone, Serialize, Default, Deserialize, PartialEq, Eq)]
pub struct OverpaymentAbsoluteThreshold {
pub amount: StringMajorUnit,
pub currency: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentElement {
pub net: CoinbaseProcessingFee,
pub block: Block,
pub value: CoinbaseProcessingFee,
pub status: String,
pub network: String,
pub deposited: Deposited,
pub payment_id: String,
pub detected_at: String,
pub transaction_id: String,
pub coinbase_processing_fee: CoinbaseProcessingFee,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Block {
pub hash: Option<String>,
pub height: Option<i64>,
pub confirmations: Option<i64>,
pub confirmations_required: Option<i64>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CoinbaseProcessingFee {
pub local: Option<OverpaymentAbsoluteThreshold>,
pub crypto: OverpaymentAbsoluteThreshold,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Deposited {
pub amount: Amount,
pub status: String,
pub destination: String,
pub exchange_rate: Option<serde_json::Value>,
pub autoconversion_status: String,
pub autoconversion_enabled: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Amount {
pub net: CoinbaseProcessingFee,
pub gross: CoinbaseProcessingFee,
pub coinbase_fee: CoinbaseProcessingFee,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TimelinePayment {
pub value: OverpaymentAbsoluteThreshold,
pub network: String,
pub transaction_id: String,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3127
}
|
large_file_-4505302231721727775
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs
</path>
<file>
use std::collections::HashMap;
use base64::Engine;
use common_enums::enums;
use common_utils::{crypto::GenerateDigest, date_time, pii::Email, request::Method};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankTransferData, PaymentMethodData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::{PaymentsSyncData, ResponseId},
router_response_types::{PaymentsResponseData, RedirectForm},
types,
};
use hyperswitch_interfaces::{api, consts::NO_ERROR_CODE, errors};
use masking::{ExposeInterface, Secret};
use ring::digest;
use serde::{Deserialize, Serialize};
use crate::{
types::ResponseRouterData,
utils::{
get_amount_as_string, get_unimplemented_payment_method_error_message,
PaymentsAuthorizeRequestData, RouterData as _,
},
};
mod auth_error {
pub const INVALID_SIGNATURE: &str = "INVALID_SIGNATURE";
}
mod zsl_version {
pub const VERSION_1: &str = "1";
}
pub struct ZslRouterData<T> {
pub amount: String,
pub router_data: T,
}
impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for ZslRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(currency_unit, currency, txn_amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = get_amount_as_string(currency_unit, txn_amount, currency)?;
Ok(Self {
amount,
router_data: item,
})
}
}
pub struct ZslAuthType {
pub(super) api_key: Secret<String>,
pub(super) merchant_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for ZslAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
merchant_id: key1.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZslPaymentsRequest {
process_type: ProcessType,
process_code: ProcessCode,
txn_amt: String,
ccy: api_models::enums::Currency,
mer_ref: String,
mer_txn_date: String,
mer_id: Secret<String>,
lang: String,
success_url: String,
failure_url: String,
success_s2s_url: String,
failure_s2s_url: String,
enctype: EncodingType,
signature: Secret<String>,
country: api_models::enums::CountryAlpha2,
verno: String,
service_code: ServiceCode,
cust_tag: String,
#[serde(flatten)]
payment_method: ZslPaymentMethods,
name: Option<Secret<String>>,
family_name: Option<Secret<String>>,
tel_phone: Option<Secret<String>>,
email: Option<Email>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ZslPaymentMethods {
LocalBankTransfer(LocalBankTransaferRequest),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LocalBankTransaferRequest {
bank_code: Option<String>,
pay_method: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ProcessType {
#[serde(rename = "0200")]
PaymentRequest,
#[serde(rename = "0208")]
PaymentResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ProcessCode {
#[serde(rename = "200002")]
API,
#[serde(rename = "200003")]
CallBack,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EncodingType {
#[serde(rename = "1")]
MD5,
#[serde(rename = "2")]
Sha1,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum ServiceCode {
MPG,
}
impl TryFrom<&ZslRouterData<&types::PaymentsAuthorizeRouterData>> for ZslPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ZslRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payment_method = match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankTransfer(bank_transfer_data) => match *bank_transfer_data {
BankTransferData::LocalBankTransfer { bank_code } => Ok(
ZslPaymentMethods::LocalBankTransfer(LocalBankTransaferRequest {
bank_code,
pay_method: None,
}),
),
BankTransferData::AchBankTransfer { .. }
| BankTransferData::SepaBankTransfer { .. }
| BankTransferData::BacsBankTransfer { .. }
| BankTransferData::MultibancoBankTransfer { .. }
| BankTransferData::PermataBankTransfer { .. }
| BankTransferData::BcaBankTransfer { .. }
| BankTransferData::BniVaBankTransfer { .. }
| BankTransferData::BriVaBankTransfer { .. }
| BankTransferData::CimbVaBankTransfer { .. }
| BankTransferData::DanamonVaBankTransfer { .. }
| BankTransferData::MandiriVaBankTransfer { .. }
| BankTransferData::Pix { .. }
| BankTransferData::Pse {}
| BankTransferData::InstantBankTransferFinland {}
| BankTransferData::InstantBankTransferPoland {}
| BankTransferData::IndonesianBankTransfer { .. }
| BankTransferData::InstantBankTransfer {} => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message(
item.router_data.connector.as_str(),
),
))
}
},
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::OpenBanking(_) => Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message(item.router_data.connector.as_str()),
)),
}?;
let auth_type = ZslAuthType::try_from(&item.router_data.connector_auth_type)?;
let key: Secret<String> = auth_type.api_key;
let mer_id = auth_type.merchant_id;
let mer_txn_date =
date_time::format_date(date_time::now(), date_time::DateFormat::YYYYMMDDHHmmss)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let txn_amt = item.amount.clone();
let ccy = item.router_data.request.currency;
let mer_ref = item.router_data.connector_request_reference_id.clone();
let signature = calculate_signature(
EncodingType::MD5,
ZslSignatureType::RequestSignature {
txn_amt: txn_amt.clone(),
ccy: ccy.to_string(),
mer_ref: mer_ref.clone(),
mer_id: mer_id.clone().expose(),
mer_txn_date: mer_txn_date.clone(),
key: key.expose(),
},
)?;
let tel_phone = item.router_data.get_optional_billing_phone_number();
let email = item.router_data.get_optional_billing_email();
let name = item.router_data.get_optional_billing_first_name();
let family_name = item.router_data.get_optional_billing_last_name();
let router_url = item.router_data.request.get_router_return_url()?;
let webhook_url = item.router_data.request.get_webhook_url()?;
let billing_country = item.router_data.get_billing_country()?;
let lang = item
.router_data
.request
.browser_info
.as_ref()
.and_then(|browser_data| {
browser_data.language.as_ref().map(|language| {
language
.split_once('-')
.map_or(language.to_uppercase(), |(lang, _)| lang.to_uppercase())
})
})
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "browser_info.language",
})?;
let cust_tag = item
.router_data
.customer_id
.clone()
.and_then(|customer_id| {
let cust_id = customer_id.get_string_repr().replace(['_', '-'], "");
let id_len = cust_id.len();
if id_len > 10 {
cust_id.get(id_len - 10..id_len).map(|id| id.to_string())
} else {
Some(cust_id)
}
})
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "customer_id",
})?;
Ok(Self {
process_type: ProcessType::PaymentRequest,
process_code: ProcessCode::API,
txn_amt,
ccy,
mer_ref,
mer_txn_date,
mer_id,
lang,
success_url: router_url.clone(),
failure_url: router_url.clone(),
success_s2s_url: webhook_url.clone(),
failure_s2s_url: webhook_url.clone(),
enctype: EncodingType::MD5,
signature,
verno: zsl_version::VERSION_1.to_owned(),
service_code: ServiceCode::MPG,
country: billing_country,
payment_method,
name,
family_name,
tel_phone,
email,
cust_tag,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZslPaymentsResponse {
process_type: ProcessType,
process_code: ProcessCode,
status: String,
mer_ref: String,
mer_id: String,
enctype: EncodingType,
txn_url: String,
signature: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, ZslPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ZslPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
if item.response.status.eq("0") && !item.response.txn_url.is_empty() {
let auth_type = ZslAuthType::try_from(&item.data.connector_auth_type)?;
let key: Secret<String> = auth_type.api_key;
let mer_id = auth_type.merchant_id;
let calculated_signature = calculate_signature(
item.response.enctype,
ZslSignatureType::ResponseSignature {
status: item.response.status.clone(),
txn_url: item.response.txn_url.clone(),
mer_ref: item.response.mer_ref.clone(),
mer_id: mer_id.clone().expose(),
key: key.expose(),
},
)?;
if calculated_signature.clone().eq(&item.response.signature) {
let decoded_redirect_url_bytes: Vec<u8> = base64::engine::general_purpose::STANDARD
.decode(item.response.txn_url.clone())
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let redirect_url = String::from_utf8(decoded_redirect_url_bytes)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending, // Redirect is always expected after success response
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::Form {
endpoint: redirect_url,
method: Method::Get,
form_fields: HashMap::new(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.mer_ref.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
// When the signature check fails
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: auth_error::INVALID_SIGNATURE.to_string(),
reason: Some(auth_error::INVALID_SIGNATURE.to_string()),
status_code: item.http_code,
attempt_status: Some(enums::AttemptStatus::Failure),
connector_transaction_id: Some(item.response.mer_ref.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
} else {
let error_reason =
ZslResponseStatus::try_from(item.response.status.clone())?.to_string();
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: item.response.status.clone(),
message: error_reason.clone(),
reason: Some(error_reason.clone()),
status_code: item.http_code,
attempt_status: Some(enums::AttemptStatus::Failure),
connector_transaction_id: Some(item.response.mer_ref.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZslWebhookResponse {
pub process_type: ProcessType,
pub process_code: ProcessCode,
pub status: String,
pub txn_id: String,
pub txn_date: String,
pub paid_ccy: api_models::enums::Currency,
pub paid_amt: String,
pub consr_paid_ccy: Option<api_models::enums::Currency>,
pub consr_paid_amt: String,
pub service_fee_ccy: Option<api_models::enums::Currency>,
pub service_fee: Option<String>,
pub txn_amt: String,
pub ccy: String,
pub mer_ref: String,
pub mer_txn_date: String,
pub mer_id: String,
pub enctype: EncodingType,
pub signature: Secret<String>,
}
pub(crate) fn get_status(status: String) -> api_models::webhooks::IncomingWebhookEvent {
match status.as_str() {
//any response with status != 0 are a failed deposit transaction
"0" => api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess,
_ => api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure,
}
}
impl<F> TryFrom<ResponseRouterData<F, ZslWebhookResponse, PaymentsSyncData, PaymentsResponseData>>
for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ZslWebhookResponse, PaymentsSyncData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let paid_amount = item
.response
.consr_paid_amt
.parse::<i64>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
if item.response.status == "0" {
Ok(Self {
status: enums::AttemptStatus::Charged,
amount_captured: Some(paid_amount),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.txn_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.mer_ref.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
let error_reason =
ZslResponseStatus::try_from(item.response.status.clone())?.to_string();
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: item.response.status.clone(),
message: error_reason.clone(),
reason: Some(error_reason.clone()),
status_code: item.http_code,
attempt_status: Some(enums::AttemptStatus::Failure),
connector_transaction_id: Some(item.response.mer_ref.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
impl TryFrom<String> for ZslResponseStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(status: String) -> Result<Self, Self::Error> {
match status.as_str() {
"0" => Ok(Self::Normal),
"1000" => Ok(Self::InternalError),
"1001" => Ok(Self::BreakDownMessageError),
"1002" => Ok(Self::FormatError),
"1004" => Ok(Self::InvalidTransaction),
"1005" => Ok(Self::TransactionCountryNotFound),
"1006" => Ok(Self::MerchantIdNotFound),
"1007" => Ok(Self::AccountDisabled),
"1008" => Ok(Self::DuplicateMerchantReference),
"1009" => Ok(Self::InvalidPayAmount),
"1010" => Ok(Self::PayAmountNotFound),
"1011" => Ok(Self::InvalidCurrencyCode),
"1012" => Ok(Self::CurrencyCodeNotFound),
"1013" => Ok(Self::ReferenceNotFound),
"1014" => Ok(Self::TransmissionTimeNotFound),
"1015" => Ok(Self::PayMethodNotFound),
"1016" => Ok(Self::BankCodeNotFound),
"1017" => Ok(Self::InvalidShowPayPage),
"1018" => Ok(Self::ShowPayPageNotFound),
"1019" => Ok(Self::SuccessUrlNotFound),
"1020" => Ok(Self::SuccessCallbackUrlNotFound),
"1021" => Ok(Self::FailUrlNotFound),
"1022" => Ok(Self::FailCallbackUrlNotFound),
"1023" => Ok(Self::MacNotFound),
"1025" => Ok(Self::OriginalTransactionNotFound),
"1026" => Ok(Self::DeblockDataError),
"1028" => Ok(Self::PspAckNotYetReturn),
"1029" => Ok(Self::BankBranchNameNotFound),
"1030" => Ok(Self::BankAccountIDNotFound),
"1031" => Ok(Self::BankAccountNameNotFound),
"1032" => Ok(Self::IdentityIDNotFound),
"1033" => Ok(Self::ErrorConnectingToPsp),
"1034" => Ok(Self::CountryPspNotAvailable),
"1035" => Ok(Self::UnsupportedPayAmount),
"1036" => Ok(Self::RecordMismatch),
"1037" => Ok(Self::NoRecord),
"1038" => Ok(Self::PspError),
"1039" => Ok(Self::UnsupportedEncryptionType),
"1040" => Ok(Self::ExceedTransactionLimitCount),
"1041" => Ok(Self::ExceedTransactionLimitAmount),
"1042" => Ok(Self::ExceedTransactionAccountLimitCount),
"1043" => Ok(Self::ExceedTransactionAccountLimitAmount),
"1044" => Ok(Self::ExchangeRateError),
"1045" => Ok(Self::InvalidEncoding),
"1046" => Ok(Self::CustomerNameNotFound),
"1047" => Ok(Self::CustomerFamilyNameNotFound),
"1048" => Ok(Self::CustomerTelPhoneNotFound),
"1049" => Ok(Self::InsufficientFund),
"1050" => Ok(Self::ServiceCodeIsMissing),
"1051" => Ok(Self::CurrencyIdNotMatch),
"1052" => Ok(Self::NoPendingRecord),
"1053" => Ok(Self::NoLoadBalancerRuleDefineForTransaction),
"1054" => Ok(Self::NoPaymentProviderAvailable),
"1055" => Ok(Self::UnsupportedPayMethod),
"1056" => Ok(Self::PendingTransaction),
"1057" => Ok(Self::OtherError1059),
"1058" => Ok(Self::OtherError1058),
"1059" => Ok(Self::OtherError1059),
"1084" => Ok(Self::InvalidRequestId),
"5043" => Ok(Self::BeneficiaryBankAccountIsNotAvailable),
"5053" => Ok(Self::BaidNotFound),
"5057" => Ok(Self::InvalidBaid),
"5059" => Ok(Self::InvalidBaidStatus),
"5107" => Ok(Self::AutoUploadBankDisabled),
"5108" => Ok(Self::InvalidNature),
"5109" => Ok(Self::SmsCreateDateNotFound),
"5110" => Ok(Self::InvalidSmsCreateDate),
"5111" => Ok(Self::RecordNotFound),
"5112" => Ok(Self::InsufficientBaidAvailableBalance),
"5113" => Ok(Self::ExceedTxnAmountLimit),
"5114" => Ok(Self::BaidBalanceNotFound),
"5115" => Ok(Self::AutoUploadIndicatorNotFound),
"5116" => Ok(Self::InvalidBankAcctStatus),
"5117" => Ok(Self::InvalidAutoUploadIndicator),
"5118" => Ok(Self::InvalidPidStatus),
"5119" => Ok(Self::InvalidProviderStatus),
"5120" => Ok(Self::InvalidBankAccountSystemSwitchEnabled),
"5121" => Ok(Self::AutoUploadProviderDisabled),
"5122" => Ok(Self::AutoUploadBankNotFound),
"5123" => Ok(Self::AutoUploadBankAcctNotFound),
"5124" => Ok(Self::AutoUploadProviderNotFound),
"5125" => Ok(Self::UnsupportedBankCode),
"5126" => Ok(Self::BalanceOverrideIndicatorNotFound),
"5127" => Ok(Self::InvalidBalanceOverrideIndicator),
"10000" => Ok(Self::VernoInvalid),
"10001" => Ok(Self::ServiceCodeInvalid),
"10002" => Ok(Self::PspResponseSignatureIsNotValid),
"10003" => Ok(Self::ProcessTypeNotFound),
"10004" => Ok(Self::ProcessCodeNotFound),
"10005" => Ok(Self::EnctypeNotFound),
"10006" => Ok(Self::VernoNotFound),
"10007" => Ok(Self::DepositBankNotFound),
"10008" => Ok(Self::DepositFlowNotFound),
"10009" => Ok(Self::CustDepositDateNotFound),
"10010" => Ok(Self::CustTagNotFound),
"10011" => Ok(Self::CountryValueInvalid),
"10012" => Ok(Self::CurrencyCodeValueInvalid),
"10013" => Ok(Self::MerTxnDateInvalid),
"10014" => Ok(Self::CustDepositDateInvalid),
"10015" => Ok(Self::TxnAmtInvalid),
"10016" => Ok(Self::SuccessCallbackUrlInvalid),
"10017" => Ok(Self::DepositFlowInvalid),
"10018" => Ok(Self::ProcessTypeInvalid),
"10019" => Ok(Self::ProcessCodeInvalid),
"10020" => Ok(Self::UnsupportedMerRefLength),
"10021" => Ok(Self::DepositBankLengthOverLimit),
"10022" => Ok(Self::CustTagLengthOverLimit),
"10023" => Ok(Self::SignatureLengthOverLimit),
"10024" => Ok(Self::RequestContainInvalidTag),
"10025" => Ok(Self::RequestSignatureNotMatch),
"10026" => Ok(Self::InvalidCustomer),
"10027" => Ok(Self::SchemeNotFound),
"10028" => Ok(Self::PspResponseFieldsMissing),
"10029" => Ok(Self::PspResponseMerRefNotMatchWithRequestMerRef),
"10030" => Ok(Self::PspResponseMerIdNotMatchWithRequestMerId),
"10031" => Ok(Self::UpdateDepositFailAfterResponse),
"10032" => Ok(Self::UpdateUsedLimitTransactionCountFailAfterSuccessResponse),
"10033" => Ok(Self::UpdateCustomerLastDepositRecordAfterSuccessResponse),
"10034" => Ok(Self::CreateDepositFail),
"10035" => Ok(Self::CreateDepositMsgFail),
"10036" => Ok(Self::UpdateStatusSubStatusFail),
"10037" => Ok(Self::AddDepositRecordToSchemeAccount),
"10038" => Ok(Self::EmptyResponse),
"10039" => Ok(Self::AubConfirmErrorFromPh),
"10040" => Ok(Self::ProviderEmailAddressNotFound),
"10041" => Ok(Self::AubConnectionTimeout),
"10042" => Ok(Self::AubConnectionIssue),
"10043" => Ok(Self::AubMsgTypeMissing),
"10044" => Ok(Self::AubMsgCodeMissing),
"10045" => Ok(Self::AubVersionMissing),
"10046" => Ok(Self::AubEncTypeMissing),
"10047" => Ok(Self::AubSignMissing),
"10048" => Ok(Self::AubInfoMissing),
"10049" => Ok(Self::AubErrorCodeMissing),
"10050" => Ok(Self::AubMsgTypeInvalid),
"10051" => Ok(Self::AubMsgCodeInvalid),
"10052" => Ok(Self::AubBaidMissing),
"10053" => Ok(Self::AubResponseSignNotMatch),
"10054" => Ok(Self::SmsConnectionTimeout),
"10055" => Ok(Self::SmsConnectionIssue),
"10056" => Ok(Self::SmsConfirmErrorFromPh),
"10057" => Ok(Self::SmsMsgTypeMissing),
"10058" => Ok(Self::SmsMsgCodeMissing),
"10059" => Ok(Self::SmsVersionMissing),
"10060" => Ok(Self::SmsEncTypeMissing),
"10061" => Ok(Self::SmsSignMissing),
"10062" => Ok(Self::SmsInfoMissing),
"10063" => Ok(Self::SmsErrorCodeMissing),
"10064" => Ok(Self::SmsMsgTypeInvalid),
"10065" => Ok(Self::SmsMsgCodeInvalid),
"10066" => Ok(Self::SmsResponseSignNotMatch),
"10067" => Ok(Self::SmsRequestReachMaximumLimit),
"10068" => Ok(Self::SyncConnectionTimeout),
"10069" => Ok(Self::SyncConnectionIssue),
"10070" => Ok(Self::SyncConfirmErrorFromPh),
"10071" => Ok(Self::SyncMsgTypeMissing),
"10072" => Ok(Self::SyncMsgCodeMissing),
"10073" => Ok(Self::SyncVersionMissing),
"10074" => Ok(Self::SyncEncTypeMissing),
"10075" => Ok(Self::SyncSignMissing),
"10076" => Ok(Self::SyncInfoMissing),
"10077" => Ok(Self::SyncErrorCodeMissing),
"10078" => Ok(Self::SyncMsgTypeInvalid),
"10079" => Ok(Self::SyncMsgCodeInvalid),
"10080" => Ok(Self::SyncResponseSignNotMatch),
"10081" => Ok(Self::AccountExpired),
"10082" => Ok(Self::ExceedMaxMinAmount),
"10083" => Ok(Self::WholeNumberAmountLessThanOne),
"10084" => Ok(Self::AddDepositRecordToSchemeChannel),
"10085" => Ok(Self::UpdateUtilizedAmountFailAfterSuccessResponse),
"10086" => Ok(Self::PidResponseInvalidFormat),
"10087" => Ok(Self::PspNameNotFound),
"10088" => Ok(Self::LangIsMissing),
"10089" => Ok(Self::FailureCallbackUrlInvalid),
"10090" => Ok(Self::SuccessRedirectUrlInvalid),
"10091" => Ok(Self::FailureRedirectUrlInvalid),
"10092" => Ok(Self::LangValueInvalid),
"10093" => Ok(Self::OnlineDepositSessionTimeout),
"10094" => Ok(Self::AccessPaymentPageRouteFieldMissing),
"10095" => Ok(Self::AmountNotMatch),
"10096" => Ok(Self::PidCallbackFieldsMissing),
"10097" => Ok(Self::TokenNotMatch),
"10098" => Ok(Self::OperationDuplicated),
"10099" => Ok(Self::PayPageDomainNotAvailable),
"10100" => Ok(Self::PayPageConfirmSignatureNotMatch),
"10101" => Ok(Self::PaymentPageConfirmationFieldMissing),
"10102" => Ok(Self::MultipleCallbackFromPsp),
"10103" => Ok(Self::PidNotAvailable),
"10104" => Ok(Self::PidDepositUrlNotValidOrEmp),
"10105" => Ok(Self::PspSelfRedirectTagNotValid),
"20000" => Ok(Self::InternalError20000),
"20001" => Ok(Self::DepositTimeout),
_ => Err(errors::ConnectorError::ResponseHandlingFailed.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, strum::Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ZslResponseStatus {
Normal,
InternalError,
BreakDownMessageError,
FormatError,
InvalidTransaction,
TransactionCountryNotFound,
MerchantIdNotFound,
AccountDisabled,
DuplicateMerchantReference,
InvalidPayAmount,
PayAmountNotFound,
InvalidCurrencyCode,
CurrencyCodeNotFound,
ReferenceNotFound,
TransmissionTimeNotFound,
PayMethodNotFound,
BankCodeNotFound,
InvalidShowPayPage,
ShowPayPageNotFound,
SuccessUrlNotFound,
SuccessCallbackUrlNotFound,
FailUrlNotFound,
FailCallbackUrlNotFound,
MacNotFound,
OriginalTransactionNotFound,
DeblockDataError,
PspAckNotYetReturn,
BankBranchNameNotFound,
BankAccountIDNotFound,
BankAccountNameNotFound,
IdentityIDNotFound,
ErrorConnectingToPsp,
CountryPspNotAvailable,
UnsupportedPayAmount,
RecordMismatch,
NoRecord,
PspError,
UnsupportedEncryptionType,
ExceedTransactionLimitCount,
ExceedTransactionLimitAmount,
ExceedTransactionAccountLimitCount,
ExceedTransactionAccountLimitAmount,
ExchangeRateError,
InvalidEncoding,
CustomerNameNotFound,
CustomerFamilyNameNotFound,
CustomerTelPhoneNotFound,
InsufficientFund,
ServiceCodeIsMissing,
CurrencyIdNotMatch,
NoPendingRecord,
NoLoadBalancerRuleDefineForTransaction,
NoPaymentProviderAvailable,
UnsupportedPayMethod,
PendingTransaction,
OtherError1059,
OtherError1058,
InvalidRequestId,
BeneficiaryBankAccountIsNotAvailable,
BaidNotFound,
InvalidBaid,
InvalidBaidStatus,
AutoUploadBankDisabled,
InvalidNature,
SmsCreateDateNotFound,
InvalidSmsCreateDate,
RecordNotFound,
InsufficientBaidAvailableBalance,
ExceedTxnAmountLimit,
BaidBalanceNotFound,
AutoUploadIndicatorNotFound,
InvalidBankAcctStatus,
InvalidAutoUploadIndicator,
InvalidPidStatus,
InvalidProviderStatus,
InvalidBankAccountSystemSwitchEnabled,
AutoUploadProviderDisabled,
AutoUploadBankNotFound,
AutoUploadBankAcctNotFound,
AutoUploadProviderNotFound,
UnsupportedBankCode,
BalanceOverrideIndicatorNotFound,
InvalidBalanceOverrideIndicator,
VernoInvalid,
ServiceCodeInvalid,
PspResponseSignatureIsNotValid,
ProcessTypeNotFound,
ProcessCodeNotFound,
EnctypeNotFound,
VernoNotFound,
DepositBankNotFound,
DepositFlowNotFound,
CustDepositDateNotFound,
CustTagNotFound,
CountryValueInvalid,
CurrencyCodeValueInvalid,
MerTxnDateInvalid,
CustDepositDateInvalid,
TxnAmtInvalid,
SuccessCallbackUrlInvalid,
DepositFlowInvalid,
ProcessTypeInvalid,
ProcessCodeInvalid,
UnsupportedMerRefLength,
DepositBankLengthOverLimit,
CustTagLengthOverLimit,
SignatureLengthOverLimit,
RequestContainInvalidTag,
RequestSignatureNotMatch,
InvalidCustomer,
SchemeNotFound,
PspResponseFieldsMissing,
PspResponseMerRefNotMatchWithRequestMerRef,
PspResponseMerIdNotMatchWithRequestMerId,
UpdateDepositFailAfterResponse,
UpdateUsedLimitTransactionCountFailAfterSuccessResponse,
UpdateCustomerLastDepositRecordAfterSuccessResponse,
CreateDepositFail,
CreateDepositMsgFail,
UpdateStatusSubStatusFail,
AddDepositRecordToSchemeAccount,
EmptyResponse,
AubConfirmErrorFromPh,
ProviderEmailAddressNotFound,
AubConnectionTimeout,
AubConnectionIssue,
AubMsgTypeMissing,
AubMsgCodeMissing,
AubVersionMissing,
AubEncTypeMissing,
AubSignMissing,
AubInfoMissing,
AubErrorCodeMissing,
AubMsgTypeInvalid,
AubMsgCodeInvalid,
AubBaidMissing,
AubResponseSignNotMatch,
SmsConnectionTimeout,
SmsConnectionIssue,
SmsConfirmErrorFromPh,
SmsMsgTypeMissing,
SmsMsgCodeMissing,
SmsVersionMissing,
SmsEncTypeMissing,
SmsSignMissing,
SmsInfoMissing,
SmsErrorCodeMissing,
SmsMsgTypeInvalid,
SmsMsgCodeInvalid,
SmsResponseSignNotMatch,
SmsRequestReachMaximumLimit,
SyncConnectionTimeout,
SyncConnectionIssue,
SyncConfirmErrorFromPh,
SyncMsgTypeMissing,
SyncMsgCodeMissing,
SyncVersionMissing,
SyncEncTypeMissing,
SyncSignMissing,
SyncInfoMissing,
SyncErrorCodeMissing,
SyncMsgTypeInvalid,
SyncMsgCodeInvalid,
SyncResponseSignNotMatch,
AccountExpired,
ExceedMaxMinAmount,
WholeNumberAmountLessThanOne,
AddDepositRecordToSchemeChannel,
UpdateUtilizedAmountFailAfterSuccessResponse,
PidResponseInvalidFormat,
PspNameNotFound,
LangIsMissing,
FailureCallbackUrlInvalid,
SuccessRedirectUrlInvalid,
FailureRedirectUrlInvalid,
LangValueInvalid,
OnlineDepositSessionTimeout,
AccessPaymentPageRouteFieldMissing,
AmountNotMatch,
PidCallbackFieldsMissing,
TokenNotMatch,
OperationDuplicated,
PayPageDomainNotAvailable,
PayPageConfirmSignatureNotMatch,
PaymentPageConfirmationFieldMissing,
MultipleCallbackFromPsp,
PidNotAvailable,
PidDepositUrlNotValidOrEmp,
PspSelfRedirectTagNotValid,
InternalError20000,
DepositTimeout,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZslErrorResponse {
pub status: String,
}
pub enum ZslSignatureType {
RequestSignature {
txn_amt: String,
ccy: String,
mer_ref: String,
mer_id: String,
mer_txn_date: String,
key: String,
},
ResponseSignature {
status: String,
txn_url: String,
mer_ref: String,
mer_id: String,
key: String,
},
WebhookSignature {
status: String,
txn_id: String,
txn_date: String,
paid_ccy: String,
paid_amt: String,
mer_ref: String,
mer_id: String,
key: String,
},
}
pub fn calculate_signature(
enctype: EncodingType,
signature_data: ZslSignatureType,
) -> Result<Secret<String>, error_stack::Report<errors::ConnectorError>> {
let signature_data = match signature_data {
ZslSignatureType::RequestSignature {
txn_amt,
ccy,
mer_ref,
mer_id,
mer_txn_date,
key,
} => format!("{txn_amt}{ccy}{mer_ref}{mer_id}{mer_txn_date}{key}"),
ZslSignatureType::ResponseSignature {
status,
txn_url,
mer_ref,
mer_id,
key,
} => {
format!("{status}{txn_url}{mer_ref}{mer_id}{key}")
}
ZslSignatureType::WebhookSignature {
status,
txn_id,
txn_date,
paid_ccy,
paid_amt,
mer_ref,
mer_id,
key,
} => format!("{status}{txn_id}{txn_date}{paid_ccy}{paid_amt}{mer_ref}{mer_id}{key}"),
};
let message = signature_data.as_bytes();
let encoded_data = match enctype {
EncodingType::MD5 => hex::encode(
common_utils::crypto::Md5
.generate_digest(message)
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
),
EncodingType::Sha1 => {
hex::encode(digest::digest(&digest::SHA1_FOR_LEGACY_USE_ONLY, message))
}
};
Ok(Secret::new(encoded_data))
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 8634
}
|
large_file_-7127665451112007718
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs
</path>
<file>
use std::collections::HashMap;
use api_models::webhooks::IncomingWebhookEvent;
use common_enums::enums;
use common_utils::{
errors::CustomResult, ext_traits::Encode, request::Method, types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankRedirectData, PaymentMethodData, RealTimePaymentData, UpiData},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
refunds::{Execute, RSync},
Authorize,
},
router_request_types::{PaymentsAuthorizeData, ResponseId},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{self, RefundsRouterData},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{Secret, SwitchStrategy};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
get_unimplemented_payment_method_error_message, is_payment_failure, is_refund_failure,
PaymentsAuthorizeRequestData, RefundsRequestData,
},
};
type Error = error_stack::Report<errors::ConnectorError>;
// Every access token will be valid for 5 minutes. It contains grant_type and scope for different type of access, but for our usecases it should be only 'client_credentials' and 'payment' resp(as per doc) for all type of api call.
#[derive(Debug, Serialize)]
pub struct IatapayAuthUpdateRequest {
grant_type: String,
scope: String,
}
impl TryFrom<&types::RefreshTokenRouterData> for IatapayAuthUpdateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(_item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> {
Ok(Self {
grant_type: "client_credentials".to_string(),
scope: "payment".to_string(),
})
}
}
#[derive(Debug, Serialize)]
pub struct IatapayRouterData<T> {
amount: FloatMajorUnit,
router_data: T,
}
impl<T> TryFrom<(FloatMajorUnit, T)> for IatapayRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (FloatMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct IatapayAuthUpdateResponse {
pub access_token: Secret<String>,
pub expires_in: i64,
}
impl<F, T> TryFrom<ResponseRouterData<F, IatapayAuthUpdateResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, IatapayAuthUpdateResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RedirectUrls {
success_url: String,
failure_url: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayerInfo {
token_id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum PreferredCheckoutMethod {
Vpa, //Passing this in UPI_COLLECT will trigger an S2S payment call which is not required.
Qr,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IatapayPaymentsRequest {
merchant_id: Secret<String>,
merchant_payment_id: Option<String>,
amount: FloatMajorUnit,
currency: common_enums::Currency,
country: common_enums::CountryAlpha2,
locale: String,
redirect_urls: RedirectUrls,
notification_url: String,
#[serde(skip_serializing_if = "Option::is_none")]
payer_info: Option<PayerInfo>,
#[serde(skip_serializing_if = "Option::is_none")]
preferred_checkout_method: Option<PreferredCheckoutMethod>,
}
impl
TryFrom<&IatapayRouterData<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>>>
for IatapayPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &IatapayRouterData<
&RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
>,
) -> Result<Self, Self::Error> {
let return_url = item.router_data.request.get_router_return_url()?;
// Iatapay processes transactions through the payment method selected based on the country
let (country, payer_info, preferred_checkout_method) = match item
.router_data
.request
.payment_method_data
.clone()
{
PaymentMethodData::Upi(upi_type) => match upi_type {
UpiData::UpiCollect(upi_data) => (
common_enums::CountryAlpha2::IN,
upi_data.vpa_id.map(|id| PayerInfo {
token_id: id.switch_strategy(),
}),
None,
),
UpiData::UpiIntent(_) | UpiData::UpiQr(_) => (
common_enums::CountryAlpha2::IN,
None,
Some(PreferredCheckoutMethod::Qr),
),
},
PaymentMethodData::BankRedirect(bank_redirect_data) => match bank_redirect_data {
BankRedirectData::Ideal { .. } => (common_enums::CountryAlpha2::NL, None, None),
BankRedirectData::LocalBankRedirect {} => {
(common_enums::CountryAlpha2::AT, None, None)
}
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Bizum {}
| BankRedirectData::Blik { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Eps { .. }
| BankRedirectData::Giropay { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::Sofort { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. } => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("iatapay"),
))?
}
},
PaymentMethodData::RealTimePayment(real_time_payment_data) => {
match *real_time_payment_data {
RealTimePaymentData::DuitNow {} => {
(common_enums::CountryAlpha2::MY, None, None)
}
RealTimePaymentData::Fps {} => (common_enums::CountryAlpha2::HK, None, None),
RealTimePaymentData::PromptPay {} => {
(common_enums::CountryAlpha2::TH, None, None)
}
RealTimePaymentData::VietQr {} => (common_enums::CountryAlpha2::VN, None, None),
}
}
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("iatapay"),
))?
}
};
let payload = Self {
merchant_id: IatapayAuthType::try_from(&item.router_data.connector_auth_type)?
.merchant_id,
merchant_payment_id: Some(item.router_data.connector_request_reference_id.clone()),
amount: item.amount,
currency: item.router_data.request.currency,
country,
locale: format!("en-{country}"),
redirect_urls: get_redirect_url(return_url),
payer_info,
notification_url: item.router_data.request.get_webhook_url()?,
preferred_checkout_method,
};
Ok(payload)
}
}
fn get_redirect_url(return_url: String) -> RedirectUrls {
RedirectUrls {
success_url: return_url.clone(),
failure_url: return_url,
}
}
// Auth Struct
pub struct IatapayAuthType {
pub(super) client_id: Secret<String>,
pub(super) merchant_id: Secret<String>,
pub(super) client_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for IatapayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
client_id: api_key.to_owned(),
merchant_id: key1.to_owned(),
client_secret: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum IatapayPaymentStatus {
#[default]
Created,
Initiated,
Authorized,
Settled,
Cleared,
Failed,
#[serde(rename = "UNEXPECTED SETTLED")]
UnexpectedSettled,
}
impl From<IatapayPaymentStatus> for enums::AttemptStatus {
fn from(item: IatapayPaymentStatus) -> Self {
match item {
IatapayPaymentStatus::Authorized
| IatapayPaymentStatus::Settled
| IatapayPaymentStatus::Cleared => Self::Charged,
IatapayPaymentStatus::Failed | IatapayPaymentStatus::UnexpectedSettled => Self::Failure,
IatapayPaymentStatus::Created => Self::AuthenticationPending,
IatapayPaymentStatus::Initiated => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RedirectUrl {
pub redirect_url: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckoutMethod {
pub redirect: RedirectUrl,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IatapayPaymentsResponse {
pub status: IatapayPaymentStatus,
pub iata_payment_id: Option<String>,
pub iata_refund_id: Option<String>,
pub merchant_id: Option<Secret<String>>,
pub merchant_payment_id: Option<String>,
pub amount: FloatMajorUnit,
pub currency: String,
pub checkout_methods: Option<CheckoutMethod>,
pub failure_code: Option<String>,
pub failure_details: Option<String>,
}
fn get_iatpay_response(
response: IatapayPaymentsResponse,
status_code: u16,
) -> CustomResult<
(
enums::AttemptStatus,
Option<ErrorResponse>,
PaymentsResponseData,
),
errors::ConnectorError,
> {
let status = enums::AttemptStatus::from(response.status);
let error = if is_payment_failure(status) {
Some(ErrorResponse {
code: response
.failure_code
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: response
.failure_details
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: response.failure_details,
status_code,
attempt_status: Some(status),
connector_transaction_id: response.iata_payment_id.clone(),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
let form_fields = HashMap::new();
let id = match response.iata_payment_id.clone() {
Some(s) => ResponseId::ConnectorTransactionId(s),
None => ResponseId::NoResponseId,
};
let connector_response_reference_id = response.merchant_payment_id.or(response.iata_payment_id);
let payment_response_data = match response.checkout_methods {
Some(checkout_methods) => {
let (connector_metadata, redirection_data) =
match checkout_methods.redirect.redirect_url.ends_with("qr") {
true => {
let qr_code_info = api_models::payments::FetchQrCodeInformation {
qr_code_fetch_url: url::Url::parse(
&checkout_methods.redirect.redirect_url,
)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?,
};
(
Some(qr_code_info.encode_to_value())
.transpose()
.change_context(errors::ConnectorError::ResponseHandlingFailed)?,
None,
)
}
false => (
None,
Some(RedirectForm::Form {
endpoint: checkout_methods.redirect.redirect_url,
method: Method::Get,
form_fields,
}),
),
};
PaymentsResponseData::TransactionResponse {
resource_id: id,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: connector_response_reference_id.clone(),
incremental_authorization_allowed: None,
charges: None,
}
}
None => PaymentsResponseData::TransactionResponse {
resource_id: id.clone(),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: connector_response_reference_id.clone(),
incremental_authorization_allowed: None,
charges: None,
},
};
Ok((status, error, payment_response_data))
}
impl<F, T> TryFrom<ResponseRouterData<F, IatapayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, IatapayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, error, payment_response_data) =
get_iatpay_response(item.response, item.http_code)?;
Ok(Self {
status,
response: error.map_or_else(|| Ok(payment_response_data), Err),
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IatapayRefundRequest {
pub merchant_id: Secret<String>,
pub merchant_refund_id: Option<String>,
pub amount: FloatMajorUnit,
pub currency: String,
pub bank_transfer_description: Option<String>,
pub notification_url: String,
}
impl<F> TryFrom<&IatapayRouterData<&RefundsRouterData<F>>> for IatapayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &IatapayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
merchant_id: IatapayAuthType::try_from(&item.router_data.connector_auth_type)?
.merchant_id,
merchant_refund_id: Some(item.router_data.request.refund_id.clone()),
currency: item.router_data.request.currency.to_string(),
bank_transfer_description: item.router_data.request.reason.clone(),
notification_url: item.router_data.request.get_webhook_url()?,
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
#[default]
Created,
Locked,
Initiated,
Authorized,
Settled,
Cleared,
Failed,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Created => Self::Pending,
RefundStatus::Failed => Self::Failure,
RefundStatus::Locked => Self::Pending,
RefundStatus::Initiated => Self::Pending,
RefundStatus::Authorized => Self::Pending,
RefundStatus::Settled => Self::Success,
RefundStatus::Cleared => Self::Success,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
iata_refund_id: String,
status: RefundStatus,
merchant_refund_id: String,
amount: FloatMajorUnit,
currency: String,
bank_transfer_description: Option<String>,
failure_code: Option<String>,
failure_details: Option<String>,
lock_reason: Option<String>,
creation_date_time: Option<String>,
finish_date_time: Option<String>,
update_date_time: Option<String>,
clearance_date_time: Option<String>,
iata_payment_id: Option<String>,
merchant_payment_id: Option<String>,
payment_amount: Option<FloatMajorUnit>,
merchant_id: Option<Secret<String>>,
account_country: Option<String>,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
let response = if is_refund_failure(refund_status) {
Err(ErrorResponse {
code: item
.response
.failure_code
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: item
.response
.failure_details
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: item.response.failure_details,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.iata_refund_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.iata_refund_id.to_string(),
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
let response = if is_refund_failure(refund_status) {
Err(ErrorResponse {
code: item
.response
.failure_code
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: item
.response
.failure_details
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: item.response.failure_details,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.iata_refund_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.iata_refund_id.to_string(),
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct IatapayErrorResponse {
pub status: Option<u16>,
pub error: String,
pub message: Option<String>,
pub reason: Option<String>,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct IatapayAccessTokenErrorResponse {
pub error: String,
pub path: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IatapayPaymentWebhookBody {
pub status: IatapayWebhookStatus,
pub iata_payment_id: String,
pub merchant_payment_id: Option<String>,
pub failure_code: Option<String>,
pub failure_details: Option<String>,
pub amount: FloatMajorUnit,
pub currency: String,
pub checkout_methods: Option<CheckoutMethod>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IatapayRefundWebhookBody {
pub status: IatapayRefundWebhookStatus,
pub iata_refund_id: String,
pub merchant_refund_id: Option<String>,
pub failure_code: Option<String>,
pub failure_details: Option<String>,
pub amount: FloatMajorUnit,
pub currency: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum IatapayWebhookResponse {
IatapayPaymentWebhookBody(IatapayPaymentWebhookBody),
IatapayRefundWebhookBody(IatapayRefundWebhookBody),
}
impl TryFrom<IatapayWebhookResponse> for IncomingWebhookEvent {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(payload: IatapayWebhookResponse) -> CustomResult<Self, errors::ConnectorError> {
match payload {
IatapayWebhookResponse::IatapayPaymentWebhookBody(wh_body) => match wh_body.status {
IatapayWebhookStatus::Authorized | IatapayWebhookStatus::Settled => {
Ok(Self::PaymentIntentSuccess)
}
IatapayWebhookStatus::Initiated => Ok(Self::PaymentIntentProcessing),
IatapayWebhookStatus::Failed => Ok(Self::PaymentIntentFailure),
IatapayWebhookStatus::Created
| IatapayWebhookStatus::Cleared
| IatapayWebhookStatus::Tobeinvestigated
| IatapayWebhookStatus::Blocked
| IatapayWebhookStatus::UnexpectedSettled
| IatapayWebhookStatus::Unknown => Ok(Self::EventNotSupported),
},
IatapayWebhookResponse::IatapayRefundWebhookBody(wh_body) => match wh_body.status {
IatapayRefundWebhookStatus::Cleared
| IatapayRefundWebhookStatus::Authorized
| IatapayRefundWebhookStatus::Settled => Ok(Self::RefundSuccess),
IatapayRefundWebhookStatus::Failed => Ok(Self::RefundFailure),
IatapayRefundWebhookStatus::Created
| IatapayRefundWebhookStatus::Locked
| IatapayRefundWebhookStatus::Initiated
| IatapayRefundWebhookStatus::Unknown => Ok(Self::EventNotSupported),
},
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum IatapayWebhookStatus {
Created,
Initiated,
Authorized,
Settled,
Cleared,
Failed,
Tobeinvestigated,
Blocked,
#[serde(rename = "UNEXPECTED SETTLED")]
UnexpectedSettled,
#[serde(other)]
Unknown,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum IatapayRefundWebhookStatus {
Created,
Initiated,
Authorized,
Settled,
Failed,
Cleared,
Locked,
#[serde(other)]
Unknown,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5416
}
|
large_file_1439296304490686994
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/square/transformers.rs
</path>
<file>
use api_models::webhooks::IncomingWebhookEvent;
use common_enums::enums;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankDebitData, Card, PayLaterData, PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
router_flow_types::{refunds::Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData as _},
};
impl TryFrom<(&types::TokenizationRouterData, BankDebitData)> for SquareTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (&types::TokenizationRouterData, BankDebitData),
) -> Result<Self, Self::Error> {
let (_item, bank_debit_data) = value;
match bank_debit_data {
BankDebitData::AchBankDebit { .. }
| BankDebitData::SepaBankDebit { .. }
| BankDebitData::BecsBankDebit { .. }
| BankDebitData::BacsBankDebit { .. }
| BankDebitData::SepaGuarenteedBankDebit { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Square"),
))?
}
}
}
}
impl TryFrom<(&types::TokenizationRouterData, Card)> for SquareTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: (&types::TokenizationRouterData, Card)) -> Result<Self, Self::Error> {
let (item, card_data) = value;
let auth = SquareAuthType::try_from(&item.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let exp_year = Secret::new(
card_data
.get_expiry_year_4_digit()
.peek()
.parse::<u16>()
.change_context(errors::ConnectorError::DateFormattingFailed)?,
);
let exp_month = Secret::new(
card_data
.card_exp_month
.peek()
.parse::<u16>()
.change_context(errors::ConnectorError::DateFormattingFailed)?,
);
//The below error will never happen because if session-id is not generated it would give error in execute_pretasks itself.
let session_id = Secret::new(
item.session_token
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?,
);
Ok(Self::Card(SquareTokenizeData {
client_id: auth.key1,
session_id,
card_data: SquareCardData {
exp_year,
exp_month,
number: card_data.card_number,
cvv: card_data.card_cvc,
},
}))
}
}
impl TryFrom<(&types::TokenizationRouterData, PayLaterData)> for SquareTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (&types::TokenizationRouterData, PayLaterData),
) -> Result<Self, Self::Error> {
let (_item, pay_later_data) = value;
match pay_later_data {
PayLaterData::AfterpayClearpayRedirect { .. }
| PayLaterData::KlarnaRedirect { .. }
| PayLaterData::KlarnaSdk { .. }
| PayLaterData::AffirmRedirect { .. }
| PayLaterData::PayBrightRedirect { .. }
| PayLaterData::WalleyRedirect { .. }
| PayLaterData::AlmaRedirect { .. }
| PayLaterData::FlexitiRedirect { .. }
| PayLaterData::AtomeRedirect { .. }
| PayLaterData::BreadpayRedirect { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Square"),
))?
}
}
}
}
impl TryFrom<(&types::TokenizationRouterData, WalletData)> for SquareTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: (&types::TokenizationRouterData, WalletData)) -> Result<Self, Self::Error> {
let (_item, wallet_data) = value;
match wallet_data {
WalletData::AmazonPay(_)
| WalletData::ApplePay(_)
| WalletData::GooglePay(_)
| WalletData::BluecodeRedirect {}
| WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Square"),
))?,
}
}
}
#[derive(Debug, Serialize)]
pub struct SquareCardData {
cvv: Secret<String>,
exp_month: Secret<u16>,
exp_year: Secret<u16>,
number: cards::CardNumber,
}
#[derive(Debug, Serialize)]
pub struct SquareTokenizeData {
client_id: Secret<String>,
session_id: Secret<String>,
card_data: SquareCardData,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum SquareTokenRequest {
Card(SquareTokenizeData),
}
impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::BankDebit(bank_debit_data) => {
Self::try_from((item, bank_debit_data))
}
PaymentMethodData::Card(card_data) => Self::try_from((item, card_data)),
PaymentMethodData::Wallet(wallet_data) => Self::try_from((item, wallet_data)),
PaymentMethodData::PayLater(pay_later_data) => Self::try_from((item, pay_later_data)),
PaymentMethodData::GiftCard(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Square"),
))?
}
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SquareSessionResponse {
session_id: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, SquareSessionResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SquareSessionResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::Pending,
session_token: Some(item.response.session_id.clone().expose()),
response: Ok(PaymentsResponseData::SessionTokenResponse {
session_token: item.response.session_id.expose(),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct SquareTokenResponse {
card_nonce: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, SquareTokenResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SquareTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.card_nonce.expose(),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct SquarePaymentsAmountData {
amount: i64,
currency: enums::Currency,
}
#[derive(Debug, Serialize)]
pub struct SquarePaymentsRequestExternalDetails {
source: String,
#[serde(rename = "type")]
source_type: String,
}
#[derive(Debug, Serialize)]
pub struct SquarePaymentsRequest {
amount_money: SquarePaymentsAmountData,
idempotency_key: Secret<String>,
source_id: Secret<String>,
autocomplete: bool,
external_details: SquarePaymentsRequestExternalDetails,
}
impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let autocomplete = item.request.is_auto_capture()?;
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(_) => {
let pm_token = item.get_payment_method_token()?;
Ok(Self {
idempotency_key: Secret::new(item.attempt_id.clone()),
source_id: match pm_token {
PaymentMethodToken::Token(token) => token,
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Square"),
)?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Square"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Square"))?
}
},
amount_money: SquarePaymentsAmountData {
amount: item.request.amount,
currency: item.request.currency,
},
autocomplete,
external_details: SquarePaymentsRequestExternalDetails {
source: "Hyperswitch".to_string(),
source_type: "Card".to_string(),
},
})
}
PaymentMethodData::BankDebit(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Square"),
))?
}
}
}
}
// Auth Struct
pub struct SquareAuthType {
pub(super) api_key: Secret<String>,
pub(super) key1: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for SquareAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1, .. } => Ok(Self {
api_key: api_key.to_owned(),
key1: key1.to_owned(),
}),
ConnectorAuthType::HeaderKey { .. }
| ConnectorAuthType::SignatureKey { .. }
| ConnectorAuthType::MultiAuthKey { .. }
| ConnectorAuthType::CurrencyAuthKey { .. }
| ConnectorAuthType::TemporaryAuth
| ConnectorAuthType::NoKey
| ConnectorAuthType::CertificateAuth { .. } => {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
}
// PaymentsResponse
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum SquarePaymentStatus {
Completed,
Failed,
Approved,
Canceled,
Pending,
}
impl From<SquarePaymentStatus> for enums::AttemptStatus {
fn from(item: SquarePaymentStatus) -> Self {
match item {
SquarePaymentStatus::Completed => Self::Charged,
SquarePaymentStatus::Approved => Self::Authorized,
SquarePaymentStatus::Failed => Self::Failure,
SquarePaymentStatus::Canceled => Self::Voided,
SquarePaymentStatus::Pending => Self::Pending,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct SquarePaymentsResponseDetails {
status: SquarePaymentStatus,
id: String,
amount_money: SquarePaymentsAmountData,
reference_id: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct SquarePaymentsResponse {
payment: SquarePaymentsResponseDetails,
}
impl<F, T> TryFrom<ResponseRouterData<F, SquarePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SquarePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
//Since this try_from is being used in Authorize, Sync, Capture & Void flow. Field amount_captured should only be updated in case of Charged status.
let status = enums::AttemptStatus::from(item.response.payment.status);
let mut amount_captured = None;
if status == enums::AttemptStatus::Charged {
amount_captured = Some(item.response.payment.amount_money.amount)
};
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.payment.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.payment.reference_id,
incremental_authorization_allowed: None,
charges: None,
}),
amount_captured,
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
pub struct SquareRefundRequest {
amount_money: SquarePaymentsAmountData,
idempotency_key: Secret<String>,
payment_id: Secret<String>,
}
impl<F> TryFrom<&types::RefundsRouterData<F>> for SquareRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
Ok(Self {
amount_money: SquarePaymentsAmountData {
amount: item.request.refund_amount,
currency: item.request.currency,
},
idempotency_key: Secret::new(item.request.refund_id.clone()),
payment_id: Secret::new(item.request.connector_transaction_id.clone()),
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Completed,
Failed,
Pending,
Rejected,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Completed => Self::Success,
RefundStatus::Failed | RefundStatus::Rejected => Self::Failure,
RefundStatus::Pending => Self::Pending,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct SquareRefundResponseDetails {
status: RefundStatus,
id: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RefundResponse {
refund: SquareRefundResponseDetails,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund.id,
refund_status: enums::RefundStatus::from(item.response.refund.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund.id,
refund_status: enums::RefundStatus::from(item.response.refund.status),
}),
..item.data
})
}
}
#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct SquareErrorDetails {
pub category: Option<String>,
pub code: Option<String>,
pub detail: Option<String>,
}
#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct SquareErrorResponse {
pub errors: Vec<SquareErrorDetails>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SquareWebhookObject {
Payment(SquarePaymentsResponseDetails),
Refund(SquareRefundResponseDetails),
}
#[derive(Debug, Deserialize)]
pub struct SquareWebhookData {
pub id: String,
pub object: SquareWebhookObject,
}
#[derive(Debug, Deserialize)]
pub struct SquareWebhookBody {
#[serde(rename = "type")]
pub webhook_type: String,
pub data: SquareWebhookData,
}
impl From<SquareWebhookObject> for IncomingWebhookEvent {
fn from(item: SquareWebhookObject) -> Self {
match item {
SquareWebhookObject::Payment(payment_data) => match payment_data.status {
SquarePaymentStatus::Completed => Self::PaymentIntentSuccess,
SquarePaymentStatus::Failed => Self::PaymentIntentFailure,
SquarePaymentStatus::Pending => Self::PaymentIntentProcessing,
SquarePaymentStatus::Approved | SquarePaymentStatus::Canceled => {
Self::EventNotSupported
}
},
SquareWebhookObject::Refund(refund_data) => match refund_data.status {
RefundStatus::Completed => Self::RefundSuccess,
RefundStatus::Failed | RefundStatus::Rejected => Self::RefundFailure,
RefundStatus::Pending => Self::EventNotSupported,
},
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/square/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4457
}
|
large_file_-8217376662142601283
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/payone/transformers.rs
</path>
<file>
#[cfg(feature = "payouts")]
use api_models::payouts::PayoutMethodData;
#[cfg(feature = "payouts")]
use cards::CardNumber;
#[cfg(feature = "payouts")]
use common_enums::{PayoutStatus, PayoutType};
use common_utils::types::MinorUnit;
#[cfg(feature = "payouts")]
use common_utils::{ext_traits::OptionExt, transformers::ForeignFrom};
#[cfg(feature = "payouts")]
use error_stack::ResultExt;
use hyperswitch_domain_models::router_data::ConnectorAuthType;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::PoFulfill,
types::{PayoutsResponseData, PayoutsRouterData},
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::Secret;
use serde::{Deserialize, Serialize};
#[cfg(feature = "payouts")]
use crate::utils::CardData as _;
use crate::utils::{
get_unimplemented_payment_method_error_message, CardIssuer, ErrorCodeAndMessage,
};
#[cfg(feature = "payouts")]
use crate::{
types::PayoutsResponseRouterData,
utils::{PayoutsData, RouterData},
};
#[cfg(feature = "payouts")]
type Error = error_stack::Report<ConnectorError>;
use serde_repr::{Deserialize_repr, Serialize_repr};
pub struct PayoneRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for PayoneRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ErrorResponse {
pub errors: Option<Vec<SubError>>,
pub error_id: Option<i32>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct SubError {
pub code: String,
pub message: String,
pub http_status_code: u16,
}
impl From<SubError> for ErrorCodeAndMessage {
fn from(error: SubError) -> Self {
Self {
error_code: error.code.to_string(),
error_message: error.code.to_string(),
}
}
}
// Auth Struct
pub struct PayoneAuthType {
pub(super) api_key: Secret<String>,
pub merchant_account: Secret<String>,
pub api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PayoneAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
api_key: api_key.to_owned(),
merchant_account: key1.to_owned(),
api_secret: api_secret.to_owned(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType)?,
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayonePayoutFulfillRequest {
amount_of_money: AmountOfMoney,
card_payout_method_specific_input: CardPayoutMethodSpecificInput,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AmountOfMoney {
amount: MinorUnit,
currency_code: String,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardPayoutMethodSpecificInput {
card: Card,
payment_product_id: PaymentProductId,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
card_holder_name: Secret<String>,
card_number: CardNumber,
expiry_date: Secret<String>,
}
#[cfg(feature = "payouts")]
impl TryFrom<PayoneRouterData<&PayoutsRouterData<PoFulfill>>> for PayonePayoutFulfillRequest {
type Error = Error;
fn try_from(
item: PayoneRouterData<&PayoutsRouterData<PoFulfill>>,
) -> Result<Self, Self::Error> {
let request = item.router_data.request.to_owned();
let payout_type = request.get_payout_type()?;
match payout_type {
PayoutType::Card => {
let amount_of_money: AmountOfMoney = AmountOfMoney {
amount: item.amount,
currency_code: item.router_data.request.destination_currency.to_string(),
};
let card_payout_method_specific_input = match item
.router_data
.get_payout_method_data()?
{
PayoutMethodData::Card(card_data) => CardPayoutMethodSpecificInput {
card: Card {
card_number: card_data.card_number.clone(),
card_holder_name: card_data
.card_holder_name
.clone()
.get_required_value("card_holder_name")
.change_context(ConnectorError::MissingRequiredField {
field_name: "payout_method_data.card.holder_name",
})?,
expiry_date: card_data
.get_card_expiry_month_year_2_digit_with_delimiter(
"".to_string(),
)?,
},
payment_product_id: PaymentProductId::try_from(
card_data.get_card_issuer()?,
)?,
},
PayoutMethodData::Bank(_)
| PayoutMethodData::Wallet(_)
| PayoutMethodData::BankRedirect(_) => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Payone"),
))?,
};
Ok(Self {
amount_of_money,
card_payout_method_specific_input,
})
}
PayoutType::Wallet | PayoutType::Bank | PayoutType::BankRedirect => {
Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Payone"),
))?
}
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize_repr, Deserialize_repr)]
#[repr(i32)]
pub enum PaymentProductId {
Visa = 1,
MasterCard = 3,
}
impl TryFrom<CardIssuer> for PaymentProductId {
type Error = error_stack::Report<ConnectorError>;
fn try_from(issuer: CardIssuer) -> Result<Self, Self::Error> {
match issuer {
CardIssuer::Master => Ok(Self::MasterCard),
CardIssuer::Visa => Ok(Self::Visa),
CardIssuer::AmericanExpress
| CardIssuer::Maestro
| CardIssuer::Discover
| CardIssuer::DinersClub
| CardIssuer::JCB
| CardIssuer::CarteBlanche
| CardIssuer::UnionPay
| CardIssuer::CartesBancaires => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("payone"),
)
.into()),
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Default, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayoneStatus {
Created,
#[default]
PendingApproval,
Rejected,
PayoutRequested,
AccountCredited,
RejectedCredit,
Cancelled,
Reversed,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayonePayoutFulfillResponse {
id: String,
payout_output: PayoutOutput,
status: PayoneStatus,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayoutOutput {
amount_of_money: AmountOfMoney,
}
#[cfg(feature = "payouts")]
impl ForeignFrom<PayoneStatus> for PayoutStatus {
fn foreign_from(payone_status: PayoneStatus) -> Self {
match payone_status {
PayoneStatus::AccountCredited => Self::Success,
PayoneStatus::RejectedCredit | PayoneStatus::Rejected => Self::Failed,
PayoneStatus::Cancelled | PayoneStatus::Reversed => Self::Cancelled,
PayoneStatus::Created
| PayoneStatus::PendingApproval
| PayoneStatus::PayoutRequested => Self::Pending,
}
}
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, PayonePayoutFulfillResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, PayonePayoutFulfillResponse>,
) -> Result<Self, Self::Error> {
let response: PayonePayoutFulfillResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::foreign_from(response.status)),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/payone/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2004
}
|
large_file_1926100377678128725
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/gpayments/transformers.rs
</path>
<file>
use api_models::payments::DeviceChannel;
use base64::Engine;
use common_utils::{consts::BASE64_ENGINE, date_time, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, ErrorResponse},
router_flow_types::authentication::{
Authentication, PreAuthentication, PreAuthenticationVersionCall,
},
router_request_types::{
authentication::{
AuthNFlowType, ChallengeParams, ConnectorAuthenticationRequestData, MessageCategory,
PreAuthNRequestData,
},
BrowserInformation,
},
router_response_types::AuthenticationResponseData,
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::{ExposeInterface, Secret};
use serde::Deserialize;
use serde_json::to_string;
use super::gpayments_types::{
self, AuthStatus, BrowserInfoCollected, GpaymentsAuthenticationSuccessResponse,
GpaymentsPreAuthVersionCallResponse,
};
use crate::{
types::{
ConnectorAuthenticationRouterData, PreAuthNRouterData, PreAuthNVersionCallRouterData,
ResponseRouterData,
},
utils::{get_card_details, to_connector_meta_from_secret, CardData as _},
};
pub struct GpaymentsRouterData<T> {
pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for GpaymentsRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
// Auth Struct
pub struct GpaymentsAuthType {
/// base64 encoded certificate
pub certificate: Secret<String>,
/// base64 encoded private_key
pub private_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for GpaymentsAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type.to_owned() {
ConnectorAuthType::CertificateAuth {
certificate,
private_key,
} => Ok(Self {
certificate,
private_key,
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<&GpaymentsRouterData<&PreAuthNVersionCallRouterData>>
for gpayments_types::GpaymentsPreAuthVersionCallRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
value: &GpaymentsRouterData<&PreAuthNVersionCallRouterData>,
) -> Result<Self, Self::Error> {
let router_data = value.router_data;
let metadata = GpaymentsMetaData::try_from(&router_data.connector_meta_data)?;
Ok(Self {
acct_number: router_data.request.card.card_number.clone(),
merchant_id: metadata.merchant_id,
})
}
}
#[derive(Deserialize, PartialEq)]
pub struct GpaymentsMetaData {
pub endpoint_prefix: String,
pub merchant_id: common_utils::id_type::MerchantId,
}
impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for GpaymentsMetaData {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
meta_data: &Option<common_utils::pii::SecretSerdeValue>,
) -> Result<Self, Self::Error> {
let metadata: Self = to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(ConnectorError::InvalidConnectorConfig { config: "metadata" })?;
Ok(metadata)
}
}
impl
TryFrom<
ResponseRouterData<
PreAuthenticationVersionCall,
GpaymentsPreAuthVersionCallResponse,
PreAuthNRequestData,
AuthenticationResponseData,
>,
> for PreAuthNVersionCallRouterData
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
PreAuthenticationVersionCall,
GpaymentsPreAuthVersionCallResponse,
PreAuthNRequestData,
AuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
let version_response = item.response;
let response = Ok(AuthenticationResponseData::PreAuthVersionCallResponse {
maximum_supported_3ds_version: version_response
.supported_message_versions
.and_then(|supported_version| supported_version.iter().max().cloned()) // if no version is returned for the card number, then
.unwrap_or(common_utils::types::SemanticVersion::new(0, 0, 0)),
});
Ok(Self {
response,
..item.data.clone()
})
}
}
impl TryFrom<&GpaymentsRouterData<&PreAuthNRouterData>>
for gpayments_types::GpaymentsPreAuthenticationRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(value: &GpaymentsRouterData<&PreAuthNRouterData>) -> Result<Self, Self::Error> {
let router_data = value.router_data;
let metadata = GpaymentsMetaData::try_from(&router_data.connector_meta_data)?;
Ok(Self {
acct_number: router_data.request.card.card_number.clone(),
card_scheme: None,
challenge_window_size: Some(gpayments_types::ChallengeWindowSize::FullScreen),
event_callback_url: "https://webhook.site/55e3db24-7c4e-4432-9941-d806f68d210b"
.to_string(),
merchant_id: metadata.merchant_id,
skip_auto_browser_info_collect: Some(true),
// should auto generate this id.
three_ds_requestor_trans_id: uuid::Uuid::new_v4().hyphenated().to_string(),
})
}
}
impl TryFrom<&GpaymentsRouterData<&ConnectorAuthenticationRouterData>>
for gpayments_types::GpaymentsAuthenticationRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &GpaymentsRouterData<&ConnectorAuthenticationRouterData>,
) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
let browser_details = match request.browser_details.clone() {
Some(details) => Ok::<Option<BrowserInformation>, Self::Error>(Some(details)),
None => {
if request.device_channel == DeviceChannel::Browser {
Err(ConnectorError::MissingRequiredField {
field_name: "browser_info",
})?
} else {
Ok(None)
}
}
}?;
let card_details = get_card_details(request.payment_method_data.clone(), "gpayments")?;
let metadata = GpaymentsMetaData::try_from(&item.router_data.connector_meta_data)?;
Ok(Self {
acct_number: card_details.card_number.clone(),
authentication_ind: "01".into(),
card_expiry_date: card_details.get_expiry_date_as_yymm()?.expose(),
merchant_id: metadata.merchant_id,
message_category: match item.router_data.request.message_category.clone() {
MessageCategory::Payment => "01".into(),
MessageCategory::NonPayment => "02".into(),
},
notification_url: request
.return_url
.clone()
.ok_or(ConnectorError::RequestEncodingFailed)
.attach_printable("missing return_url")?,
three_ds_comp_ind: request.threeds_method_comp_ind.clone(),
purchase_amount: item.amount.to_string(),
purchase_date: date_time::DateTime::<date_time::YYYYMMDDHHmmss>::from(date_time::now())
.to_string(),
three_ds_server_trans_id: request
.pre_authentication_data
.threeds_server_transaction_id
.clone(),
browser_info_collected: BrowserInfoCollected {
browser_javascript_enabled: browser_details
.as_ref()
.and_then(|details| details.java_script_enabled),
browser_accept_header: browser_details
.as_ref()
.and_then(|details| details.accept_header.clone()),
browser_ip: browser_details
.clone()
.and_then(|details| details.ip_address.map(|ip| Secret::new(ip.to_string()))),
browser_java_enabled: browser_details
.as_ref()
.and_then(|details| details.java_enabled),
browser_language: browser_details
.as_ref()
.and_then(|details| details.language.clone()),
browser_color_depth: browser_details
.as_ref()
.and_then(|details| details.color_depth.map(|a| a.to_string())),
browser_screen_height: browser_details
.as_ref()
.and_then(|details| details.screen_height.map(|a| a.to_string())),
browser_screen_width: browser_details
.as_ref()
.and_then(|details| details.screen_width.map(|a| a.to_string())),
browser_tz: browser_details
.as_ref()
.and_then(|details| details.time_zone.map(|a| a.to_string())),
browser_user_agent: browser_details
.as_ref()
.and_then(|details| details.user_agent.clone().map(|a| a.to_string())),
},
})
}
}
impl
TryFrom<
ResponseRouterData<
Authentication,
GpaymentsAuthenticationSuccessResponse,
ConnectorAuthenticationRequestData,
AuthenticationResponseData,
>,
> for ConnectorAuthenticationRouterData
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
Authentication,
GpaymentsAuthenticationSuccessResponse,
ConnectorAuthenticationRequestData,
AuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
let response_auth = item.response;
let creq = serde_json::json!({
"threeDSServerTransID": response_auth.three_ds_server_trans_id,
"acsTransID": response_auth.acs_trans_id,
"messageVersion": response_auth.message_version,
"messageType": "CReq",
"challengeWindowSize": "01",
});
let creq_str = to_string(&creq)
.change_context(ConnectorError::ResponseDeserializationFailed)
.attach_printable("error while constructing creq_str")?;
let creq_base64 = Engine::encode(&BASE64_ENGINE, creq_str)
.trim_end_matches('=')
.to_owned();
let response: Result<AuthenticationResponseData, ErrorResponse> =
Ok(AuthenticationResponseData::AuthNResponse {
trans_status: response_auth.trans_status.clone().into(),
authn_flow_type: if response_auth.trans_status == AuthStatus::C {
AuthNFlowType::Challenge(Box::new(ChallengeParams {
acs_url: response_auth.acs_url,
challenge_request: Some(creq_base64),
acs_reference_number: Some(response_auth.acs_reference_number.clone()),
acs_trans_id: Some(response_auth.acs_trans_id.clone()),
three_dsserver_trans_id: Some(response_auth.three_ds_server_trans_id),
acs_signed_content: None,
challenge_request_key: None,
}))
} else {
AuthNFlowType::Frictionless
},
authentication_value: response_auth.authentication_value,
ds_trans_id: Some(response_auth.ds_trans_id),
connector_metadata: None,
eci: None,
challenge_code: None,
challenge_cancel: None,
challenge_code_reason: None,
message_extension: None,
});
Ok(Self {
response,
..item.data.clone()
})
}
}
impl
TryFrom<
ResponseRouterData<
PreAuthentication,
gpayments_types::GpaymentsPreAuthenticationResponse,
PreAuthNRequestData,
AuthenticationResponseData,
>,
> for PreAuthNRouterData
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
PreAuthentication,
gpayments_types::GpaymentsPreAuthenticationResponse,
PreAuthNRequestData,
AuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
let threeds_method_response = item.response;
let three_ds_method_data = threeds_method_response
.three_ds_method_url
.as_ref()
.map(|_| {
let three_ds_method_data_json = serde_json::json!({
"threeDSServerTransID": threeds_method_response.three_ds_server_trans_id,
"threeDSMethodNotificationURL": "https://webhook.site/bd06863d-82c2-42ea-b35b-5ffd5ecece71"
});
to_string(&three_ds_method_data_json)
.change_context(ConnectorError::ResponseDeserializationFailed)
.attach_printable("error while constructing three_ds_method_data_str")
.map(|three_ds_method_data_string| {
Engine::encode(&BASE64_ENGINE, three_ds_method_data_string)
})
})
.transpose()?;
let connector_metadata = Some(serde_json::json!(
gpayments_types::GpaymentsConnectorMetaData {
authentication_url: threeds_method_response.auth_url,
three_ds_requestor_trans_id: None,
}
));
let response: Result<AuthenticationResponseData, ErrorResponse> = Ok(
AuthenticationResponseData::PreAuthThreeDsMethodCallResponse {
threeds_server_transaction_id: threeds_method_response
.three_ds_server_trans_id
.clone(),
three_ds_method_data,
three_ds_method_url: threeds_method_response.three_ds_method_url,
connector_metadata,
},
);
Ok(Self {
response,
..item.data.clone()
})
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/gpayments/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2922
}
|
large_file_-6257035486801414655
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs
</path>
<file>
use bytes::Bytes;
use common_enums::{
self, AttemptStatus, AuthorizationStatus, CaptureMethod, Currency, FutureUsage,
PaymentMethodStatus, RefundStatus,
};
use common_utils::{date_time, ext_traits::Encode, pii, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
address::AddressDetails,
payment_method_data::{Card, PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{
AuthenticationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
PaymentsIncrementalAuthorizationData, PaymentsSyncData, ResponseId,
SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsIncrementalAuthorizationRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
utils::{
self, AddressData, AddressDetailsData, CardData, CardIssuer, PaymentsAuthorizeRequestData,
RouterData as _,
},
};
const THREE_DS_MAX_SUPPORTED_VERSION: &str = "2.2.0";
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(transparent)]
pub struct ArchipelTenantId(pub String);
impl From<String> for ArchipelTenantId {
fn from(value: String) -> Self {
Self(value)
}
}
pub struct ArchipelRouterData<T> {
pub amount: MinorUnit,
pub tenant_id: ArchipelTenantId,
pub router_data: T,
}
impl<T> From<(MinorUnit, ArchipelTenantId, T)> for ArchipelRouterData<T> {
fn from((amount, tenant_id, router_data): (MinorUnit, ArchipelTenantId, T)) -> Self {
Self {
amount,
tenant_id,
router_data,
}
}
}
pub struct ArchipelAuthType {
pub(super) ca_certificate: Option<Secret<String>>,
}
impl TryFrom<&ConnectorAuthType> for ArchipelAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
ca_certificate: Some(api_key.to_owned()),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct ArchipelConfigData {
pub tenant_id: ArchipelTenantId,
pub platform_url: String,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for ArchipelConfigData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(connector_metadata: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let config_data = utils::to_connector_meta_from_secret::<Self>(connector_metadata.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata. Required fields: tenant_id, platform_url",
})?;
Ok(config_data)
}
}
#[derive(Debug, Default, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum ArchipelPaymentInitiator {
#[default]
Customer,
Merchant,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ArchipelWalletProvider {
ApplePay,
GooglePay,
SamsungPay,
}
#[derive(Debug, Default, Serialize, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum ArchipelPaymentCertainty {
#[default]
Final,
Estimated,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelOrderRequest {
amount: MinorUnit,
currency: String,
certainty: ArchipelPaymentCertainty,
initiator: ArchipelPaymentInitiator,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
pub struct CardExpiryDate {
month: Secret<String>,
year: Secret<String>,
}
#[derive(Debug, Serialize, Default, Eq, PartialEq, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ApplicationSelectionIndicator {
#[default]
ByDefault,
CustomerChoice,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Archipel3DS {
#[serde(rename = "acsTransID")]
acs_trans_id: Option<Secret<String>>,
#[serde(rename = "dsTransID")]
ds_trans_id: Option<Secret<String>>,
#[serde(rename = "3DSRequestorName")]
three_ds_requestor_name: Option<Secret<String>>,
#[serde(rename = "3DSAuthDate")]
three_ds_auth_date: Option<String>,
#[serde(rename = "3DSAuthAmt")]
three_ds_auth_amt: Option<MinorUnit>,
#[serde(rename = "3DSAuthStatus")]
three_ds_auth_status: Option<String>,
#[serde(rename = "3DSMaxSupportedVersion")]
three_ds_max_supported_version: String,
#[serde(rename = "3DSVersion")]
three_ds_version: Option<common_utils::types::SemanticVersion>,
authentication_value: Secret<String>,
authentication_method: Option<Secret<String>>,
eci: Option<String>,
}
impl From<AuthenticationData> for Archipel3DS {
fn from(three_ds_data: AuthenticationData) -> Self {
let now = date_time::date_as_yyyymmddthhmmssmmmz().ok();
Self {
acs_trans_id: None,
ds_trans_id: three_ds_data.ds_trans_id.map(Secret::new),
three_ds_requestor_name: None,
three_ds_auth_date: now,
three_ds_auth_amt: None,
three_ds_auth_status: None,
three_ds_max_supported_version: THREE_DS_MAX_SUPPORTED_VERSION.into(),
three_ds_version: three_ds_data.message_version,
authentication_value: three_ds_data.cavv,
authentication_method: None,
eci: three_ds_data.eci,
}
}
}
#[derive(Clone, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelCardHolder {
billing_address: Option<ArchipelBillingAddress>,
}
impl From<Option<ArchipelBillingAddress>> for ArchipelCardHolder {
fn from(value: Option<ArchipelBillingAddress>) -> Self {
Self {
billing_address: value,
}
}
}
#[derive(Clone, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelBillingAddress {
address: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
}
pub trait ToArchipelBillingAddress {
fn to_archipel_billing_address(&self) -> Option<ArchipelBillingAddress>;
}
impl ToArchipelBillingAddress for AddressDetails {
fn to_archipel_billing_address(&self) -> Option<ArchipelBillingAddress> {
let address = self.get_combined_address_line().ok();
let postal_code = self.get_optional_zip();
match (address, postal_code) {
(None, None) => None,
(addr, zip) => Some(ArchipelBillingAddress {
address: addr,
postal_code: zip,
}),
}
}
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum ArchipelCredentialIndicatorStatus {
Initial,
Subsequent,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelCredentialIndicator {
status: ArchipelCredentialIndicatorStatus,
recurring: Option<bool>,
transaction_id: Option<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCardData {
card_data: ArchipelTokenizedCard,
wallet_information: ArchipelWalletInformation,
}
impl TryFrom<(&WalletData, &Option<PaymentMethodToken>)> for TokenizedCardData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(wallet_data, pm_token): (&WalletData, &Option<PaymentMethodToken>),
) -> Result<Self, Self::Error> {
let WalletData::ApplePay(apple_pay_data) = wallet_data else {
return Err(error_stack::Report::from(
errors::ConnectorError::NotSupported {
message: "Wallet type used".to_string(),
connector: "Archipel",
},
));
};
let Some(PaymentMethodToken::ApplePayDecrypt(apple_pay_decrypt_data)) = pm_token else {
return Err(error_stack::Report::from(unimplemented_payment_method!(
"Apple Pay",
"Manual",
"Archipel"
)));
};
let card_number = apple_pay_decrypt_data
.application_primary_account_number
.clone();
let expiry_year_2_digit = apple_pay_decrypt_data
.get_two_digit_expiry_year()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay expiry year",
})?;
let expiry_month = apple_pay_decrypt_data.get_expiry_month().change_context(
errors::ConnectorError::InvalidDataFormat {
field_name: "expiration_month",
},
)?;
Ok(Self {
card_data: ArchipelTokenizedCard {
expiry: CardExpiryDate {
year: expiry_year_2_digit,
month: expiry_month,
},
number: card_number,
scheme: ArchipelCardScheme::from(apple_pay_data.payment_method.network.as_str()),
},
wallet_information: {
ArchipelWalletInformation {
wallet_provider: ArchipelWalletProvider::ApplePay,
wallet_indicator: apple_pay_decrypt_data.payment_data.eci_indicator.clone(),
wallet_cryptogram: apple_pay_decrypt_data
.payment_data
.online_payment_cryptogram
.clone(),
}
},
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelTokenizedCard {
number: cards::CardNumber,
expiry: CardExpiryDate,
scheme: ArchipelCardScheme,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelCard {
number: cards::CardNumber,
expiry: CardExpiryDate,
security_code: Option<Secret<String>>,
card_holder_name: Option<Secret<String>>,
application_selection_indicator: ApplicationSelectionIndicator,
scheme: ArchipelCardScheme,
}
impl TryFrom<(Option<Secret<String>>, Option<ArchipelCardHolder>, &Card)> for ArchipelCard {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(card_holder_name, card_holder_billing, ccard): (
Option<Secret<String>>,
Option<ArchipelCardHolder>,
&Card,
),
) -> Result<Self, Self::Error> {
// NOTE: Archipel does not accept `card.card_holder_name` field without `cardholder` field.
// So if `card_holder` is None, `card.card_holder_name` must also be None.
// However, the reverse is allowed — the `cardholder` field can exist without `card.card_holder_name`.
let card_holder_name = card_holder_billing
.as_ref()
.and_then(|_| ccard.card_holder_name.clone().or(card_holder_name.clone()));
let scheme: ArchipelCardScheme = ccard.get_card_issuer().ok().into();
Ok(Self {
number: ccard.card_number.clone(),
expiry: CardExpiryDate {
month: ccard.card_exp_month.clone(),
year: ccard.get_card_expiry_year_2_digit()?,
},
security_code: Some(ccard.card_cvc.clone()),
application_selection_indicator: ApplicationSelectionIndicator::ByDefault,
card_holder_name,
scheme,
})
}
}
impl
TryFrom<(
Option<Secret<String>>,
Option<ArchipelCardHolder>,
&hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId,
)> for ArchipelCard
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(card_holder_name, card_holder_billing, card_details): (
Option<Secret<String>>,
Option<ArchipelCardHolder>,
&hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId,
),
) -> Result<Self, Self::Error> {
// NOTE: Archipel does not accept `card.card_holder_name` field without `cardholder` field.
// So if `card_holder` is None, `card.card_holder_name` must also be None.
// However, the reverse is allowed — the `cardholder` field can exist without `card.card_holder_name`.
let card_holder_name = card_holder_billing.as_ref().and_then(|_| {
card_details
.card_holder_name
.clone()
.or(card_holder_name.clone())
});
let scheme: ArchipelCardScheme = card_details.get_card_issuer().ok().into();
Ok(Self {
number: card_details.card_number.clone(),
expiry: CardExpiryDate {
month: card_details.card_exp_month.clone(),
year: card_details.get_card_expiry_year_2_digit()?,
},
security_code: None,
application_selection_indicator: ApplicationSelectionIndicator::ByDefault,
card_holder_name,
scheme,
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelWalletInformation {
wallet_indicator: Option<String>,
wallet_provider: ArchipelWalletProvider,
wallet_cryptogram: Secret<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelPaymentInformation {
order: ArchipelOrderRequest,
cardholder: Option<ArchipelCardHolder>,
card_holder_name: Option<Secret<String>>,
credential_indicator: Option<ArchipelCredentialIndicator>,
stored_on_file: bool,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelWalletAuthorizationRequest {
order: ArchipelOrderRequest,
card: ArchipelTokenizedCard,
cardholder: Option<ArchipelCardHolder>,
wallet: ArchipelWalletInformation,
#[serde(rename = "3DS")]
three_ds: Option<Archipel3DS>,
credential_indicator: Option<ArchipelCredentialIndicator>,
stored_on_file: bool,
tenant_id: ArchipelTenantId,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelCardAuthorizationRequest {
order: ArchipelOrderRequest,
card: ArchipelCard,
cardholder: Option<ArchipelCardHolder>,
#[serde(rename = "3DS")]
three_ds: Option<Archipel3DS>,
credential_indicator: Option<ArchipelCredentialIndicator>,
stored_on_file: bool,
tenant_id: ArchipelTenantId,
}
// PaymentsResponse
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "UPPERCASE")]
pub enum ArchipelCardScheme {
Amex,
Mastercard,
Visa,
Discover,
Diners,
Unknown,
}
impl From<&str> for ArchipelCardScheme {
fn from(input: &str) -> Self {
match input {
"Visa" => Self::Visa,
"Amex" => Self::Amex,
"Diners" => Self::Diners,
"MasterCard" => Self::Mastercard,
"Discover" => Self::Discover,
_ => Self::Unknown,
}
}
}
impl From<Option<CardIssuer>> for ArchipelCardScheme {
fn from(card_issuer: Option<CardIssuer>) -> Self {
match card_issuer {
Some(CardIssuer::Visa) => Self::Visa,
Some(CardIssuer::Master | CardIssuer::Maestro) => Self::Mastercard,
Some(CardIssuer::AmericanExpress) => Self::Amex,
Some(CardIssuer::Discover) => Self::Discover,
Some(CardIssuer::DinersClub) => Self::Diners,
_ => Self::Unknown,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum ArchipelPaymentStatus {
#[default]
Succeeded,
Failed,
}
impl TryFrom<(AttemptStatus, CaptureMethod)> for ArchipelPaymentFlow {
type Error = errors::ConnectorError;
fn try_from(
(status, capture_method): (AttemptStatus, CaptureMethod),
) -> Result<Self, Self::Error> {
let is_auto_capture = matches!(capture_method, CaptureMethod::Automatic);
match status {
AttemptStatus::AuthenticationFailed => Ok(Self::Verify),
AttemptStatus::Authorizing
| AttemptStatus::Authorized
| AttemptStatus::AuthorizationFailed => Ok(Self::Authorize),
AttemptStatus::Voided | AttemptStatus::VoidInitiated | AttemptStatus::VoidFailed => {
Ok(Self::Cancel)
}
AttemptStatus::CaptureInitiated | AttemptStatus::CaptureFailed => {
if is_auto_capture {
Ok(Self::Pay)
} else {
Ok(Self::Capture)
}
}
AttemptStatus::PaymentMethodAwaited | AttemptStatus::ConfirmationAwaited => {
if is_auto_capture {
Ok(Self::Pay)
} else {
Ok(Self::Authorize)
}
}
_ => Err(errors::ConnectorError::ProcessingStepFailed(Some(
Bytes::from_static(
"Impossible to determine Archipel flow from AttemptStatus".as_bytes(),
),
))),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ArchipelPaymentFlow {
Verify,
Authorize,
Pay,
Capture,
Cancel,
}
struct ArchipelFlowStatus {
status: ArchipelPaymentStatus,
flow: ArchipelPaymentFlow,
}
impl ArchipelFlowStatus {
fn new(status: ArchipelPaymentStatus, flow: ArchipelPaymentFlow) -> Self {
Self { status, flow }
}
}
impl From<ArchipelFlowStatus> for AttemptStatus {
fn from(ArchipelFlowStatus { status, flow }: ArchipelFlowStatus) -> Self {
match status {
ArchipelPaymentStatus::Succeeded => match flow {
ArchipelPaymentFlow::Authorize => Self::Authorized,
ArchipelPaymentFlow::Pay
| ArchipelPaymentFlow::Verify
| ArchipelPaymentFlow::Capture => Self::Charged,
ArchipelPaymentFlow::Cancel => Self::Voided,
},
ArchipelPaymentStatus::Failed => match flow {
ArchipelPaymentFlow::Authorize | ArchipelPaymentFlow::Pay => {
Self::AuthorizationFailed
}
ArchipelPaymentFlow::Verify => Self::AuthenticationFailed,
ArchipelPaymentFlow::Capture => Self::CaptureFailed,
ArchipelPaymentFlow::Cancel => Self::VoidFailed,
},
}
}
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelOrderResponse {
id: String,
amount: Option<i64>,
currency: Option<Currency>,
captured_amount: Option<i64>,
authorized_amount: Option<i64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ArchipelErrorMessage {
pub code: String,
pub description: Option<String>,
}
impl Default for ArchipelErrorMessage {
fn default() -> Self {
Self {
code: consts::NO_ERROR_CODE.to_string(),
description: Some(consts::NO_ERROR_MESSAGE.to_string()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct ArchipelErrorMessageWithHttpCode {
error_message: ArchipelErrorMessage,
http_code: u16,
}
impl ArchipelErrorMessageWithHttpCode {
fn new(error_message: ArchipelErrorMessage, http_code: u16) -> Self {
Self {
error_message,
http_code,
}
}
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelTransactionMetadata {
pub transaction_id: String,
pub transaction_date: String,
pub financial_network_code: Option<String>,
pub issuer_transaction_id: Option<String>,
pub response_code: Option<String>,
pub authorization_code: Option<String>,
pub payment_account_reference: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelPaymentsResponse {
order: ArchipelOrderResponse,
transaction_id: String,
transaction_date: String,
transaction_result: ArchipelPaymentStatus,
error: Option<ArchipelErrorMessage>,
financial_network_code: Option<String>,
issuer_transaction_id: Option<String>,
response_code: Option<String>,
authorization_code: Option<String>,
payment_account_reference: Option<Secret<String>>,
}
impl From<&ArchipelPaymentsResponse> for ArchipelTransactionMetadata {
fn from(payment_response: &ArchipelPaymentsResponse) -> Self {
Self {
transaction_id: payment_response.transaction_id.clone(),
transaction_date: payment_response.transaction_date.clone(),
financial_network_code: payment_response.financial_network_code.clone(),
issuer_transaction_id: payment_response.issuer_transaction_id.clone(),
response_code: payment_response.response_code.clone(),
authorization_code: payment_response.authorization_code.clone(),
payment_account_reference: payment_response.payment_account_reference.clone(),
}
}
}
// AUTHORIZATION FLOW
impl TryFrom<(MinorUnit, &PaymentsAuthorizeRouterData)> for ArchipelPaymentInformation {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(amount, router_data): (MinorUnit, &PaymentsAuthorizeRouterData),
) -> Result<Self, Self::Error> {
let is_recurring_payment = router_data
.request
.mandate_id
.as_ref()
.and_then(|mandate_ids| mandate_ids.mandate_id.as_ref())
.is_some();
let is_subsequent_trx = router_data
.request
.mandate_id
.as_ref()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref())
.is_some();
let is_saved_card_payment = (router_data.request.is_mandate_payment())
| (router_data.request.setup_future_usage == Some(FutureUsage::OnSession))
| (router_data.payment_method_status == Some(PaymentMethodStatus::Active));
let certainty = if router_data.request.request_incremental_authorization {
if is_recurring_payment {
ArchipelPaymentCertainty::Final
} else {
ArchipelPaymentCertainty::Estimated
}
} else {
ArchipelPaymentCertainty::Final
};
let transaction_initiator = if is_recurring_payment {
ArchipelPaymentInitiator::Merchant
} else {
ArchipelPaymentInitiator::Customer
};
let order = ArchipelOrderRequest {
amount,
currency: router_data.request.currency.to_string(),
certainty,
initiator: transaction_initiator.clone(),
};
let cardholder = router_data
.get_billing_address()
.ok()
.and_then(|address| address.to_archipel_billing_address())
.map(|billing_address| ArchipelCardHolder {
billing_address: Some(billing_address),
});
// NOTE: Archipel does not accept `card.card_holder_name` field without `cardholder` field.
// So if `card_holder` is None, `card.card_holder_name` must also be None.
// However, the reverse is allowed — the `cardholder` field can exist without `card.card_holder_name`.
let card_holder_name = cardholder.as_ref().and_then(|_| {
router_data
.get_billing()
.ok()
.and_then(|billing| billing.get_optional_full_name())
});
let indicator_status = if is_subsequent_trx {
ArchipelCredentialIndicatorStatus::Subsequent
} else {
ArchipelCredentialIndicatorStatus::Initial
};
let stored_on_file =
is_saved_card_payment | router_data.request.is_customer_initiated_mandate_payment();
let credential_indicator = stored_on_file.then(|| ArchipelCredentialIndicator {
status: indicator_status.clone(),
recurring: Some(is_recurring_payment),
transaction_id: match indicator_status {
ArchipelCredentialIndicatorStatus::Initial => None,
ArchipelCredentialIndicatorStatus::Subsequent => {
router_data.request.get_optional_network_transaction_id()
}
},
});
Ok(Self {
order,
cardholder,
card_holder_name,
credential_indicator,
stored_on_file,
})
}
}
impl TryFrom<ArchipelRouterData<&PaymentsAuthorizeRouterData>>
for ArchipelCardAuthorizationRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ArchipelRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let ArchipelRouterData {
amount,
tenant_id,
router_data,
} = item;
let payment_information: ArchipelPaymentInformation =
ArchipelPaymentInformation::try_from((amount, router_data))?;
let payment_method_data = match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(ccard) => ArchipelCard::try_from((
payment_information.card_holder_name,
payment_information.cardholder.clone(),
ccard,
))?,
PaymentMethodData::CardDetailsForNetworkTransactionId(card_details) => {
ArchipelCard::try_from((
payment_information.card_holder_name,
payment_information.cardholder.clone(),
card_details,
))?
}
PaymentMethodData::CardRedirect(..)
| PaymentMethodData::Wallet(..)
| PaymentMethodData::PayLater(..)
| PaymentMethodData::BankRedirect(..)
| PaymentMethodData::BankDebit(..)
| PaymentMethodData::BankTransfer(..)
| PaymentMethodData::Crypto(..)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(..)
| PaymentMethodData::Upi(..)
| PaymentMethodData::Voucher(..)
| PaymentMethodData::GiftCard(..)
| PaymentMethodData::CardToken(..)
| PaymentMethodData::OpenBanking(..)
| PaymentMethodData::NetworkToken(..)
| PaymentMethodData::MobilePayment(..) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Archipel"),
))?,
};
let three_ds: Option<Archipel3DS> = if item.router_data.is_three_ds() {
let auth_data = item
.router_data
.request
.get_authentication_data()
.change_context(errors::ConnectorError::NotSupported {
message: "Selected 3DS authentication method".to_string(),
connector: "archipel",
})?;
Some(Archipel3DS::from(auth_data))
} else {
None
};
Ok(Self {
order: payment_information.order,
cardholder: payment_information.cardholder,
card: payment_method_data,
three_ds,
credential_indicator: payment_information.credential_indicator,
stored_on_file: payment_information.stored_on_file,
tenant_id,
})
}
}
impl TryFrom<ArchipelRouterData<&PaymentsAuthorizeRouterData>>
for ArchipelWalletAuthorizationRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ArchipelRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let ArchipelRouterData {
amount,
tenant_id,
router_data,
} = item;
let payment_information = ArchipelPaymentInformation::try_from((amount, router_data))?;
let payment_method_data = match &item.router_data.request.payment_method_data {
PaymentMethodData::Wallet(wallet_data) => {
TokenizedCardData::try_from((wallet_data, &item.router_data.payment_method_token))?
}
PaymentMethodData::Card(..)
| PaymentMethodData::CardDetailsForNetworkTransactionId(..)
| PaymentMethodData::CardRedirect(..)
| PaymentMethodData::PayLater(..)
| PaymentMethodData::BankRedirect(..)
| PaymentMethodData::BankDebit(..)
| PaymentMethodData::BankTransfer(..)
| PaymentMethodData::Crypto(..)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(..)
| PaymentMethodData::Upi(..)
| PaymentMethodData::Voucher(..)
| PaymentMethodData::GiftCard(..)
| PaymentMethodData::CardToken(..)
| PaymentMethodData::OpenBanking(..)
| PaymentMethodData::NetworkToken(..)
| PaymentMethodData::MobilePayment(..) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Archipel"),
))?,
};
Ok(Self {
order: payment_information.order,
cardholder: payment_information.cardholder,
card: payment_method_data.card_data.clone(),
wallet: payment_method_data.wallet_information.clone(),
three_ds: None,
credential_indicator: payment_information.credential_indicator,
stored_on_file: payment_information.stored_on_file,
tenant_id,
})
}
}
// Responses for AUTHORIZATION FLOW
impl<F>
TryFrom<
ResponseRouterData<
F,
ArchipelPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
ArchipelPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
if let Some(error) = item.response.error {
return Ok(Self {
response: Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),
..item.data
});
};
let capture_method = item
.data
.request
.capture_method
.ok_or_else(|| errors::ConnectorError::CaptureMethodNotSupported)?;
let (archipel_flow, is_incremental_allowed) = match capture_method {
CaptureMethod::Automatic => (ArchipelPaymentFlow::Pay, false),
_ => (
ArchipelPaymentFlow::Authorize,
item.data.request.request_incremental_authorization,
),
};
let connector_metadata: Option<serde_json::Value> =
ArchipelTransactionMetadata::from(&item.response)
.encode_to_value()
.ok();
let status: AttemptStatus =
ArchipelFlowStatus::new(item.response.transaction_result, archipel_flow).into();
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order.id),
charges: None,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
// Save archipel initial transaction uuid for network transaction mit/cit
network_txn_id: item
.data
.request
.is_customer_initiated_mandate_payment()
.then_some(item.response.transaction_id),
connector_response_reference_id: None,
incremental_authorization_allowed: Some(is_incremental_allowed),
}),
..item.data
})
}
}
// PSYNC FLOW
impl<F>
TryFrom<ResponseRouterData<F, ArchipelPaymentsResponse, PaymentsSyncData, PaymentsResponseData>>
for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
ArchipelPaymentsResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
if let Some(error) = item.response.error {
return Ok(Self {
response: Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),
..item.data
});
};
let connector_metadata: Option<serde_json::Value> =
ArchipelTransactionMetadata::from(&item.response)
.encode_to_value()
.ok();
let capture_method = item
.data
.request
.capture_method
.ok_or_else(|| errors::ConnectorError::CaptureMethodNotSupported)?;
let archipel_flow: ArchipelPaymentFlow = (item.data.status, capture_method).try_into()?;
let status: AttemptStatus =
ArchipelFlowStatus::new(item.response.transaction_result, archipel_flow).into();
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order.id),
charges: None,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
}),
..item.data
})
}
}
/* CAPTURE FLOW */
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct ArchipelCaptureRequest {
order: ArchipelCaptureOrderRequest,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct ArchipelCaptureOrderRequest {
amount: MinorUnit,
}
impl From<ArchipelRouterData<&PaymentsCaptureRouterData>> for ArchipelCaptureRequest {
fn from(item: ArchipelRouterData<&PaymentsCaptureRouterData>) -> Self {
Self {
order: ArchipelCaptureOrderRequest {
amount: item.amount,
},
}
}
}
impl<F>
TryFrom<
ResponseRouterData<F, ArchipelPaymentsResponse, PaymentsCaptureData, PaymentsResponseData>,
> for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
ArchipelPaymentsResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
if let Some(error) = item.response.error {
return Ok(Self {
response: Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),
..item.data
});
};
let connector_metadata: Option<serde_json::Value> =
ArchipelTransactionMetadata::from(&item.response)
.encode_to_value()
.ok();
let status: AttemptStatus = ArchipelFlowStatus::new(
item.response.transaction_result,
ArchipelPaymentFlow::Capture,
)
.into();
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order.id),
charges: None,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
}),
..item.data
})
}
}
// Setup Mandate FLow
impl TryFrom<ArchipelRouterData<&SetupMandateRouterData>> for ArchipelCardAuthorizationRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: ArchipelRouterData<&SetupMandateRouterData>) -> Result<Self, Self::Error> {
let order = ArchipelOrderRequest {
amount: item.amount,
currency: item.router_data.request.currency.to_string(),
certainty: ArchipelPaymentCertainty::Final,
initiator: ArchipelPaymentInitiator::Customer,
};
let cardholder = Some(ArchipelCardHolder {
billing_address: item
.router_data
.get_billing_address()
.ok()
.and_then(|address| address.to_archipel_billing_address()),
});
// NOTE: Archipel does not accept `card.card_holder_name` field without `cardholder` field.
// So if `card_holder` is None, `card.card_holder_name` must also be None.
// However, the reverse is allowed — the `cardholder` field can exist without `card.card_holder_name`.
let card_holder_name = cardholder.as_ref().and_then(|_| {
item.router_data
.get_billing()
.ok()
.and_then(|billing| billing.get_optional_full_name())
});
let stored_on_file = true;
let credential_indicator = Some(ArchipelCredentialIndicator {
status: ArchipelCredentialIndicatorStatus::Initial,
recurring: Some(false),
transaction_id: None,
});
let payment_information = ArchipelPaymentInformation {
order,
cardholder,
card_holder_name,
stored_on_file,
credential_indicator,
};
let card_data = match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(ccard) => ArchipelCard::try_from((
payment_information.card_holder_name,
payment_information.cardholder.clone(),
ccard,
))?,
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Archipel"),
))?,
};
Ok(Self {
order: payment_information.order,
cardholder: payment_information.cardholder.clone(),
card: card_data,
three_ds: None,
credential_indicator: payment_information.credential_indicator,
stored_on_file: payment_information.stored_on_file,
tenant_id: item.tenant_id,
})
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
ArchipelPaymentsResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
> for RouterData<F, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
ArchipelPaymentsResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
if let Some(error) = item.response.error {
return Ok(Self {
response: Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),
..item.data
});
};
let connector_metadata: Option<serde_json::Value> =
ArchipelTransactionMetadata::from(&item.response)
.encode_to_value()
.ok();
let status: AttemptStatus = ArchipelFlowStatus::new(
item.response.transaction_result,
ArchipelPaymentFlow::Verify,
)
.into();
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order.id),
charges: None,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: Some(item.response.transaction_id.clone()),
connector_response_reference_id: Some(item.response.transaction_id),
incremental_authorization_allowed: Some(false),
}),
..item.data
})
}
}
// Void Flow => /cancel/{order_id}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelPaymentsCancelRequest {
tenant_id: ArchipelTenantId,
}
impl From<ArchipelRouterData<&PaymentsCancelRouterData>> for ArchipelPaymentsCancelRequest {
fn from(item: ArchipelRouterData<&PaymentsCancelRouterData>) -> Self {
Self {
tenant_id: item.tenant_id,
}
}
}
impl<F>
TryFrom<
ResponseRouterData<F, ArchipelPaymentsResponse, PaymentsCancelData, PaymentsResponseData>,
> for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
ArchipelPaymentsResponse,
PaymentsCancelData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
if let Some(error) = item.response.error {
return Ok(Self {
response: Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),
..item.data
});
};
let connector_metadata: Option<serde_json::Value> =
ArchipelTransactionMetadata::from(&item.response)
.encode_to_value()
.ok();
let status: AttemptStatus = ArchipelFlowStatus::new(
item.response.transaction_result,
ArchipelPaymentFlow::Cancel,
)
.into();
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order.id),
charges: None,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelIncrementalAuthorizationRequest {
order: ArchipelOrderRequest,
tenant_id: ArchipelTenantId,
}
// Incremental Authorization status mapping
impl From<ArchipelPaymentStatus> for AuthorizationStatus {
fn from(status: ArchipelPaymentStatus) -> Self {
match status {
ArchipelPaymentStatus::Succeeded => Self::Success,
ArchipelPaymentStatus::Failed => Self::Failure,
}
}
}
impl From<ArchipelRouterData<&PaymentsIncrementalAuthorizationRouterData>>
for ArchipelIncrementalAuthorizationRequest
{
fn from(item: ArchipelRouterData<&PaymentsIncrementalAuthorizationRouterData>) -> Self {
Self {
order: ArchipelOrderRequest {
amount: item.amount,
currency: item.router_data.request.currency.to_string(),
certainty: ArchipelPaymentCertainty::Estimated,
initiator: ArchipelPaymentInitiator::Customer,
},
tenant_id: item.tenant_id,
}
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
ArchipelPaymentsResponse,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsIncrementalAuthorizationData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
ArchipelPaymentsResponse,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = AuthorizationStatus::from(item.response.transaction_result);
let (error_code, error_message) = match (&status, item.response.error) {
(AuthorizationStatus::Success, _) | (_, None) => (None, None),
(_, Some(err)) => (Some(err.code), err.description),
};
Ok(Self {
response: Ok(PaymentsResponseData::IncrementalAuthorizationResponse {
status,
error_code,
error_message,
connector_authorization_id: None,
}),
..item.data
})
}
}
/* REFUND FLOW */
#[derive(Debug, Serialize)]
pub struct ArchipelRefundOrder {
pub amount: MinorUnit,
pub currency: Currency,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelRefundRequest {
pub order: ArchipelRefundOrder,
pub tenant_id: ArchipelTenantId,
}
impl<F> From<ArchipelRouterData<&RefundsRouterData<F>>> for ArchipelRefundRequest {
fn from(item: ArchipelRouterData<&RefundsRouterData<F>>) -> Self {
Self {
order: ArchipelRefundOrder {
amount: item.amount,
currency: item.router_data.request.currency,
},
tenant_id: item.tenant_id,
}
}
}
// Type definition for Refund Response
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum ArchipelRefundStatus {
Accepted,
Failed,
#[default]
Pending,
}
impl From<ArchipelPaymentStatus> for RefundStatus {
fn from(item: ArchipelPaymentStatus) -> Self {
match item {
ArchipelPaymentStatus::Succeeded => Self::Success,
ArchipelPaymentStatus::Failed => Self::Failure,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct ArchipelRefundOrderResponse {
id: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelRefundResponse {
order: ArchipelRefundOrderResponse,
status: ArchipelRefundStatus,
transaction_result: ArchipelPaymentStatus,
transaction_id: Option<String>,
transaction_date: Option<String>,
error: Option<ArchipelErrorMessage>,
}
impl TryFrom<ArchipelRefundResponse> for RefundsResponseData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(resp: ArchipelRefundResponse) -> Result<Self, Self::Error> {
Ok(Self {
connector_refund_id: resp
.transaction_id
.ok_or_else(|| errors::ConnectorError::ParsingFailed)?,
refund_status: RefundStatus::from(resp.transaction_result),
})
}
}
impl TryFrom<RefundsResponseRouterData<Execute, ArchipelRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, ArchipelRefundResponse>,
) -> Result<Self, Self::Error> {
let response = match item.response.error {
None => Ok(RefundsResponseData::try_from(item.response)?),
Some(error) => Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),
};
Ok(Self {
response,
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, ArchipelRefundResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, ArchipelRefundResponse>,
) -> Result<Self, Self::Error> {
let response = match item.response.error {
None => Ok(RefundsResponseData::try_from(item.response)?),
Some(error) => Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),
};
Ok(Self {
response,
..item.data
})
}
}
impl From<ArchipelErrorMessageWithHttpCode> for ErrorResponse {
fn from(
ArchipelErrorMessageWithHttpCode {
error_message,
http_code,
}: ArchipelErrorMessageWithHttpCode,
) -> Self {
Self {
status_code: http_code,
code: error_message.code,
attempt_status: None,
connector_transaction_id: None,
message: error_message
.description
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: error_message.description,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 10361
}
|
large_file_7483827540636989620
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/payload/transformers.rs
</path>
<file>
use std::collections::HashMap;
use api_models::webhooks::IncomingWebhookEvent;
use common_enums::enums;
use common_utils::{ext_traits::ValueExt, types::StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
address::AddressDetails,
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, RefundsRouterData,
SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeOptionInterface, Secret};
use serde::Deserialize;
use super::{requests, responses};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
get_unimplemented_payment_method_error_message, is_manual_capture, AddressDetailsData,
CardData, PaymentsAuthorizeRequestData, PaymentsSetupMandateRequestData,
RouterData as OtherRouterData,
},
};
type Error = error_stack::Report<errors::ConnectorError>;
fn build_payload_cards_request_data(
payment_method_data: &PaymentMethodData,
connector_auth_type: &ConnectorAuthType,
currency: enums::Currency,
amount: StringMajorUnit,
billing_address: &AddressDetails,
capture_method: Option<enums::CaptureMethod>,
is_mandate: bool,
) -> Result<requests::PayloadCardsRequestData, Error> {
if let PaymentMethodData::Card(req_card) = payment_method_data {
let payload_auth = PayloadAuth::try_from((connector_auth_type, currency))?;
let card = requests::PayloadCard {
number: req_card.clone().card_number,
expiry: req_card
.clone()
.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?,
cvc: req_card.card_cvc.clone(),
};
let city = billing_address.get_city()?.to_owned();
let country = billing_address.get_country()?.to_owned();
let postal_code = billing_address.get_zip()?.to_owned();
let state_province = billing_address.get_state()?.to_owned();
let street_address = billing_address.get_line1()?.to_owned();
let billing_address = requests::BillingAddress {
city,
country,
postal_code,
state_province,
street_address,
};
// For manual capture, set status to "authorized"
let status = if is_manual_capture(capture_method) {
Some(responses::PayloadPaymentStatus::Authorized)
} else {
None
};
Ok(requests::PayloadCardsRequestData {
amount,
card,
transaction_types: requests::TransactionTypes::Payment,
payment_method_type: "card".to_string(),
status,
billing_address,
processing_id: payload_auth.processing_account_id,
keep_active: is_mandate,
})
} else {
Err(
errors::ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message(
"Payload",
))
.into(),
)
}
}
pub struct PayloadRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for PayloadRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
// Auth Struct
#[derive(Debug, Clone, Deserialize)]
pub struct PayloadAuth {
pub api_key: Secret<String>,
pub processing_account_id: Option<Secret<String>>,
}
#[derive(Debug, Clone)]
pub struct PayloadAuthType {
pub auths: HashMap<enums::Currency, PayloadAuth>,
}
impl TryFrom<(&ConnectorAuthType, enums::Currency)> for PayloadAuth {
type Error = Error;
fn try_from(value: (&ConnectorAuthType, enums::Currency)) -> Result<Self, Self::Error> {
let (auth_type, currency) = value;
match auth_type {
ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
let auth_key = auth_key_map.get(¤cy).ok_or(
errors::ConnectorError::CurrencyNotSupported {
message: currency.to_string(),
connector: "Payload",
},
)?;
auth_key
.to_owned()
.parse_value("PayloadAuth")
.change_context(errors::ConnectorError::FailedToObtainAuthType)
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<&ConnectorAuthType> for PayloadAuthType {
type Error = Error;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
let auths = auth_key_map
.iter()
.map(|(currency, auth_key)| {
let auth: PayloadAuth = auth_key
.to_owned()
.parse_value("PayloadAuth")
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "auth_key_map",
})?;
Ok((*currency, auth))
})
.collect::<Result<_, Self::Error>>()?;
Ok(Self { auths })
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<&SetupMandateRouterData> for requests::PayloadCardsRequestData {
type Error = Error;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
match item.request.amount {
Some(amount) if amount > 0 => Err(errors::ConnectorError::FlowNotSupported {
flow: "Setup mandate with non zero amount".to_string(),
connector: "Payload".to_string(),
}
.into()),
_ => {
let billing_address = item.get_billing_address()?;
let is_mandate = item.request.is_customer_initiated_mandate_payment();
build_payload_cards_request_data(
&item.request.payment_method_data,
&item.connector_auth_type,
item.request.currency,
StringMajorUnit::zero(),
billing_address,
item.request.capture_method,
is_mandate,
)
}
}
}
}
impl TryFrom<&PayloadRouterData<&PaymentsAuthorizeRouterData>>
for requests::PayloadPaymentsRequest
{
type Error = Error;
fn try_from(
item: &PayloadRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if item.router_data.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Cards 3DS".to_string(),
connector: "Payload",
})?
}
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(_) => {
let billing_address = item.router_data.get_billing_address()?;
let is_mandate = item.router_data.request.is_mandate_payment();
let cards_data = build_payload_cards_request_data(
&item.router_data.request.payment_method_data,
&item.router_data.connector_auth_type,
item.router_data.request.currency,
item.amount.clone(),
billing_address,
item.router_data.request.capture_method,
is_mandate,
)?;
Ok(Self::PayloadCardsRequest(Box::new(cards_data)))
}
PaymentMethodData::MandatePayment => {
// For manual capture, set status to "authorized"
let status = if is_manual_capture(item.router_data.request.capture_method) {
Some(responses::PayloadPaymentStatus::Authorized)
} else {
None
};
Ok(Self::PayloadMandateRequest(Box::new(
requests::PayloadMandateRequestData {
amount: item.amount.clone(),
transaction_types: requests::TransactionTypes::Payment,
payment_method_id: Secret::new(
item.router_data.request.get_connector_mandate_id()?,
),
status,
},
)))
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
impl From<responses::PayloadPaymentStatus> for common_enums::AttemptStatus {
fn from(item: responses::PayloadPaymentStatus) -> Self {
match item {
responses::PayloadPaymentStatus::Authorized => Self::Authorized,
responses::PayloadPaymentStatus::Processed => Self::Charged,
responses::PayloadPaymentStatus::Processing => Self::Pending,
responses::PayloadPaymentStatus::Rejected
| responses::PayloadPaymentStatus::Declined => Self::Failure,
responses::PayloadPaymentStatus::Voided => Self::Voided,
}
}
}
impl<F: 'static, T>
TryFrom<ResponseRouterData<F, responses::PayloadPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
where
T: 'static,
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, responses::PayloadPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.clone() {
responses::PayloadPaymentsResponse::PayloadCardsResponse(response) => {
let status = enums::AttemptStatus::from(response.status);
let router_data: &dyn std::any::Any = &item.data;
let is_mandate_payment = router_data
.downcast_ref::<PaymentsAuthorizeRouterData>()
.is_some_and(|router_data| router_data.request.is_mandate_payment())
|| router_data
.downcast_ref::<SetupMandateRouterData>()
.is_some();
let mandate_reference = if is_mandate_payment {
let connector_payment_method_id =
response.connector_payment_method_id.clone().expose_option();
if connector_payment_method_id.is_some() {
Some(MandateReference {
connector_mandate_id: connector_payment_method_id,
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})
} else {
None
}
} else {
None
};
let response_result = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
attempt_status: None,
code: response
.status_code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: response
.status_message
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: response.status_message,
status_code: item.http_code,
connector_transaction_id: Some(response.transaction_id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.transaction_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: response.ref_number,
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response: response_result,
..item.data
})
}
}
}
}
impl<T> TryFrom<&PayloadRouterData<T>> for requests::PayloadCancelRequest {
type Error = Error;
fn try_from(_item: &PayloadRouterData<T>) -> Result<Self, Self::Error> {
Ok(Self {
status: responses::PayloadPaymentStatus::Voided,
})
}
}
impl TryFrom<&PayloadRouterData<&PaymentsCaptureRouterData>> for requests::PayloadCaptureRequest {
type Error = Error;
fn try_from(
_item: &PayloadRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: responses::PayloadPaymentStatus::Processed,
})
}
}
impl<F> TryFrom<&PayloadRouterData<&RefundsRouterData<F>>> for requests::PayloadRefundRequest {
type Error = Error;
fn try_from(item: &PayloadRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let connector_transaction_id = item.router_data.request.connector_transaction_id.clone();
Ok(Self {
transaction_type: requests::TransactionTypes::Refund,
amount: item.amount.to_owned(),
ledger_assoc_transaction_id: connector_transaction_id,
})
}
}
impl From<responses::RefundStatus> for enums::RefundStatus {
fn from(item: responses::RefundStatus) -> Self {
match item {
responses::RefundStatus::Processed => Self::Success,
responses::RefundStatus::Processing => Self::Pending,
responses::RefundStatus::Declined | responses::RefundStatus::Rejected => Self::Failure,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, responses::PayloadRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<Execute, responses::PayloadRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, responses::PayloadRefundResponse>>
for RefundsRouterData<RSync>
{
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<RSync, responses::PayloadRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
// Webhook transformations
impl From<responses::PayloadWebhooksTrigger> for IncomingWebhookEvent {
fn from(trigger: responses::PayloadWebhooksTrigger) -> Self {
match trigger {
// Payment Success Events
responses::PayloadWebhooksTrigger::Processed => Self::PaymentIntentSuccess,
responses::PayloadWebhooksTrigger::Authorized => {
Self::PaymentIntentAuthorizationSuccess
}
// Payment Processing Events
responses::PayloadWebhooksTrigger::Payment
| responses::PayloadWebhooksTrigger::AutomaticPayment => Self::PaymentIntentProcessing,
// Payment Failure Events
responses::PayloadWebhooksTrigger::Decline
| responses::PayloadWebhooksTrigger::Reject
| responses::PayloadWebhooksTrigger::BankAccountReject => Self::PaymentIntentFailure,
responses::PayloadWebhooksTrigger::Void
| responses::PayloadWebhooksTrigger::Reversal => Self::PaymentIntentCancelled,
// Refund Events
responses::PayloadWebhooksTrigger::Refund => Self::RefundSuccess,
// Dispute Events
responses::PayloadWebhooksTrigger::Chargeback => Self::DisputeOpened,
responses::PayloadWebhooksTrigger::ChargebackReversal => Self::DisputeWon,
// Other payment-related events
// Events not supported by our standard flows
responses::PayloadWebhooksTrigger::PaymentActivationStatus
| responses::PayloadWebhooksTrigger::Credit
| responses::PayloadWebhooksTrigger::Deposit
| responses::PayloadWebhooksTrigger::PaymentLinkStatus
| responses::PayloadWebhooksTrigger::ProcessingStatus
| responses::PayloadWebhooksTrigger::TransactionOperation
| responses::PayloadWebhooksTrigger::TransactionOperationClear => {
Self::EventNotSupported
}
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/payload/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3420
}
|
large_file_816643401444564205
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
</path>
<file>
use common_enums::enums;
use common_utils::{ext_traits::Encode, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{self, RefundsRouterData},
};
use hyperswitch_interfaces::{consts, errors};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{get_unimplemented_payment_method_error_message, RouterData as _},
};
type Error = error_stack::Report<errors::ConnectorError>;
#[derive(Debug, Serialize)]
pub struct GlobepayRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for GlobepayRouterData<T> {
fn from((amount, router_data): (MinorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Serialize)]
pub struct GlobepayPaymentsRequest {
price: MinorUnit,
description: String,
currency: enums::Currency,
channel: GlobepayChannel,
}
#[derive(Debug, Serialize)]
pub enum GlobepayChannel {
Alipay,
Wechat,
}
impl TryFrom<&GlobepayRouterData<&types::PaymentsAuthorizeRouterData>> for GlobepayPaymentsRequest {
type Error = Error;
fn try_from(
item_data: &GlobepayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let item = item_data.router_data.clone();
let channel: GlobepayChannel = match &item.request.payment_method_data {
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletData::AliPayQr(_) => GlobepayChannel::Alipay,
WalletData::WeChatPayQr(_) => GlobepayChannel::Wechat,
WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePay(_)
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("globepay"),
))?,
},
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("globepay"),
))?
}
};
let description = item.get_description()?;
Ok(Self {
price: item_data.amount,
description,
currency: item.request.currency,
channel,
})
}
}
pub struct GlobepayAuthType {
pub(super) partner_code: Secret<String>,
pub(super) credential_code: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for GlobepayAuthType {
type Error = Error;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
partner_code: api_key.to_owned(),
credential_code: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GlobepayPaymentStatus {
Success,
Exists,
}
impl From<GlobepayPaymentStatus> for enums::AttemptStatus {
fn from(item: GlobepayPaymentStatus) -> Self {
match item {
GlobepayPaymentStatus::Success => Self::AuthenticationPending, // this connector only have redirection flows so "Success" is mapped to authenticatoin pending ,ref = "https://pay.globepay.co/docs/en/#api-QRCode-NewQRCode"
GlobepayPaymentStatus::Exists => Self::Failure,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GlobepayConnectorMetadata {
image_data_url: url::Url,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GlobepayPaymentsResponse {
result_code: Option<GlobepayPaymentStatus>,
order_id: Option<String>,
qrcode_img: Option<url::Url>,
return_code: GlobepayReturnCode, //Execution result
return_msg: Option<String>,
}
#[derive(Debug, Deserialize, PartialEq, strum::Display, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GlobepayReturnCode {
Success,
OrderNotExist,
OrderMismatch,
Systemerror,
InvalidShortId,
SignTimeout,
InvalidSign,
ParamInvalid,
NotPermitted,
InvalidChannel,
DuplicateOrderId,
OrderNotPaid,
}
impl<F, T> TryFrom<ResponseRouterData<F, GlobepayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, GlobepayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
if item.response.return_code == GlobepayReturnCode::Success {
let globepay_metadata = GlobepayConnectorMetadata {
image_data_url: item
.response
.qrcode_img
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?,
};
let connector_metadata = Some(globepay_metadata.encode_to_value())
.transpose()
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let globepay_status = item
.response
.result_code
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(Self {
status: enums::AttemptStatus::from(globepay_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response
.order_id
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?,
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: enums::AttemptStatus::Failure, //As this connector gives 200 in failed scenarios . if return_code is not success status is mapped to failure. ref = "https://pay.globepay.co/docs/en/#api-QRCode-NewQRCode"
response: Err(get_error_response(
item.response.return_code,
item.response.return_msg,
item.http_code,
)),
..item.data
})
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GlobepaySyncResponse {
pub result_code: Option<GlobepayPaymentPsyncStatus>,
pub order_id: Option<String>,
pub return_code: GlobepayReturnCode,
pub return_msg: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GlobepayPaymentPsyncStatus {
Paying,
CreateFail,
Closed,
PayFail,
PaySuccess,
}
impl From<GlobepayPaymentPsyncStatus> for enums::AttemptStatus {
fn from(item: GlobepayPaymentPsyncStatus) -> Self {
match item {
GlobepayPaymentPsyncStatus::PaySuccess => Self::Charged,
GlobepayPaymentPsyncStatus::PayFail
| GlobepayPaymentPsyncStatus::CreateFail
| GlobepayPaymentPsyncStatus::Closed => Self::Failure,
GlobepayPaymentPsyncStatus::Paying => Self::AuthenticationPending,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, GlobepaySyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, GlobepaySyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
if item.response.return_code == GlobepayReturnCode::Success {
let globepay_status = item
.response
.result_code
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let globepay_id = item
.response
.order_id
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(Self {
status: enums::AttemptStatus::from(globepay_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(globepay_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: enums::AttemptStatus::Failure, //As this connector gives 200 in failed scenarios . if return_code is not success status is mapped to failure. ref = "https://pay.globepay.co/docs/en/#api-QRCode-NewQRCode"
response: Err(get_error_response(
item.response.return_code,
item.response.return_msg,
item.http_code,
)),
..item.data
})
}
}
}
fn get_error_response(
return_code: GlobepayReturnCode,
return_msg: Option<String>,
status_code: u16,
) -> ErrorResponse {
ErrorResponse {
code: return_code.to_string(),
message: consts::NO_ERROR_MESSAGE.to_string(),
reason: return_msg,
status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
#[derive(Debug, Serialize)]
pub struct GlobepayRefundRequest {
pub fee: MinorUnit,
}
impl<F> TryFrom<&GlobepayRouterData<&RefundsRouterData<F>>> for GlobepayRefundRequest {
type Error = Error;
fn try_from(item: &GlobepayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self { fee: item.amount })
}
}
#[derive(Debug, Deserialize, Serialize)]
pub enum GlobepayRefundStatus {
Waiting,
CreateFailed,
Failed,
Success,
Finished,
Change,
}
impl From<GlobepayRefundStatus> for enums::RefundStatus {
fn from(item: GlobepayRefundStatus) -> Self {
match item {
GlobepayRefundStatus::Finished => Self::Success, //FINISHED: Refund success(funds has already been returned to user's account)
GlobepayRefundStatus::Failed
| GlobepayRefundStatus::CreateFailed
| GlobepayRefundStatus::Change => Self::Failure, //CHANGE: Refund can not return to user's account. Manual operation is required
GlobepayRefundStatus::Waiting | GlobepayRefundStatus::Success => Self::Pending, // SUCCESS: Submission succeeded, but refund is not yet complete. Waiting = Submission succeeded, but refund is not yet complete.
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GlobepayRefundResponse {
pub result_code: Option<GlobepayRefundStatus>,
pub refund_id: Option<String>,
pub return_code: GlobepayReturnCode,
pub return_msg: Option<String>,
}
impl<T> TryFrom<RefundsResponseRouterData<T, GlobepayRefundResponse>> for RefundsRouterData<T> {
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<T, GlobepayRefundResponse>,
) -> Result<Self, Self::Error> {
if item.response.return_code == GlobepayReturnCode::Success {
let globepay_refund_id = item
.response
.refund_id
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let globepay_refund_status = item
.response
.result_code
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: globepay_refund_id,
refund_status: enums::RefundStatus::from(globepay_refund_status),
}),
..item.data
})
} else {
Ok(Self {
response: Err(get_error_response(
item.response.return_code,
item.response.return_msg,
item.http_code,
)),
..item.data
})
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GlobepayErrorResponse {
pub return_msg: String,
pub return_code: GlobepayReturnCode,
pub message: String,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3310
}
|
large_file_-8080229159179927690
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/forte/transformers.rs
</path>
<file>
use cards::CardNumber;
use common_enums::enums;
use common_utils::types::FloatMajorUnit;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{PaymentsCaptureResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, CardData as _PaymentsAuthorizeRequestData,
PaymentsAuthorizeRequestData, RouterData as _,
},
};
#[derive(Debug, Serialize)]
pub struct ForteRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for ForteRouterData<T> {
fn from((amount, router_data): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Serialize)]
pub struct FortePaymentsRequest {
action: ForteAction,
authorization_amount: FloatMajorUnit,
billing_address: BillingAddress,
card: Card,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BillingAddress {
first_name: Secret<String>,
last_name: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct Card {
card_type: ForteCardType,
name_on_card: Secret<String>,
account_number: CardNumber,
expire_month: Secret<String>,
expire_year: Secret<String>,
card_verification_value: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ForteCardType {
Visa,
MasterCard,
Amex,
Discover,
DinersClub,
Jcb,
}
impl TryFrom<utils::CardIssuer> for ForteCardType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(issuer: utils::CardIssuer) -> Result<Self, Self::Error> {
match issuer {
utils::CardIssuer::AmericanExpress => Ok(Self::Amex),
utils::CardIssuer::Master => Ok(Self::MasterCard),
utils::CardIssuer::Discover => Ok(Self::Discover),
utils::CardIssuer::Visa => Ok(Self::Visa),
utils::CardIssuer::DinersClub => Ok(Self::DinersClub),
utils::CardIssuer::JCB => Ok(Self::Jcb),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Forte"),
)
.into()),
}
}
}
impl TryFrom<&ForteRouterData<&types::PaymentsAuthorizeRouterData>> for FortePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item_data: &ForteRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let item = item_data.router_data;
if item.request.currency != enums::Currency::USD {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Forte"),
))?
}
match item.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => {
let action = match item.request.is_auto_capture()? {
true => ForteAction::Sale,
false => ForteAction::Authorize,
};
let card_type = ForteCardType::try_from(ccard.get_card_issuer()?)?;
let address = item.get_billing_address()?;
let card = Card {
card_type,
name_on_card: item
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string())),
account_number: ccard.card_number.clone(),
expire_month: ccard.card_exp_month.clone(),
expire_year: ccard.card_exp_year.clone(),
card_verification_value: ccard.card_cvc.clone(),
};
let first_name = address.get_first_name()?;
let billing_address = BillingAddress {
first_name: first_name.clone(),
last_name: address.get_last_name().unwrap_or(first_name).clone(),
};
let authorization_amount = item_data.amount;
Ok(Self {
action,
authorization_amount,
billing_address,
card,
})
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Forte"),
))?
}
}
}
}
// Auth Struct
pub struct ForteAuthType {
pub(super) api_access_id: Secret<String>,
pub(super) organization_id: Secret<String>,
pub(super) location_id: Secret<String>,
pub(super) api_secret_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for ForteAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Ok(Self {
api_access_id: api_key.to_owned(),
organization_id: Secret::new(format!("org_{}", key1.peek())),
location_id: Secret::new(format!("loc_{}", key2.peek())),
api_secret_key: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
}
// PaymentsResponse
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum FortePaymentStatus {
Complete,
Failed,
Authorized,
Ready,
Voided,
Settled,
}
impl From<FortePaymentStatus> for enums::AttemptStatus {
fn from(item: FortePaymentStatus) -> Self {
match item {
FortePaymentStatus::Complete | FortePaymentStatus::Settled => Self::Charged,
FortePaymentStatus::Failed => Self::Failure,
FortePaymentStatus::Ready => Self::Pending,
FortePaymentStatus::Authorized => Self::Authorized,
FortePaymentStatus::Voided => Self::Voided,
}
}
}
fn get_status(response_code: ForteResponseCode, action: ForteAction) -> enums::AttemptStatus {
match response_code {
ForteResponseCode::A01 => match action {
ForteAction::Authorize => enums::AttemptStatus::Authorized,
ForteAction::Sale => enums::AttemptStatus::Pending,
ForteAction::Verify | ForteAction::Capture => enums::AttemptStatus::Charged,
},
ForteResponseCode::A05 | ForteResponseCode::A06 => enums::AttemptStatus::Authorizing,
_ => enums::AttemptStatus::Failure,
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CardResponse {
pub name_on_card: Option<Secret<String>>,
pub last_4_account_number: String,
pub masked_account_number: String,
pub card_type: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub enum ForteResponseCode {
A01,
A05,
A06,
U13,
U14,
U18,
U20,
}
impl From<ForteResponseCode> for enums::AttemptStatus {
fn from(item: ForteResponseCode) -> Self {
match item {
ForteResponseCode::A01 | ForteResponseCode::A05 | ForteResponseCode::A06 => {
Self::Pending
}
_ => Self::Failure,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ResponseStatus {
pub environment: String,
pub response_type: String,
pub response_code: ForteResponseCode,
pub response_desc: String,
pub authorization_code: String,
pub avs_result: Option<String>,
pub cvv_result: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ForteAction {
Sale,
Authorize,
Verify,
Capture,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct FortePaymentsResponse {
pub transaction_id: String,
pub location_id: Secret<String>,
pub action: ForteAction,
pub authorization_amount: Option<FloatMajorUnit>,
pub authorization_code: String,
pub entered_by: String,
pub billing_address: Option<BillingAddress>,
pub card: Option<CardResponse>,
pub response: ResponseStatus,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ForteMeta {
pub auth_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, FortePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FortePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response_code = item.response.response.response_code;
let action = item.response.action;
let transaction_id = &item.response.transaction_id;
Ok(Self {
status: get_status(response_code, action),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(ForteMeta {
auth_id: item.response.authorization_code,
})),
network_txn_id: None,
connector_response_reference_id: Some(transaction_id.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
//PsyncResponse
#[derive(Debug, Deserialize, Serialize)]
pub struct FortePaymentsSyncResponse {
pub transaction_id: String,
pub organization_id: Secret<String>,
pub location_id: Secret<String>,
pub original_transaction_id: Option<String>,
pub status: FortePaymentStatus,
pub action: ForteAction,
pub authorization_code: String,
pub authorization_amount: Option<FloatMajorUnit>,
pub billing_address: Option<BillingAddress>,
pub entered_by: String,
pub received_date: String,
pub origination_date: Option<String>,
pub card: Option<CardResponse>,
pub attempt_number: i64,
pub response: ResponseStatus,
pub links: ForteLink,
pub biller_name: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ForteLink {
pub disputes: String,
pub settlements: String,
#[serde(rename = "self")]
pub self_url: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, FortePaymentsSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FortePaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction_id = &item.response.transaction_id;
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(ForteMeta {
auth_id: item.response.authorization_code,
})),
network_txn_id: None,
connector_response_reference_id: Some(transaction_id.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// Capture
#[derive(Debug, Serialize)]
pub struct ForteCaptureRequest {
action: String,
transaction_id: String,
authorization_code: String,
}
impl TryFrom<&types::PaymentsCaptureRouterData> for ForteCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
let trn_id = item.request.connector_transaction_id.clone();
let connector_auth_id: ForteMeta =
utils::to_connector_meta(item.request.connector_meta.clone())?;
let auth_code = connector_auth_id.auth_id;
Ok(Self {
action: "capture".to_string(),
transaction_id: trn_id,
authorization_code: auth_code,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CaptureResponseStatus {
pub environment: String,
pub response_type: String,
pub response_code: ForteResponseCode,
pub response_desc: String,
pub authorization_code: String,
}
// Capture Response
#[derive(Debug, Deserialize, Serialize)]
pub struct ForteCaptureResponse {
pub transaction_id: String,
pub original_transaction_id: String,
pub entered_by: String,
pub authorization_code: String,
pub response: CaptureResponseStatus,
}
impl TryFrom<PaymentsCaptureResponseRouterData<ForteCaptureResponse>>
for types::PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<ForteCaptureResponse>,
) -> Result<Self, Self::Error> {
let transaction_id = &item.response.transaction_id;
Ok(Self {
status: enums::AttemptStatus::from(item.response.response.response_code),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(ForteMeta {
auth_id: item.response.authorization_code,
})),
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
amount_captured: None,
..item.data
})
}
}
//Cancel
#[derive(Debug, Serialize)]
pub struct ForteCancelRequest {
action: String,
authorization_code: String,
}
impl TryFrom<&types::PaymentsCancelRouterData> for ForteCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let action = "void".to_string();
let connector_auth_id: ForteMeta =
utils::to_connector_meta(item.request.connector_meta.clone())?;
let authorization_code = connector_auth_id.auth_id;
Ok(Self {
action,
authorization_code,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CancelResponseStatus {
pub response_type: String,
pub response_code: ForteResponseCode,
pub response_desc: String,
pub authorization_code: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ForteCancelResponse {
pub transaction_id: String,
pub location_id: Secret<String>,
pub action: String,
pub authorization_code: String,
pub entered_by: String,
pub response: CancelResponseStatus,
}
impl<F, T> TryFrom<ResponseRouterData<F, ForteCancelResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ForteCancelResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction_id = &item.response.transaction_id;
Ok(Self {
status: enums::AttemptStatus::from(item.response.response.response_code),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(ForteMeta {
auth_id: item.response.authorization_code,
})),
network_txn_id: None,
connector_response_reference_id: Some(transaction_id.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
#[derive(Default, Debug, Serialize)]
pub struct ForteRefundRequest {
action: String,
authorization_amount: FloatMajorUnit,
original_transaction_id: String,
authorization_code: String,
}
impl<F> TryFrom<&ForteRouterData<&types::RefundsRouterData<F>>> for ForteRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item_data: &ForteRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let item = item_data.router_data;
let trn_id = item.request.connector_transaction_id.clone();
let connector_auth_id: ForteMeta =
utils::to_connector_meta(item.request.connector_metadata.clone())?;
let auth_code = connector_auth_id.auth_id;
let authorization_amount = item_data.amount;
Ok(Self {
action: "reverse".to_string(),
authorization_amount,
original_transaction_id: trn_id,
authorization_code: auth_code,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum RefundStatus {
Complete,
Ready,
Failed,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Complete => Self::Success,
RefundStatus::Ready => Self::Pending,
RefundStatus::Failed => Self::Failure,
}
}
}
impl From<ForteResponseCode> for enums::RefundStatus {
fn from(item: ForteResponseCode) -> Self {
match item {
ForteResponseCode::A01 | ForteResponseCode::A05 | ForteResponseCode::A06 => {
Self::Pending
}
_ => Self::Failure,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RefundResponse {
pub transaction_id: String,
pub original_transaction_id: String,
pub action: String,
pub authorization_amount: Option<FloatMajorUnit>,
pub authorization_code: String,
pub response: ResponseStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.response.response_code),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RefundSyncResponse {
status: RefundStatus,
transaction_id: String,
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundSyncResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ErrorResponseStatus {
pub environment: String,
pub response_type: Option<String>,
pub response_code: Option<String>,
pub response_desc: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ForteErrorResponse {
pub response: ErrorResponseStatus,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/forte/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4549
}
|
large_file_1631844734476920271
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs
</path>
<file>
use std::str::FromStr;
use cards::CardNumber;
use common_enums::enums as storage_enums;
use common_utils::{errors::CustomResult, pii, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
network_tokenization::NetworkTokenNumber,
payment_method_data::{Card, NetworkTokenData, PaymentMethodData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{RefundsData, ResponseId},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::{format_description::well_known::Rfc3339, OffsetDateTime};
use crate::{
types::ResponseRouterData,
utils::{self, CardData, NetworkTokenData as _, RouterData as OtherRouterData},
};
//TODO: Fill the struct with respective fields
pub struct PeachpaymentsRouterData<T> {
pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for PeachpaymentsRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
}
}
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for PeachPaymentsConnectorMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
const COF_DATA_TYPE: &str = "adhoc";
const COF_DATA_SOURCE: &str = "cit";
const COF_DATA_MODE: &str = "initial";
// Card Gateway API Transaction Request
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsPaymentsCardRequest {
pub charge_method: String,
pub reference_id: String,
pub ecommerce_card_payment_only_transaction_data: EcommercePaymentOnlyTransactionData,
#[serde(skip_serializing_if = "Option::is_none")]
pub pos_data: Option<serde_json::Value>,
pub send_date_time: String,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsPaymentsNTRequest {
pub payment_method: String,
pub reference_id: String,
pub ecommerce_card_payment_only_transaction_data: EcommercePaymentOnlyTransactionData,
pub send_date_time: String,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(untagged)]
pub enum PeachpaymentsPaymentsRequest {
Card(PeachpaymentsPaymentsCardRequest),
NetworkToken(PeachpaymentsPaymentsNTRequest),
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CardOnFileData {
#[serde(rename = "type")]
pub _type: String,
pub source: String,
pub mode: String,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EcommerceCardPaymentOnlyTransactionData {
pub merchant_information: MerchantInformation,
pub routing: Routing,
pub card: CardDetails,
pub amount: AmountDetails,
pub rrn: Option<String>,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EcommerceNetworkTokenPaymentOnlyTransactionData {
pub merchant_information: MerchantInformation,
pub routing: Routing,
pub network_token_data: NetworkTokenDetails,
pub amount: AmountDetails,
pub cof_data: CardOnFileData,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(untagged)]
pub enum EcommercePaymentOnlyTransactionData {
Card(EcommerceCardPaymentOnlyTransactionData),
NetworkToken(EcommerceNetworkTokenPaymentOnlyTransactionData),
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MerchantInformation {
pub client_merchant_reference_id: Secret<String>,
pub name: Secret<String>,
pub mcc: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<pii::Email>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mobile: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub city: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub postal_code: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub region_code: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub merchant_type: Option<MerchantType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub website_url: Option<url::Url>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum MerchantType {
Standard,
Sub,
Iso,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Routing {
pub route: Route,
pub mid: Secret<String>,
pub tid: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub visa_payment_facilitator_id: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub master_card_payment_facilitator_id: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sub_mid: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub amex_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum Route {
ExipayEmulator,
AbsaBase24,
NedbankPostbridge,
AbsaPostbridgeEcentric,
PostbridgeDirecttransact,
PostbridgeEfficacy,
FiservLloyds,
NfsIzwe,
AbsaHpsZambia,
EcentricEcommerce,
UnitTestEmptyConfig,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CardDetails {
pub pan: CardNumber,
#[serde(skip_serializing_if = "Option::is_none")]
pub cardholder_name: Option<Secret<String>>,
pub expiry_year: Secret<String>,
pub expiry_month: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cvv: Option<Secret<String>>,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct NetworkTokenDetails {
pub token: NetworkTokenNumber,
pub expiry_year: Secret<String>,
pub expiry_month: Secret<String>,
pub cryptogram: Option<Secret<String>>,
pub eci: Option<String>,
pub scheme: Option<CardNetworkLowercase>,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CardNetworkLowercase {
Visa,
Mastercard,
Amex,
Discover,
Jcb,
Diners,
CartesBancaires,
UnionPay,
Interac,
RuPay,
Maestro,
Star,
Pulse,
Accel,
Nyce,
}
impl From<common_enums::CardNetwork> for CardNetworkLowercase {
fn from(value: common_enums::CardNetwork) -> Self {
match value {
common_enums::CardNetwork::Visa => Self::Visa,
common_enums::CardNetwork::Mastercard => Self::Mastercard,
common_enums::CardNetwork::AmericanExpress => Self::Amex,
common_enums::CardNetwork::Discover => Self::Discover,
common_enums::CardNetwork::JCB => Self::Jcb,
common_enums::CardNetwork::DinersClub => Self::Diners,
common_enums::CardNetwork::CartesBancaires => Self::CartesBancaires,
common_enums::CardNetwork::UnionPay => Self::UnionPay,
common_enums::CardNetwork::Interac => Self::Interac,
common_enums::CardNetwork::RuPay => Self::RuPay,
common_enums::CardNetwork::Maestro => Self::Maestro,
common_enums::CardNetwork::Star => Self::Star,
common_enums::CardNetwork::Pulse => Self::Pulse,
common_enums::CardNetwork::Accel => Self::Accel,
common_enums::CardNetwork::Nyce => Self::Nyce,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmountDetails {
pub amount: MinorUnit,
pub currency_code: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub display_amount: Option<String>,
}
// Confirm Transaction Request (for capture)
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsConfirmRequest {
pub ecommerce_card_payment_only_confirmation_data: EcommerceCardPaymentOnlyConfirmationData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsRefundRequest {
pub reference_id: String,
pub ecommerce_card_payment_only_transaction_data: PeachpaymentsRefundTransactionData,
#[serde(skip_serializing_if = "Option::is_none")]
pub pos_data: Option<PosData>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PosData {
pub referral: String,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsRefundTransactionData {
pub amount: AmountDetails,
}
impl TryFrom<&RefundsRouterData<Execute>> for PeachpaymentsRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundsRouterData<Execute>) -> Result<Self, Self::Error> {
let amount = AmountDetails {
amount: item.request.minor_refund_amount,
currency_code: item.request.currency.to_string(),
display_amount: None,
};
let ecommerce_card_payment_only_transaction_data =
PeachpaymentsRefundTransactionData { amount };
Ok(Self {
reference_id: item.request.refund_id.clone(),
ecommerce_card_payment_only_transaction_data,
pos_data: None,
})
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct EcommerceCardPaymentOnlyConfirmationData {
pub amount: AmountDetails,
}
// Void Transaction Request
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsVoidRequest {
pub payment_method: PaymentMethod,
pub send_date_time: String,
pub failure_reason: FailureReason,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum PaymentMethod {
EcommerceCardPaymentOnly,
}
impl TryFrom<&PeachpaymentsRouterData<&PaymentsCaptureRouterData>> for PeachpaymentsConfirmRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PeachpaymentsRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let amount_in_cents = item.amount;
let amount = AmountDetails {
amount: amount_in_cents,
currency_code: item.router_data.request.currency.to_string(),
display_amount: None,
};
let confirmation_data = EcommerceCardPaymentOnlyConfirmationData { amount };
Ok(Self {
ecommerce_card_payment_only_confirmation_data: confirmation_data,
})
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum FailureReason {
UnableToSend,
#[default]
Timeout,
SecurityError,
IssuerUnavailable,
TooLateResponse,
Malfunction,
UnableToComplete,
OnlineDeclined,
SuspectedFraud,
CardDeclined,
Partial,
OfflineDeclined,
CustomerCancel,
}
impl FromStr for FailureReason {
type Err = error_stack::Report<errors::ConnectorError>;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value.to_lowercase().as_str() {
"unable_to_send" => Ok(Self::UnableToSend),
"timeout" => Ok(Self::Timeout),
"security_error" => Ok(Self::SecurityError),
"issuer_unavailable" => Ok(Self::IssuerUnavailable),
"too_late_response" => Ok(Self::TooLateResponse),
"malfunction" => Ok(Self::Malfunction),
"unable_to_complete" => Ok(Self::UnableToComplete),
"online_declined" => Ok(Self::OnlineDeclined),
"suspected_fraud" => Ok(Self::SuspectedFraud),
"card_declined" => Ok(Self::CardDeclined),
"partial" => Ok(Self::Partial),
"offline_declined" => Ok(Self::OfflineDeclined),
"customer_cancel" => Ok(Self::CustomerCancel),
_ => Ok(Self::Timeout),
}
}
}
impl TryFrom<&PaymentsCancelRouterData> for PeachpaymentsVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let send_date_time = OffsetDateTime::now_utc()
.format(&Rfc3339)
.map_err(|_| errors::ConnectorError::ParsingFailed)?;
Ok(Self {
payment_method: PaymentMethod::EcommerceCardPaymentOnly,
send_date_time,
failure_reason: item
.request
.cancellation_reason
.as_ref()
.map(|reason| FailureReason::from_str(reason))
.transpose()?
.unwrap_or(FailureReason::Timeout),
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PeachPaymentsConnectorMetadataObject {
pub client_merchant_reference_id: Secret<String>,
pub name: Secret<String>,
pub mcc: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<pii::Email>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mobile: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub city: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub postal_code: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub region_code: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub merchant_type: Option<MerchantType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub website_url: Option<url::Url>,
pub route: Route,
pub mid: Secret<String>,
pub tid: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub visa_payment_facilitator_id: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub master_card_payment_facilitator_id: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sub_mid: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub amex_id: Option<Secret<String>>,
}
impl TryFrom<&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>>
for PeachpaymentsPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if item.router_data.is_three_ds() {
return Err(errors::ConnectorError::NotSupported {
message: "3DS flow".to_string(),
connector: "Peachpayments",
}
.into());
}
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => Self::try_from((item, req_card)),
PaymentMethodData::NetworkToken(token_data) => Self::try_from((item, token_data)),
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
impl
TryFrom<(
&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>,
NetworkTokenData,
)> for PeachpaymentsPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, token_data): (
&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>,
NetworkTokenData,
),
) -> Result<Self, Self::Error> {
let amount_in_cents = item.amount;
let connector_merchant_config =
PeachPaymentsConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?;
let merchant_information = MerchantInformation {
client_merchant_reference_id: connector_merchant_config.client_merchant_reference_id,
name: connector_merchant_config.name,
mcc: connector_merchant_config.mcc,
phone: connector_merchant_config.phone,
email: connector_merchant_config.email,
mobile: connector_merchant_config.mobile,
address: connector_merchant_config.address,
city: connector_merchant_config.city,
postal_code: connector_merchant_config.postal_code,
region_code: connector_merchant_config.region_code,
merchant_type: connector_merchant_config.merchant_type,
website_url: connector_merchant_config.website_url,
};
// Get routing configuration from metadata
let routing = Routing {
route: connector_merchant_config.route,
mid: connector_merchant_config.mid,
tid: connector_merchant_config.tid,
visa_payment_facilitator_id: connector_merchant_config.visa_payment_facilitator_id,
master_card_payment_facilitator_id: connector_merchant_config
.master_card_payment_facilitator_id,
sub_mid: connector_merchant_config.sub_mid,
amex_id: connector_merchant_config.amex_id,
};
let network_token_data = NetworkTokenDetails {
token: token_data.get_network_token(),
expiry_year: token_data.get_token_expiry_year_2_digit()?,
expiry_month: token_data.get_network_token_expiry_month(),
cryptogram: token_data.get_cryptogram(),
eci: token_data.eci.clone(),
scheme: Some(CardNetworkLowercase::from(
token_data.card_network.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "card_network",
},
)?,
)),
};
let amount = AmountDetails {
amount: amount_in_cents,
currency_code: item.router_data.request.currency.to_string(),
display_amount: None,
};
let ecommerce_data = EcommercePaymentOnlyTransactionData::NetworkToken(
EcommerceNetworkTokenPaymentOnlyTransactionData {
merchant_information,
routing,
network_token_data,
amount,
cof_data: CardOnFileData {
_type: COF_DATA_TYPE.to_string(),
source: COF_DATA_SOURCE.to_string(),
mode: COF_DATA_MODE.to_string(),
},
},
);
// Generate current timestamp for sendDateTime (ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ)
let send_date_time = OffsetDateTime::now_utc()
.format(&time::format_description::well_known::Iso8601::DEFAULT)
.map_err(|_| errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self::NetworkToken(PeachpaymentsPaymentsNTRequest {
payment_method: "ecommerce_card_payment_only".to_string(),
reference_id: item.router_data.connector_request_reference_id.clone(),
ecommerce_card_payment_only_transaction_data: ecommerce_data,
send_date_time: send_date_time.clone(),
}))
}
}
impl TryFrom<(&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>, Card)>
for PeachpaymentsPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, req_card): (&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>, Card),
) -> Result<Self, Self::Error> {
let amount_in_cents = item.amount;
let connector_merchant_config =
PeachPaymentsConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?;
let merchant_information = MerchantInformation {
client_merchant_reference_id: connector_merchant_config.client_merchant_reference_id,
name: connector_merchant_config.name,
mcc: connector_merchant_config.mcc,
phone: connector_merchant_config.phone,
email: connector_merchant_config.email,
mobile: connector_merchant_config.mobile,
address: connector_merchant_config.address,
city: connector_merchant_config.city,
postal_code: connector_merchant_config.postal_code,
region_code: connector_merchant_config.region_code,
merchant_type: connector_merchant_config.merchant_type,
website_url: connector_merchant_config.website_url,
};
// Get routing configuration from metadata
let routing = Routing {
route: connector_merchant_config.route,
mid: connector_merchant_config.mid,
tid: connector_merchant_config.tid,
visa_payment_facilitator_id: connector_merchant_config.visa_payment_facilitator_id,
master_card_payment_facilitator_id: connector_merchant_config
.master_card_payment_facilitator_id,
sub_mid: connector_merchant_config.sub_mid,
amex_id: connector_merchant_config.amex_id,
};
let card = CardDetails {
pan: req_card.card_number.clone(),
cardholder_name: req_card.card_holder_name.clone(),
expiry_year: req_card.get_card_expiry_year_2_digit()?,
expiry_month: req_card.card_exp_month.clone(),
cvv: Some(req_card.card_cvc.clone()),
};
let amount = AmountDetails {
amount: amount_in_cents,
currency_code: item.router_data.request.currency.to_string(),
display_amount: None,
};
let ecommerce_data =
EcommercePaymentOnlyTransactionData::Card(EcommerceCardPaymentOnlyTransactionData {
merchant_information,
routing,
card,
amount,
rrn: item.router_data.request.merchant_order_reference_id.clone(),
});
// Generate current timestamp for sendDateTime (ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ)
let send_date_time = OffsetDateTime::now_utc()
.format(&time::format_description::well_known::Iso8601::DEFAULT)
.map_err(|_| errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self::Card(PeachpaymentsPaymentsCardRequest {
charge_method: "ecommerce_card_payment_only".to_string(),
reference_id: item.router_data.connector_request_reference_id.clone(),
ecommerce_card_payment_only_transaction_data: ecommerce_data,
pos_data: None,
send_date_time,
}))
}
}
// Auth Struct for Card Gateway API
pub struct PeachpaymentsAuthType {
pub(crate) api_key: Secret<String>,
pub(crate) tenant_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PeachpaymentsAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
api_key: api_key.clone(),
tenant_id: key1.clone(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
// Card Gateway API Response
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum PeachpaymentsPaymentStatus {
Successful,
Pending,
Authorized,
Approved,
ApprovedConfirmed,
Declined,
Failed,
Reversed,
ThreedsRequired,
Voided,
}
impl From<PeachpaymentsPaymentStatus> for common_enums::AttemptStatus {
fn from(item: PeachpaymentsPaymentStatus) -> Self {
match item {
// PENDING means authorized but not yet captured - requires confirmation
PeachpaymentsPaymentStatus::Pending
| PeachpaymentsPaymentStatus::Authorized
| PeachpaymentsPaymentStatus::Approved => Self::Authorized,
PeachpaymentsPaymentStatus::Declined | PeachpaymentsPaymentStatus::Failed => {
Self::Failure
}
PeachpaymentsPaymentStatus::Voided | PeachpaymentsPaymentStatus::Reversed => {
Self::Voided
}
PeachpaymentsPaymentStatus::ThreedsRequired => Self::AuthenticationPending,
PeachpaymentsPaymentStatus::ApprovedConfirmed
| PeachpaymentsPaymentStatus::Successful => Self::Charged,
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum PeachpaymentsPaymentsResponse {
Response(Box<PeachpaymentsPaymentsData>),
WebhookResponse(Box<PeachpaymentsIncomingWebhook>),
}
impl From<PeachpaymentsRefundStatus> for common_enums::RefundStatus {
fn from(item: PeachpaymentsRefundStatus) -> Self {
match item {
PeachpaymentsRefundStatus::ApprovedConfirmed => Self::Success,
PeachpaymentsRefundStatus::Failed | PeachpaymentsRefundStatus::Declined => {
Self::Failure
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsPaymentsData {
pub transaction_id: String,
pub response_code: Option<ResponseCode>,
pub transaction_result: PeachpaymentsPaymentStatus,
pub ecommerce_card_payment_only_transaction_data: Option<EcommerceCardPaymentOnlyResponseData>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsRsyncResponse {
pub transaction_id: String,
pub transaction_result: PeachpaymentsRefundStatus,
pub response_code: Option<ResponseCode>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsRefundResponse {
pub transaction_id: String,
pub original_transaction_id: Option<String>,
pub reference_id: String,
pub transaction_result: PeachpaymentsRefundStatus,
pub response_code: Option<ResponseCode>,
pub refund_balance_data: Option<RefundBalanceData>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum PeachpaymentsRefundStatus {
ApprovedConfirmed,
Declined,
Failed,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundBalanceData {
pub amount: AmountDetails,
pub balance: AmountDetails,
pub refund_history: Vec<RefundHistory>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundHistory {
pub transaction_id: String,
pub reference_id: String,
pub amount: AmountDetails,
}
impl<F>
TryFrom<ResponseRouterData<F, PeachpaymentsRefundResponse, RefundsData, RefundsResponseData>>
for RouterData<F, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PeachpaymentsRefundResponse, RefundsData, RefundsResponseData>,
) -> Result<Self, Self::Error> {
let refund_status = common_enums::RefundStatus::from(item.response.transaction_result);
let response = if refund_status == storage_enums::RefundStatus::Failure {
Err(ErrorResponse {
code: get_error_code(item.response.response_code.as_ref()),
message: get_error_message(item.response.response_code.as_ref()),
reason: None,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.transaction_id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
impl
TryFrom<ResponseRouterData<RSync, PeachpaymentsRsyncResponse, RefundsData, RefundsResponseData>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
RSync,
PeachpaymentsRsyncResponse,
RefundsData,
RefundsResponseData,
>,
) -> Result<Self, Self::Error> {
let refund_status = item.response.transaction_result.into();
let response = if refund_status == storage_enums::RefundStatus::Failure {
Err(ErrorResponse {
code: get_error_code(item.response.response_code.as_ref()),
message: get_error_message(item.response.response_code.as_ref()),
reason: None,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.transaction_id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
// Confirm Transaction Response
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsConfirmResponse {
pub transaction_id: String,
pub response_code: Option<ResponseCode>,
pub transaction_result: PeachpaymentsPaymentStatus,
pub authorization_code: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum ResponseCode {
Text(String),
Structured {
value: String,
description: String,
terminal_outcome_string: Option<String>,
receipt_string: Option<String>,
},
}
impl ResponseCode {
pub fn value(&self) -> Option<&String> {
match self {
Self::Structured { value, .. } => Some(value),
_ => None,
}
}
pub fn description(&self) -> Option<&String> {
match self {
Self::Structured { description, .. } => Some(description),
_ => None,
}
}
pub fn as_text(&self) -> Option<&String> {
match self {
Self::Text(s) => Some(s),
_ => None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EcommerceCardPaymentOnlyResponseData {
pub amount: Option<AmountDetails>,
pub stan: Option<Secret<String>>,
pub rrn: Option<Secret<String>>,
pub approval_code: Option<String>,
pub merchant_advice_code: Option<String>,
pub description: Option<String>,
pub trace_id: Option<String>,
}
fn is_payment_success(value: Option<&String>) -> bool {
if let Some(val) = value {
val == "00" || val == "08" || val == "X94"
} else {
false
}
}
fn get_error_code(response_code: Option<&ResponseCode>) -> String {
response_code
.and_then(|code| code.value())
.map(|val| val.to_string())
.unwrap_or(
response_code
.and_then(|code| code.as_text())
.map(|text| text.to_string())
.unwrap_or(NO_ERROR_CODE.to_string()),
)
}
fn get_error_message(response_code: Option<&ResponseCode>) -> String {
response_code
.and_then(|code| code.description())
.map(|desc| desc.to_string())
.unwrap_or(
response_code
.and_then(|code| code.as_text())
.map(|text| text.to_string())
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
)
}
pub fn get_peachpayments_response(
response: PeachpaymentsPaymentsData,
status_code: u16,
) -> CustomResult<
(
storage_enums::AttemptStatus,
Result<PaymentsResponseData, ErrorResponse>,
),
errors::ConnectorError,
> {
let status = common_enums::AttemptStatus::from(response.transaction_result);
let payments_response = if !is_payment_success(
response
.response_code
.as_ref()
.and_then(|code| code.value()),
) {
Err(ErrorResponse {
code: get_error_code(response.response_code.as_ref()),
message: get_error_message(response.response_code.as_ref()),
reason: response
.ecommerce_card_payment_only_transaction_data
.and_then(|data| data.description),
status_code,
attempt_status: Some(status),
connector_transaction_id: Some(response.transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.transaction_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(response.transaction_id),
incremental_authorization_allowed: None,
charges: None,
})
};
Ok((status, payments_response))
}
pub fn get_webhook_response(
response: PeachpaymentsIncomingWebhook,
status_code: u16,
) -> CustomResult<
(
storage_enums::AttemptStatus,
Result<PaymentsResponseData, ErrorResponse>,
),
errors::ConnectorError,
> {
let transaction = response
.transaction
.ok_or(errors::ConnectorError::WebhookResourceObjectNotFound)?;
let status = common_enums::AttemptStatus::from(transaction.transaction_result);
let webhook_response = if !is_payment_success(
transaction
.response_code
.as_ref()
.and_then(|code| code.value()),
) {
Err(ErrorResponse {
code: get_error_code(transaction.response_code.as_ref()),
message: get_error_message(transaction.response_code.as_ref()),
reason: transaction
.ecommerce_card_payment_only_transaction_data
.and_then(|data| data.description),
status_code,
attempt_status: Some(status),
connector_transaction_id: Some(transaction.transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
transaction
.original_transaction_id
.unwrap_or(transaction.transaction_id.clone()),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(transaction.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
})
};
Ok((status, webhook_response))
}
impl<F, T> TryFrom<ResponseRouterData<F, PeachpaymentsPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PeachpaymentsPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, response) = match item.response {
PeachpaymentsPaymentsResponse::Response(response) => {
get_peachpayments_response(*response, item.http_code)?
}
PeachpaymentsPaymentsResponse::WebhookResponse(response) => {
get_webhook_response(*response, item.http_code)?
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
// TryFrom implementation for confirm response
impl<F, T> TryFrom<ResponseRouterData<F, PeachpaymentsConfirmResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PeachpaymentsConfirmResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = common_enums::AttemptStatus::from(item.response.transaction_result);
// Check if it's an error response
let response = if !is_payment_success(
item.response
.response_code
.as_ref()
.and_then(|code| code.value()),
) {
Err(ErrorResponse {
code: get_error_code(item.response.response_code.as_ref()),
message: get_error_message(item.response.response_code.as_ref()),
reason: None,
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(item.response.transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: item.response.authorization_code.map(|auth_code| {
serde_json::json!({
"authorization_code": auth_code
})
}),
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id),
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl TryFrom<&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>>
for PeachpaymentsConfirmRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let amount_in_cents = item.amount;
let amount = AmountDetails {
amount: amount_in_cents,
currency_code: item.router_data.request.currency.to_string(),
display_amount: None,
};
let confirmation_data = EcommerceCardPaymentOnlyConfirmationData { amount };
Ok(Self {
ecommerce_card_payment_only_confirmation_data: confirmation_data,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsIncomingWebhook {
pub webhook_id: String,
pub webhook_type: String,
pub reversal_failure_reason: Option<String>,
pub transaction: Option<WebhookTransaction>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct WebhookTransaction {
pub transaction_id: String,
pub original_transaction_id: Option<String>,
pub reference_id: String,
pub transaction_result: PeachpaymentsPaymentStatus,
pub error_message: Option<String>,
pub response_code: Option<ResponseCode>,
pub ecommerce_card_payment_only_transaction_data: Option<EcommerceCardPaymentOnlyResponseData>,
pub payment_method: Secret<String>,
}
// Error Response
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsErrorResponse {
pub error_ref: String,
pub message: String,
}
impl TryFrom<ErrorResponse> for PeachpaymentsErrorResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(error_response: ErrorResponse) -> Result<Self, Self::Error> {
Ok(Self {
error_ref: error_response.code,
message: error_response.message,
})
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 8794
}
|
large_file_-2860605471803424497
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/aci/aci_result_codes.rs
</path>
<file>
pub(super) const FAILURE_CODES: [&str; 502] = [
"100.370.100",
"100.370.110",
"100.370.111",
"100.380.100",
"100.380.101",
"100.380.110",
"100.380.201",
"100.380.305",
"100.380.306",
"100.380.401",
"100.380.501",
"100.395.502",
"100.396.101",
"100.400.000",
"100.400.001",
"100.400.002",
"100.400.005",
"100.400.007",
"100.400.020",
"100.400.021",
"100.400.030",
"100.400.039",
"100.400.040",
"100.400.041",
"100.400.042",
"100.400.043",
"100.400.044",
"100.400.045",
"100.400.051",
"100.400.060",
"100.400.061",
"100.400.063",
"100.400.064",
"100.400.065",
"100.400.071",
"100.400.080",
"100.400.081",
"100.400.083",
"100.400.084",
"100.400.085",
"100.400.086",
"100.400.087",
"100.400.091",
"100.400.100",
"100.400.120",
"100.400.121",
"100.400.122",
"100.400.123",
"100.400.130",
"100.400.139",
"100.400.140",
"100.400.141",
"100.400.142",
"100.400.143",
"100.400.144",
"100.400.145",
"100.400.146",
"100.400.147",
"100.400.148",
"100.400.149",
"100.400.150",
"100.400.151",
"100.400.152",
"100.400.241",
"100.400.242",
"100.400.243",
"100.400.260",
"100.400.300",
"100.400.301",
"100.400.302",
"100.400.303",
"100.400.304",
"100.400.305",
"100.400.306",
"100.400.307",
"100.400.308",
"100.400.309",
"100.400.310",
"100.400.311",
"100.400.312",
"100.400.313",
"100.400.314",
"100.400.315",
"100.400.316",
"100.400.317",
"100.400.318",
"100.400.319",
"100.400.320",
"100.400.321",
"100.400.322",
"100.400.323",
"100.400.324",
"100.400.325",
"100.400.326",
"100.400.327",
"100.400.328",
"800.400.100",
"800.400.101",
"800.400.102",
"800.400.103",
"800.400.104",
"800.400.105",
"800.400.110",
"800.400.150",
"800.400.151",
"100.380.401",
"100.390.101",
"100.390.102",
"100.390.103",
"100.390.104",
"100.390.105",
"100.390.106",
"100.390.107",
"100.390.108",
"100.390.109",
"100.390.110",
"100.390.111",
"100.390.112",
"100.390.113",
"100.390.114",
"100.390.115",
"100.390.116",
"100.390.117",
"100.390.118",
"800.400.200",
"100.100.701",
"800.200.159",
"800.200.160",
"800.200.165",
"800.200.202",
"800.200.208",
"800.200.220",
"800.300.101",
"800.300.102",
"800.300.200",
"800.300.301",
"800.300.302",
"800.300.401",
"800.300.500",
"800.300.501",
"800.310.200",
"800.310.210",
"800.310.211",
"800.110.100",
"800.120.100",
"800.120.101",
"800.120.102",
"800.120.103",
"800.120.200",
"800.120.201",
"800.120.202",
"800.120.203",
"800.120.300",
"800.120.401",
"800.130.100",
"800.140.100",
"800.140.101",
"800.140.110",
"800.140.111",
"800.140.112",
"800.140.113",
"800.150.100",
"800.160.100",
"800.160.110",
"800.160.120",
"800.160.130",
"500.100.201",
"500.100.202",
"500.100.203",
"500.100.301",
"500.100.302",
"500.100.303",
"500.100.304",
"500.100.401",
"500.100.402",
"500.100.403",
"500.200.101",
"600.200.100",
"600.200.200",
"600.200.201",
"600.200.202",
"600.200.300",
"600.200.310",
"600.200.400",
"600.200.500",
"600.200.501",
"600.200.600",
"600.200.700",
"600.200.800",
"600.200.810",
"600.300.101",
"600.300.200",
"600.300.210",
"600.300.211",
"800.121.100",
"800.121.200",
"100.150.100",
"100.150.101",
"100.150.200",
"100.150.201",
"100.150.202",
"100.150.203",
"100.150.204",
"100.150.205",
"100.150.300",
"100.350.100",
"100.350.101",
"100.350.200",
"100.350.201",
"100.350.301",
"100.350.302",
"100.350.303",
"100.350.310",
"100.350.311",
"100.350.312",
"100.350.313",
"100.350.314",
"100.350.315",
"100.350.316",
"100.350.400",
"100.350.500",
"100.350.601",
"100.350.602",
"100.250.100",
"100.250.105",
"100.250.106",
"100.250.107",
"100.250.110",
"100.250.111",
"100.250.120",
"100.250.121",
"100.250.122",
"100.250.123",
"100.250.124",
"100.250.125",
"100.250.250",
"100.360.201",
"100.360.300",
"100.360.303",
"100.360.400",
"700.100.100",
"700.100.200",
"700.100.300",
"700.100.400",
"700.100.500",
"700.100.600",
"700.100.700",
"700.100.701",
"700.100.710",
"700.300.100",
"700.300.200",
"700.300.300",
"700.300.400",
"700.300.500",
"700.300.600",
"700.300.700",
"700.300.800",
"700.400.000",
"700.400.100",
"700.400.101",
"700.400.200",
"700.400.300",
"700.400.400",
"700.400.402",
"700.400.410",
"700.400.411",
"700.400.420",
"700.400.510",
"700.400.520",
"700.400.530",
"700.400.540",
"700.400.550",
"700.400.560",
"700.400.561",
"700.400.562",
"700.400.565",
"700.400.570",
"700.400.580",
"700.400.590",
"700.400.600",
"700.400.700",
"700.450.001",
"700.500.001",
"700.500.002",
"700.500.003",
"700.500.004",
"100.300.101",
"100.300.200",
"100.300.300",
"100.300.400",
"100.300.401",
"100.300.402",
"100.300.501",
"100.300.600",
"100.300.601",
"100.300.700",
"100.300.701",
"100.370.100",
"100.370.101",
"100.370.102",
"100.370.110",
"100.370.111",
"100.370.121",
"100.370.122",
"100.370.123",
"100.370.124",
"100.370.125",
"100.370.131",
"100.370.132",
"100.500.101",
"100.500.201",
"100.500.301",
"100.500.302",
"100.500.303",
"100.500.304",
"100.600.500",
"100.900.500",
"200.100.101",
"200.100.102",
"200.100.103",
"200.100.150",
"200.100.151",
"200.100.199",
"200.100.201",
"200.100.300",
"200.100.301",
"200.100.302",
"200.100.401",
"200.100.402",
"200.100.403",
"200.100.404",
"200.100.501",
"200.100.502",
"200.100.503",
"200.100.504",
"200.100.601",
"200.100.602",
"200.100.603",
"200.200.106",
"200.300.403",
"200.300.404",
"200.300.405",
"200.300.406",
"200.300.407",
"800.900.100",
"800.900.101",
"800.900.200",
"800.900.201",
"800.900.300",
"800.900.301",
"800.900.302",
"800.900.303",
"800.900.399",
"800.900.401",
"800.900.450",
"100.800.100",
"100.800.101",
"100.800.102",
"100.800.200",
"100.800.201",
"100.800.202",
"100.800.300",
"100.800.301",
"100.800.302",
"100.800.400",
"100.800.401",
"100.800.500",
"100.800.501",
"100.700.100",
"100.700.101",
"100.700.200",
"100.700.201",
"100.700.300",
"100.700.400",
"100.700.500",
"100.700.800",
"100.700.801",
"100.700.802",
"100.700.810",
"100.900.100",
"100.900.101",
"100.900.105",
"100.900.200",
"100.900.300",
"100.900.301",
"100.900.400",
"100.900.401",
"100.900.450",
"100.900.500",
"100.100.100",
"100.100.101",
"100.100.104",
"100.100.200",
"100.100.201",
"100.100.300",
"100.100.301",
"100.100.303",
"100.100.304",
"100.100.305",
"100.100.400",
"100.100.401",
"100.100.402",
"100.100.500",
"100.100.501",
"100.100.600",
"100.100.601",
"100.100.650",
"100.100.651",
"100.100.700",
"100.100.701",
"100.200.100",
"100.200.103",
"100.200.104",
"100.200.200",
"100.210.101",
"100.210.102",
"100.211.101",
"100.211.102",
"100.211.103",
"100.211.104",
"100.211.105",
"100.211.106",
"100.212.101",
"100.212.102",
"100.212.103",
"100.550.300",
"100.550.301",
"100.550.303",
"100.550.310",
"100.550.311",
"100.550.312",
"100.550.400",
"100.550.401",
"100.550.601",
"100.550.603",
"100.550.605",
"100.550.701",
"100.550.702",
"100.380.101",
"100.380.201",
"100.380.305",
"100.380.306",
"800.100.100",
"800.100.150",
"800.100.151",
"800.100.152",
"800.100.153",
"800.100.154",
"800.100.155",
"800.100.156",
"800.100.157",
"800.100.158",
"800.100.159",
"800.100.160",
"800.100.161",
"800.100.162",
"800.100.163",
"800.100.164",
"800.100.165",
"800.100.166",
"800.100.167",
"800.100.168",
"800.100.169",
"800.100.170",
"800.100.171",
"800.100.172",
"800.100.173",
"800.100.174",
"800.100.175",
"800.100.176",
"800.100.177",
"800.100.178",
"800.100.179",
"800.100.190",
"800.100.191",
"800.100.192",
"800.100.195",
"800.100.196",
"800.100.197",
"800.100.198",
"800.100.199",
"800.100.200",
"800.100.201",
"800.100.202",
"800.100.203",
"800.100.204",
"800.100.205",
"800.100.206",
"800.100.207",
"800.100.208",
"800.100.402",
"800.100.403",
"800.100.500",
"800.100.501",
"800.700.100",
"800.700.101",
"800.700.201",
"800.700.500",
"800.800.102",
"800.800.202",
"800.800.302",
"100.390.100",
];
pub(super) const SUCCESSFUL_CODES: [&str; 16] = [
"000.000.000",
"000.000.100",
"000.100.105",
"000.100.106",
"000.100.110",
"000.100.111",
"000.100.112",
"000.300.000",
"000.300.100",
"000.300.101",
"000.300.102",
"000.300.103",
"000.310.100",
"000.310.101",
"000.310.110",
"000.600.000",
];
pub(super) const PENDING_CODES: [&str; 26] = [
"000.400.000",
"000.400.010",
"000.400.020",
"000.400.040",
"000.400.050",
"000.400.060",
"000.400.070",
"000.400.080",
"000.400.081",
"000.400.082",
"000.400.090",
"000.400.091",
"000.400.100",
"000.400.110",
"000.200.000",
"000.200.001",
"000.200.100",
"000.200.101",
"000.200.102",
"000.200.103",
"000.200.200",
"000.200.201",
"100.400.500",
"800.400.500",
"800.400.501",
"800.400.502",
];
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/aci/aci_result_codes.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 7670
}
|
large_file_-7319128191714566184
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/aci/transformers.rs
</path>
<file>
use std::str::FromStr;
use common_enums::enums;
use common_utils::{id_type, pii::Email, request::Method, types::StringMajorUnit};
use error_stack::report;
use hyperswitch_domain_models::{
network_tokenization::NetworkTokenNumber,
payment_method_data::{
BankRedirectData, Card, NetworkTokenData, PayLaterData, PaymentMethodData, WalletData,
},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::SetupMandate,
router_request_types::{
PaymentsAuthorizeData, PaymentsCancelData, PaymentsSyncData, ResponseId,
SetupMandateRequestData,
},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use super::aci_result_codes::{FAILURE_CODES, PENDING_CODES, SUCCESSFUL_CODES};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, CardData, NetworkTokenData as NetworkTokenDataTrait, PaymentsAuthorizeRequestData,
PhoneDetailsData, RouterData as _,
},
};
type Error = error_stack::Report<errors::ConnectorError>;
trait GetCaptureMethod {
fn get_capture_method(&self) -> Option<enums::CaptureMethod>;
}
impl GetCaptureMethod for PaymentsAuthorizeData {
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
self.capture_method
}
}
impl GetCaptureMethod for PaymentsSyncData {
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
self.capture_method
}
}
impl GetCaptureMethod for PaymentsCancelData {
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
None
}
}
#[derive(Debug, Serialize)]
pub struct AciRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for AciRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub struct AciAuthType {
pub api_key: Secret<String>,
pub entity_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AciAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = item {
Ok(Self {
api_key: api_key.to_owned(),
entity_id: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum AciRecurringType {
Initial,
Repeated,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciPaymentsRequest {
#[serde(flatten)]
pub txn_details: TransactionDetails,
#[serde(flatten)]
pub payment_method: PaymentDetails,
#[serde(flatten)]
pub instruction: Option<Instruction>,
pub shopper_result_url: Option<String>,
#[serde(rename = "customParameters[3DS2_enrolled]")]
pub three_ds_two_enrolled: Option<bool>,
pub recurring_type: Option<AciRecurringType>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionDetails {
pub entity_id: Secret<String>,
pub amount: StringMajorUnit,
pub currency: String,
pub payment_type: AciPaymentType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciCancelRequest {
pub entity_id: Secret<String>,
pub payment_type: AciPaymentType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciMandateRequest {
pub entity_id: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_brand: Option<PaymentBrand>,
#[serde(flatten)]
pub payment_details: PaymentDetails,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciMandateResponse {
pub id: String,
pub result: ResultCode,
pub build_number: String,
pub timestamp: String,
}
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum PaymentDetails {
#[serde(rename = "card")]
AciCard(Box<CardDetails>),
BankRedirect(Box<BankRedirectionPMData>),
Wallet(Box<WalletPMData>),
Klarna,
Mandate,
AciNetworkToken(Box<AciNetworkTokenData>),
}
impl TryFrom<(&WalletData, &PaymentsAuthorizeRouterData)> for PaymentDetails {
type Error = Error;
fn try_from(value: (&WalletData, &PaymentsAuthorizeRouterData)) -> Result<Self, Self::Error> {
let (wallet_data, item) = value;
let payment_data = match wallet_data {
WalletData::MbWayRedirect(_) => {
let phone_details = item.get_billing_phone()?;
Self::Wallet(Box::new(WalletPMData {
payment_brand: PaymentBrand::Mbway,
account_id: Some(phone_details.get_number_with_hash_country_code()?),
}))
}
WalletData::AliPayRedirect { .. } => Self::Wallet(Box::new(WalletPMData {
payment_brand: PaymentBrand::AliPay,
account_id: None,
})),
WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect { .. }
| WalletData::GooglePay(_)
| WalletData::BluecodeRedirect {}
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect { .. }
| WalletData::VippsRedirect { .. }
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::AliPayQr(_)
| WalletData::ApplePayRedirect(_)
| WalletData::GooglePayRedirect(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
"Payment method".to_string(),
))?,
};
Ok(payment_data)
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
&BankRedirectData,
)> for PaymentDetails
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
&BankRedirectData,
),
) -> Result<Self, Self::Error> {
let (item, bank_redirect_data) = value;
let payment_data = match bank_redirect_data {
BankRedirectData::Eps { .. } => Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Eps,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
})),
BankRedirectData::Eft { .. } => Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Eft,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
})),
BankRedirectData::Giropay {
bank_account_bic,
bank_account_iban,
..
} => Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Giropay,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: bank_account_bic.clone(),
bank_account_iban: bank_account_iban.clone(),
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
})),
BankRedirectData::Ideal { bank_name, .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Ideal,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: Some(bank_name.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "ideal.bank_name",
},
)?),
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
}))
}
BankRedirectData::Sofort { .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Sofortueberweisung,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
}))
}
BankRedirectData::Przelewy24 { .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Przelewy,
bank_account_country: None,
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: Some(item.router_data.get_billing_email()?),
}))
}
BankRedirectData::Interac { .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::InteracOnline,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: Some(item.router_data.get_billing_email()?),
}))
}
BankRedirectData::Trustly { .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Trustly,
bank_account_country: None,
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: Some(item.router_data.get_billing_country()?),
merchant_customer_id: Some(Secret::new(item.router_data.get_customer_id()?)),
merchant_transaction_id: Some(Secret::new(
item.router_data.connector_request_reference_id.clone(),
)),
customer_email: None,
}))
}
BankRedirectData::Bizum { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::BancontactCard { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {}
| BankRedirectData::OpenBankingUk { .. } => Err(
errors::ConnectorError::NotImplemented("Payment method".to_string()),
)?,
};
Ok(payment_data)
}
}
fn get_aci_payment_brand(
card_network: Option<common_enums::CardNetwork>,
is_network_token_flow: bool,
) -> Result<PaymentBrand, Error> {
match card_network {
Some(common_enums::CardNetwork::Visa) => Ok(PaymentBrand::Visa),
Some(common_enums::CardNetwork::Mastercard) => Ok(PaymentBrand::Mastercard),
Some(common_enums::CardNetwork::AmericanExpress) => Ok(PaymentBrand::AmericanExpress),
Some(common_enums::CardNetwork::JCB) => Ok(PaymentBrand::Jcb),
Some(common_enums::CardNetwork::DinersClub) => Ok(PaymentBrand::DinersClub),
Some(common_enums::CardNetwork::Discover) => Ok(PaymentBrand::Discover),
Some(common_enums::CardNetwork::UnionPay) => Ok(PaymentBrand::UnionPay),
Some(common_enums::CardNetwork::Maestro) => Ok(PaymentBrand::Maestro),
Some(unsupported_network) => Err(errors::ConnectorError::NotSupported {
message: format!("Card network {unsupported_network} is not supported by ACI"),
connector: "ACI",
})?,
None => {
if is_network_token_flow {
Ok(PaymentBrand::Visa)
} else {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "card.card_network",
}
.into())
}
}
}
}
impl TryFrom<(Card, Option<Secret<String>>)> for PaymentDetails {
type Error = Error;
fn try_from(
(card_data, card_holder_name): (Card, Option<Secret<String>>),
) -> Result<Self, Self::Error> {
let card_expiry_year = card_data.get_expiry_year_4_digit();
let payment_brand = get_aci_payment_brand(card_data.card_network, false).ok();
Ok(Self::AciCard(Box::new(CardDetails {
card_number: card_data.card_number,
card_holder: card_holder_name.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "card_holder_name",
})?,
card_expiry_month: card_data.card_exp_month.clone(),
card_expiry_year,
card_cvv: card_data.card_cvc,
payment_brand,
})))
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
&NetworkTokenData,
)> for PaymentDetails
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
&NetworkTokenData,
),
) -> Result<Self, Self::Error> {
let (_item, network_token_data) = value;
let token_number = network_token_data.get_network_token();
let payment_brand = get_aci_payment_brand(network_token_data.card_network.clone(), true)?;
let aci_network_token_data = AciNetworkTokenData {
token_type: AciTokenAccountType::Network,
token_number,
token_expiry_month: network_token_data.get_network_token_expiry_month(),
token_expiry_year: network_token_data.get_expiry_year_4_digit(),
token_cryptogram: Some(
network_token_data
.get_cryptogram()
.clone()
.unwrap_or_default(),
),
payment_brand,
};
Ok(Self::AciNetworkToken(Box::new(aci_network_token_data)))
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum AciTokenAccountType {
Network,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciNetworkTokenData {
#[serde(rename = "tokenAccount.type")]
pub token_type: AciTokenAccountType,
#[serde(rename = "tokenAccount.number")]
pub token_number: NetworkTokenNumber,
#[serde(rename = "tokenAccount.expiryMonth")]
pub token_expiry_month: Secret<String>,
#[serde(rename = "tokenAccount.expiryYear")]
pub token_expiry_year: Secret<String>,
#[serde(rename = "tokenAccount.cryptogram")]
pub token_cryptogram: Option<Secret<String>>,
#[serde(rename = "paymentBrand")]
pub payment_brand: PaymentBrand,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankRedirectionPMData {
payment_brand: PaymentBrand,
#[serde(rename = "bankAccount.country")]
bank_account_country: Option<api_models::enums::CountryAlpha2>,
#[serde(rename = "bankAccount.bankName")]
bank_account_bank_name: Option<common_enums::BankNames>,
#[serde(rename = "bankAccount.bic")]
bank_account_bic: Option<Secret<String>>,
#[serde(rename = "bankAccount.iban")]
bank_account_iban: Option<Secret<String>>,
#[serde(rename = "billing.country")]
billing_country: Option<api_models::enums::CountryAlpha2>,
#[serde(rename = "customer.email")]
customer_email: Option<Email>,
#[serde(rename = "customer.merchantCustomerId")]
merchant_customer_id: Option<Secret<id_type::CustomerId>>,
merchant_transaction_id: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletPMData {
payment_brand: PaymentBrand,
#[serde(rename = "virtualAccount.accountId")]
account_id: Option<Secret<String>>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentBrand {
Eps,
Eft,
Ideal,
Giropay,
Sofortueberweisung,
InteracOnline,
Przelewy,
Trustly,
Mbway,
#[serde(rename = "ALIPAY")]
AliPay,
// Card network brands
#[serde(rename = "VISA")]
Visa,
#[serde(rename = "MASTER")]
Mastercard,
#[serde(rename = "AMEX")]
AmericanExpress,
#[serde(rename = "JCB")]
Jcb,
#[serde(rename = "DINERS")]
DinersClub,
#[serde(rename = "DISCOVER")]
Discover,
#[serde(rename = "UNIONPAY")]
UnionPay,
#[serde(rename = "MAESTRO")]
Maestro,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
pub struct CardDetails {
#[serde(rename = "card.number")]
pub card_number: cards::CardNumber,
#[serde(rename = "card.holder")]
pub card_holder: Secret<String>,
#[serde(rename = "card.expiryMonth")]
pub card_expiry_month: Secret<String>,
#[serde(rename = "card.expiryYear")]
pub card_expiry_year: Secret<String>,
#[serde(rename = "card.cvv")]
pub card_cvv: Secret<String>,
#[serde(rename = "paymentBrand")]
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_brand: Option<PaymentBrand>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum InstructionMode {
Initial,
Repeated,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum InstructionType {
Unscheduled,
}
#[derive(Debug, Clone, Serialize)]
pub enum InstructionSource {
#[serde(rename = "CIT")]
CardholderInitiatedTransaction,
#[serde(rename = "MIT")]
MerchantInitiatedTransaction,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Instruction {
#[serde(rename = "standingInstruction.mode")]
mode: InstructionMode,
#[serde(rename = "standingInstruction.type")]
transaction_type: InstructionType,
#[serde(rename = "standingInstruction.source")]
source: InstructionSource,
create_registration: Option<bool>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
pub struct BankDetails {
#[serde(rename = "bankAccount.holder")]
pub account_holder: Secret<String>,
}
#[allow(dead_code)]
#[derive(Debug, Default, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub enum AciPaymentType {
#[serde(rename = "PA")]
Preauthorization,
#[default]
#[serde(rename = "DB")]
Debit,
#[serde(rename = "CD")]
Credit,
#[serde(rename = "CP")]
Capture,
#[serde(rename = "RV")]
Reversal,
#[serde(rename = "RF")]
Refund,
}
impl TryFrom<&AciRouterData<&PaymentsAuthorizeRouterData>> for AciPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AciRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ref card_data) => Self::try_from((item, card_data)),
PaymentMethodData::NetworkToken(ref network_token_data) => {
Self::try_from((item, network_token_data))
}
PaymentMethodData::Wallet(ref wallet_data) => Self::try_from((item, wallet_data)),
PaymentMethodData::PayLater(ref pay_later_data) => {
Self::try_from((item, pay_later_data))
}
PaymentMethodData::BankRedirect(ref bank_redirect_data) => {
Self::try_from((item, bank_redirect_data))
}
PaymentMethodData::MandatePayment => {
let mandate_id = item.router_data.request.mandate_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "mandate_id",
},
)?;
Self::try_from((item, mandate_id))
}
PaymentMethodData::Crypto(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Aci"),
))?
}
}
}
}
impl TryFrom<(&AciRouterData<&PaymentsAuthorizeRouterData>, &WalletData)> for AciPaymentsRequest {
type Error = Error;
fn try_from(
value: (&AciRouterData<&PaymentsAuthorizeRouterData>, &WalletData),
) -> Result<Self, Self::Error> {
let (item, wallet_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((wallet_data, item.router_data))?;
Ok(Self {
txn_details,
payment_method,
instruction: None,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
&BankRedirectData,
)> for AciPaymentsRequest
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
&BankRedirectData,
),
) -> Result<Self, Self::Error> {
let (item, bank_redirect_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((item, bank_redirect_data))?;
Ok(Self {
txn_details,
payment_method,
instruction: None,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl TryFrom<(&AciRouterData<&PaymentsAuthorizeRouterData>, &PayLaterData)> for AciPaymentsRequest {
type Error = Error;
fn try_from(
value: (&AciRouterData<&PaymentsAuthorizeRouterData>, &PayLaterData),
) -> Result<Self, Self::Error> {
let (item, _pay_later_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::Klarna;
Ok(Self {
txn_details,
payment_method,
instruction: None,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl TryFrom<(&AciRouterData<&PaymentsAuthorizeRouterData>, &Card)> for AciPaymentsRequest {
type Error = Error;
fn try_from(
value: (&AciRouterData<&PaymentsAuthorizeRouterData>, &Card),
) -> Result<Self, Self::Error> {
let (item, card_data) = value;
let card_holder_name = item.router_data.get_optional_billing_full_name();
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((card_data.clone(), card_holder_name))?;
let instruction = get_instruction_details(item);
let recurring_type = get_recurring_type(item);
let three_ds_two_enrolled = item
.router_data
.is_three_ds()
.then_some(item.router_data.request.enrolled_for_3ds);
Ok(Self {
txn_details,
payment_method,
instruction,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled,
recurring_type,
})
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
&NetworkTokenData,
)> for AciPaymentsRequest
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
&NetworkTokenData,
),
) -> Result<Self, Self::Error> {
let (item, network_token_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((item, network_token_data))?;
let instruction = get_instruction_details(item);
Ok(Self {
txn_details,
payment_method,
instruction,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
api_models::payments::MandateIds,
)> for AciPaymentsRequest
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
api_models::payments::MandateIds,
),
) -> Result<Self, Self::Error> {
let (item, _mandate_data) = value;
let instruction = get_instruction_details(item);
let txn_details = get_transaction_details(item)?;
let recurring_type = get_recurring_type(item);
Ok(Self {
txn_details,
payment_method: PaymentDetails::Mandate,
instruction,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type,
})
}
}
fn get_transaction_details(
item: &AciRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<TransactionDetails, error_stack::Report<errors::ConnectorError>> {
let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?;
let payment_type = if item.router_data.request.is_auto_capture()? {
AciPaymentType::Debit
} else {
AciPaymentType::Preauthorization
};
Ok(TransactionDetails {
entity_id: auth.entity_id,
amount: item.amount.to_owned(),
currency: item.router_data.request.currency.to_string(),
payment_type,
})
}
fn get_instruction_details(
item: &AciRouterData<&PaymentsAuthorizeRouterData>,
) -> Option<Instruction> {
if item.router_data.request.customer_acceptance.is_some()
&& item.router_data.request.setup_future_usage == Some(enums::FutureUsage::OffSession)
{
return Some(Instruction {
mode: InstructionMode::Initial,
transaction_type: InstructionType::Unscheduled,
source: InstructionSource::CardholderInitiatedTransaction,
create_registration: Some(true),
});
} else if item.router_data.request.mandate_id.is_some() {
return Some(Instruction {
mode: InstructionMode::Repeated,
transaction_type: InstructionType::Unscheduled,
source: InstructionSource::MerchantInitiatedTransaction,
create_registration: None,
});
}
None
}
fn get_recurring_type(
item: &AciRouterData<&PaymentsAuthorizeRouterData>,
) -> Option<AciRecurringType> {
if item.router_data.request.mandate_id.is_some() {
Some(AciRecurringType::Repeated)
} else if item.router_data.request.customer_acceptance.is_some()
&& item.router_data.request.setup_future_usage == Some(enums::FutureUsage::OffSession)
{
Some(AciRecurringType::Initial)
} else {
None
}
}
impl TryFrom<&PaymentsCancelRouterData> for AciCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let auth = AciAuthType::try_from(&item.connector_auth_type)?;
let aci_payment_request = Self {
entity_id: auth.entity_id,
payment_type: AciPaymentType::Reversal,
};
Ok(aci_payment_request)
}
}
impl TryFrom<&RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>>
for AciMandateRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let auth = AciAuthType::try_from(&item.connector_auth_type)?;
let (payment_brand, payment_details) = match &item.request.payment_method_data {
PaymentMethodData::Card(card_data) => {
let brand = get_aci_payment_brand(card_data.card_network.clone(), false).ok();
match brand.as_ref() {
Some(PaymentBrand::Visa)
| Some(PaymentBrand::Mastercard)
| Some(PaymentBrand::AmericanExpress) => (),
Some(_) => {
return Err(errors::ConnectorError::NotSupported {
message: "Payment method not supported for mandate setup".to_string(),
connector: "ACI",
}
.into());
}
None => (),
};
let details = PaymentDetails::AciCard(Box::new(CardDetails {
card_number: card_data.card_number.clone(),
card_expiry_month: card_data.card_exp_month.clone(),
card_expiry_year: card_data.get_expiry_year_4_digit(),
card_cvv: card_data.card_cvc.clone(),
card_holder: card_data.card_holder_name.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "card_holder_name",
},
)?,
payment_brand: brand.clone(),
}));
(brand, details)
}
_ => {
return Err(errors::ConnectorError::NotSupported {
message: "Payment method not supported for mandate setup".to_string(),
connector: "ACI",
}
.into());
}
};
Ok(Self {
entity_id: auth.entity_id,
payment_brand,
payment_details,
})
}
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AciPaymentStatus {
Succeeded,
Failed,
#[default]
Pending,
RedirectShopper,
}
fn map_aci_attempt_status(item: AciPaymentStatus, auto_capture: bool) -> enums::AttemptStatus {
match item {
AciPaymentStatus::Succeeded => {
if auto_capture {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
AciPaymentStatus::Failed => enums::AttemptStatus::Failure,
AciPaymentStatus::Pending => enums::AttemptStatus::Authorizing,
AciPaymentStatus::RedirectShopper => enums::AttemptStatus::AuthenticationPending,
}
}
impl FromStr for AciPaymentStatus {
type Err = error_stack::Report<errors::ConnectorError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if FAILURE_CODES.contains(&s) {
Ok(Self::Failed)
} else if PENDING_CODES.contains(&s) {
Ok(Self::Pending)
} else if SUCCESSFUL_CODES.contains(&s) {
Ok(Self::Succeeded)
} else {
Err(report!(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(s.to_owned())
)))
}
}
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciPaymentsResponse {
id: String,
registration_id: Option<Secret<String>>,
ndc: String,
timestamp: String,
build_number: String,
pub(super) result: ResultCode,
pub(super) redirect: Option<AciRedirectionData>,
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciErrorResponse {
ndc: String,
timestamp: String,
build_number: String,
pub(super) result: ResultCode,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciRedirectionData {
pub method: Option<Method>,
pub parameters: Vec<Parameters>,
pub url: Url,
pub preconditions: Option<Vec<PreconditionData>>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PreconditionData {
pub method: Option<Method>,
pub parameters: Vec<Parameters>,
pub url: Url,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
pub struct Parameters {
pub name: String,
pub value: String,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResultCode {
pub(super) code: String,
pub(super) description: String,
pub(super) parameter_errors: Option<Vec<ErrorParameters>>,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq, Serialize)]
pub struct ErrorParameters {
pub(super) name: String,
pub(super) value: Option<String>,
pub(super) message: String,
}
impl<F, Req> TryFrom<ResponseRouterData<F, AciPaymentsResponse, Req, PaymentsResponseData>>
for RouterData<F, Req, PaymentsResponseData>
where
Req: GetCaptureMethod,
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AciPaymentsResponse, Req, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirection_data = item.response.redirect.map(|data| {
let mut form_fields = std::collections::HashMap::<_, _>::from_iter(
data.parameters
.iter()
.map(|parameter| (parameter.name.clone(), parameter.value.clone())),
);
if let Some(preconditions) = data.preconditions {
if let Some(first_precondition) = preconditions.first() {
for param in &first_precondition.parameters {
form_fields.insert(param.name.clone(), param.value.clone());
}
}
}
// If method is Get, parameters are appended to URL
// If method is post, we http Post the method to URL
RedirectForm::Form {
endpoint: data.url.to_string(),
// Handles method for Bank redirects currently.
// 3DS response have method within preconditions. That would require replacing below line with a function.
method: data.method.unwrap_or(Method::Post),
form_fields,
}
});
let mandate_reference = item
.response
.registration_id
.clone()
.map(|id| MandateReference {
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
let auto_capture = matches!(
item.data.request.get_capture_method(),
Some(enums::CaptureMethod::Automatic) | None
);
let status = if redirection_data.is_some() {
map_aci_attempt_status(AciPaymentStatus::RedirectShopper, auto_capture)
} else {
map_aci_attempt_status(
AciPaymentStatus::from_str(&item.response.result.code)?,
auto_capture,
)
};
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item.response.result.code.clone(),
message: item.response.result.description.clone(),
reason: Some(item.response.result.description),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(item.response.id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciCaptureRequest {
#[serde(flatten)]
pub txn_details: TransactionDetails,
}
impl TryFrom<&AciRouterData<&PaymentsCaptureRouterData>> for AciCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AciRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
txn_details: TransactionDetails {
entity_id: auth.entity_id,
amount: item.amount.to_owned(),
currency: item.router_data.request.currency.to_string(),
payment_type: AciPaymentType::Capture,
},
})
}
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciCaptureResponse {
id: String,
referenced_id: String,
payment_type: AciPaymentType,
amount: StringMajorUnit,
currency: String,
descriptor: String,
result: AciCaptureResult,
result_details: Option<AciCaptureResultDetails>,
build_number: String,
timestamp: String,
ndc: Secret<String>,
source: Option<Secret<String>>,
payment_method: Option<String>,
short_id: Option<String>,
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciCaptureResult {
code: String,
description: String,
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct AciCaptureResultDetails {
extended_description: String,
#[serde(rename = "clearingInstituteName")]
clearing_institute_name: Option<String>,
connector_tx_i_d1: Option<String>,
connector_tx_i_d3: Option<String>,
connector_tx_i_d2: Option<String>,
acquirer_response: Option<String>,
}
#[derive(Debug, Default, Clone, Deserialize)]
pub enum AciStatus {
Succeeded,
Failed,
#[default]
Pending,
}
impl FromStr for AciStatus {
type Err = error_stack::Report<errors::ConnectorError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if FAILURE_CODES.contains(&s) {
Ok(Self::Failed)
} else if PENDING_CODES.contains(&s) {
Ok(Self::Pending)
} else if SUCCESSFUL_CODES.contains(&s) {
Ok(Self::Succeeded)
} else {
Err(report!(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(s.to_owned())
)))
}
}
}
fn map_aci_capture_status(item: AciStatus) -> enums::AttemptStatus {
match item {
AciStatus::Succeeded => enums::AttemptStatus::Charged,
AciStatus::Failed => enums::AttemptStatus::Failure,
AciStatus::Pending => enums::AttemptStatus::Pending,
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AciCaptureResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AciCaptureResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = map_aci_capture_status(AciStatus::from_str(&item.response.result.code)?);
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item.response.result.code.clone(),
message: item.response.result.description.clone(),
reason: Some(item.response.result.description),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(item.response.id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.referenced_id.clone()),
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
reference_id: Some(item.response.referenced_id),
..item.data
})
}
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciVoidResponse {
id: String,
referenced_id: String,
payment_type: AciPaymentType,
amount: StringMajorUnit,
currency: String,
descriptor: String,
result: AciCaptureResult,
result_details: Option<AciCaptureResultDetails>,
build_number: String,
timestamp: String,
ndc: Secret<String>,
}
fn map_aci_void_status(item: AciStatus) -> enums::AttemptStatus {
match item {
AciStatus::Succeeded => enums::AttemptStatus::Voided,
AciStatus::Failed => enums::AttemptStatus::VoidFailed,
AciStatus::Pending => enums::AttemptStatus::VoidInitiated,
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AciVoidResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AciVoidResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = map_aci_void_status(AciStatus::from_str(&item.response.result.code)?);
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item.response.result.code.clone(),
message: item.response.result.description.clone(),
reason: Some(item.response.result.description),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(item.response.id.clone()),
..Default::default()
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.referenced_id.clone()),
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
reference_id: Some(item.response.referenced_id),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciRefundRequest {
pub amount: StringMajorUnit,
pub currency: String,
pub payment_type: AciPaymentType,
pub entity_id: Secret<String>,
}
impl<F> TryFrom<&AciRouterData<&RefundsRouterData<F>>> for AciRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AciRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let amount = item.amount.to_owned();
let currency = item.router_data.request.currency;
let payment_type = AciPaymentType::Refund;
let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
amount,
currency: currency.to_string(),
payment_type,
entity_id: auth.entity_id,
})
}
}
#[derive(Debug, Default, Deserialize, Clone)]
pub enum AciRefundStatus {
Succeeded,
Failed,
#[default]
Pending,
}
impl FromStr for AciRefundStatus {
type Err = error_stack::Report<errors::ConnectorError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if FAILURE_CODES.contains(&s) {
Ok(Self::Failed)
} else if PENDING_CODES.contains(&s) {
Ok(Self::Pending)
} else if SUCCESSFUL_CODES.contains(&s) {
Ok(Self::Succeeded)
} else {
Err(report!(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(s.to_owned())
)))
}
}
}
impl From<AciRefundStatus> for enums::RefundStatus {
fn from(item: AciRefundStatus) -> Self {
match item {
AciRefundStatus::Succeeded => Self::Success,
AciRefundStatus::Failed => Self::Failure,
AciRefundStatus::Pending => Self::Pending,
}
}
}
#[allow(dead_code)]
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciRefundResponse {
id: String,
ndc: String,
timestamp: String,
build_number: String,
pub(super) result: ResultCode,
}
impl<F> TryFrom<RefundsResponseRouterData<F, AciRefundResponse>> for RefundsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<F, AciRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status =
enums::RefundStatus::from(AciRefundStatus::from_str(&item.response.result.code)?);
let response = if refund_status == enums::RefundStatus::Failure {
Err(ErrorResponse {
code: item.response.result.code.clone(),
message: item.response.result.description.clone(),
reason: Some(item.response.result.description),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
impl
TryFrom<
ResponseRouterData<
SetupMandate,
AciMandateResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
> for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
SetupMandate,
AciMandateResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let mandate_reference = Some(MandateReference {
connector_mandate_id: Some(item.response.id.clone()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
let status = if SUCCESSFUL_CODES.contains(&item.response.result.code.as_str()) {
enums::AttemptStatus::Charged
} else if FAILURE_CODES.contains(&item.response.result.code.as_str()) {
enums::AttemptStatus::Failure
} else {
enums::AttemptStatus::Pending
};
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item.response.result.code.clone(),
message: item.response.result.description.clone(),
reason: Some(item.response.result.description),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(item.response.id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum AciWebhookEventType {
Payment,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum AciWebhookAction {
Created,
Updated,
Deleted,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciWebhookCardDetails {
pub bin: Option<String>,
#[serde(rename = "last4Digits")]
pub last4_digits: Option<String>,
pub holder: Option<String>,
pub expiry_month: Option<Secret<String>>,
pub expiry_year: Option<Secret<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciWebhookCustomerDetails {
#[serde(rename = "givenName")]
pub given_name: Option<Secret<String>>,
pub surname: Option<Secret<String>>,
#[serde(rename = "merchantCustomerId")]
pub merchant_customer_id: Option<Secret<String>>,
pub sex: Option<Secret<String>>,
pub email: Option<Email>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciWebhookAuthenticationDetails {
#[serde(rename = "entityId")]
pub entity_id: Secret<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciWebhookRiskDetails {
pub score: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciPaymentWebhookPayload {
pub id: String,
pub payment_type: String,
pub payment_brand: String,
pub amount: StringMajorUnit,
pub currency: String,
pub presentation_amount: Option<StringMajorUnit>,
pub presentation_currency: Option<String>,
pub descriptor: Option<String>,
pub result: ResultCode,
pub authentication: Option<AciWebhookAuthenticationDetails>,
pub card: Option<AciWebhookCardDetails>,
pub customer: Option<AciWebhookCustomerDetails>,
#[serde(rename = "customParameters")]
pub custom_parameters: Option<serde_json::Value>,
pub risk: Option<AciWebhookRiskDetails>,
pub build_number: Option<String>,
pub timestamp: String,
pub ndc: String,
#[serde(rename = "channelName")]
pub channel_name: Option<String>,
pub source: Option<String>,
pub payment_method: Option<String>,
#[serde(rename = "shortId")]
pub short_id: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciWebhookNotification {
#[serde(rename = "type")]
pub event_type: AciWebhookEventType,
pub action: Option<AciWebhookAction>,
pub payload: serde_json::Value,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/aci/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 11833
}
|
large_file_-625167189560781633
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs
</path>
<file>
use std::collections::HashMap;
#[cfg(feature = "payouts")]
use api_models::payouts::{BankRedirect, PayoutMethodData};
use api_models::webhooks;
use common_enums::{enums, Currency};
use common_utils::{id_type, pii::Email, request::Method, types::FloatMajorUnit};
use hyperswitch_domain_models::{
payment_method_data::{BankRedirectData, PaymentMethodData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::PoFulfill, router_response_types::PayoutsResponseData,
types::PayoutsRouterData,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
#[cfg(feature = "payouts")]
use crate::types::PayoutsResponseRouterData;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, PaymentsAuthorizeRequestData, RouterData as _},
};
pub struct LoonioRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for LoonioRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
// Auth Struct
pub struct LoonioAuthType {
pub(super) merchant_id: Secret<String>,
pub(super) merchant_token: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for LoonioAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
merchant_id: api_key.to_owned(),
merchant_token: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize)]
pub struct LoonioPaymentRequest {
pub currency_code: Currency,
pub customer_profile: LoonioCustomerProfile,
pub amount: FloatMajorUnit,
pub customer_id: id_type::CustomerId,
pub transaction_id: String,
pub payment_method_type: InteracPaymentMethodType,
#[serde(skip_serializing_if = "Option::is_none")]
pub redirect_url: Option<LoonioRedirectUrl>,
#[serde(skip_serializing_if = "Option::is_none")]
pub webhook_url: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum InteracPaymentMethodType {
InteracEtransfer,
}
#[derive(Debug, Serialize)]
pub struct LoonioCustomerProfile {
pub first_name: Secret<String>,
pub last_name: Secret<String>,
pub email: Email,
}
#[derive(Debug, Serialize)]
pub struct LoonioRedirectUrl {
pub success_url: String,
pub failed_url: String,
}
impl TryFrom<&LoonioRouterData<&PaymentsAuthorizeRouterData>> for LoonioPaymentRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &LoonioRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankRedirect(BankRedirectData::Interac { .. }) => {
let transaction_id = item.router_data.connector_request_reference_id.clone();
let customer_profile = LoonioCustomerProfile {
first_name: item.router_data.get_billing_first_name()?,
last_name: item.router_data.get_billing_last_name()?,
email: item.router_data.get_billing_email()?,
};
let redirect_url = LoonioRedirectUrl {
success_url: item.router_data.request.get_router_return_url()?,
failed_url: item.router_data.request.get_router_return_url()?,
};
Ok(Self {
currency_code: item.router_data.request.currency,
customer_profile,
amount: item.amount,
customer_id: item.router_data.get_customer_id()?,
transaction_id,
payment_method_type: InteracPaymentMethodType::InteracEtransfer,
redirect_url: Some(redirect_url),
webhook_url: Some(item.router_data.request.get_webhook_url()?),
})
}
PaymentMethodData::BankRedirect(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Loonio"),
))?,
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Loonio"),
)
.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoonioPaymentsResponse {
pub payment_form: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, LoonioPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, LoonioPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.data.connector_request_reference_id.clone(),
),
redirection_data: Box::new(Some(RedirectForm::Form {
endpoint: item.response.payment_form,
method: Method::Get,
form_fields: HashMap::new(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoonioTransactionStatus {
Created,
Prepared,
Pending,
Settled,
Available,
Abandoned,
Rejected,
Failed,
Rollback,
Returned,
Nsf,
}
impl From<LoonioTransactionStatus> for enums::AttemptStatus {
fn from(item: LoonioTransactionStatus) -> Self {
match item {
LoonioTransactionStatus::Created => Self::AuthenticationPending,
LoonioTransactionStatus::Prepared | LoonioTransactionStatus::Pending => Self::Pending,
LoonioTransactionStatus::Settled | LoonioTransactionStatus::Available => Self::Charged,
LoonioTransactionStatus::Abandoned
| LoonioTransactionStatus::Rejected
| LoonioTransactionStatus::Failed
| LoonioTransactionStatus::Returned
| LoonioTransactionStatus::Nsf => Self::Failure,
LoonioTransactionStatus::Rollback => Self::Voided,
}
}
}
// Sync Response Structures
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoonioTransactionSyncResponse {
pub transaction_id: String,
pub state: LoonioTransactionStatus,
}
#[derive(Default, Debug, Serialize)]
pub struct LoonioRefundRequest {
pub amount: FloatMajorUnit,
}
impl<F> TryFrom<&LoonioRouterData<&RefundsRouterData<F>>> for LoonioRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &LoonioRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, LoonioPaymentResponseData, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, LoonioPaymentResponseData, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
LoonioPaymentResponseData::Sync(sync_response) => Ok(Self {
status: enums::AttemptStatus::from(sync_response.state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(sync_response.transaction_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
LoonioPaymentResponseData::Webhook(webhook_body) => {
let payment_status = enums::AttemptStatus::from(&webhook_body.event_code);
Ok(Self {
status: payment_status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
webhook_body.api_transaction_id,
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct LoonioErrorResponse {
pub status: u16,
pub error_code: Option<String>,
pub message: String,
}
// Webhook related structs
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoonioWebhookEventCode {
TransactionPrepared,
TransactionPending,
TransactionAvailable,
TransactionSettled,
TransactionFailed,
TransactionRejected,
#[serde(rename = "TRANSACTION_WAITING_STATUS_FILE")]
TransactionWaitingStatusFile,
#[serde(rename = "TRANSACTION_STATUS_FILE_RECEIVED")]
TransactionStatusFileReceived,
#[serde(rename = "TRANSACTION_STATUS_FILE_FAILED")]
TransactionStatusFileFailed,
#[serde(rename = "TRANSACTION_RETURNED")]
TransactionReturned,
#[serde(rename = "TRANSACTION_WRONG_DESTINATION")]
TransactionWrongDestination,
#[serde(rename = "TRANSACTION_NSF")]
TransactionNsf,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoonioWebhookTransactionType {
Incoming,
OutgoingVerified,
OutgoingNotVerified,
OutgoingCustomerDefined,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LoonioWebhookBody {
pub amount: FloatMajorUnit,
pub api_transaction_id: String,
pub signature: Option<String>,
pub event_code: LoonioWebhookEventCode,
pub id: i32,
#[serde(rename = "type")]
pub transaction_type: LoonioWebhookTransactionType,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum LoonioPaymentResponseData {
Sync(LoonioTransactionSyncResponse),
Webhook(LoonioWebhookBody),
}
impl From<&LoonioWebhookEventCode> for webhooks::IncomingWebhookEvent {
fn from(event_code: &LoonioWebhookEventCode) -> Self {
match event_code {
LoonioWebhookEventCode::TransactionSettled
| LoonioWebhookEventCode::TransactionAvailable => Self::PaymentIntentSuccess,
LoonioWebhookEventCode::TransactionPending
| LoonioWebhookEventCode::TransactionPrepared => Self::PaymentIntentProcessing,
LoonioWebhookEventCode::TransactionFailed
// deprecated
| LoonioWebhookEventCode::TransactionRejected
| LoonioWebhookEventCode::TransactionStatusFileFailed
| LoonioWebhookEventCode::TransactionReturned
| LoonioWebhookEventCode::TransactionWrongDestination
| LoonioWebhookEventCode::TransactionNsf => Self::PaymentIntentFailure,
_ => Self::EventNotSupported,
}
}
}
impl From<&LoonioWebhookEventCode> for enums::AttemptStatus {
fn from(event_code: &LoonioWebhookEventCode) -> Self {
match event_code {
LoonioWebhookEventCode::TransactionSettled
| LoonioWebhookEventCode::TransactionAvailable => Self::Charged,
LoonioWebhookEventCode::TransactionPending
| LoonioWebhookEventCode::TransactionPrepared => Self::Pending,
LoonioWebhookEventCode::TransactionFailed
| LoonioWebhookEventCode::TransactionRejected
| LoonioWebhookEventCode::TransactionStatusFileFailed
| LoonioWebhookEventCode::TransactionReturned
| LoonioWebhookEventCode::TransactionWrongDestination
| LoonioWebhookEventCode::TransactionNsf => Self::Failure,
_ => Self::Pending,
}
}
}
// Payout Structures
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
pub struct LoonioPayoutFulfillRequest {
pub currency_code: Currency,
pub customer_profile: LoonioCustomerProfile,
pub amount: FloatMajorUnit,
pub customer_id: id_type::CustomerId,
pub transaction_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub webhook_url: Option<String>,
}
#[cfg(feature = "payouts")]
impl TryFrom<&LoonioRouterData<&PayoutsRouterData<PoFulfill>>> for LoonioPayoutFulfillRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &LoonioRouterData<&PayoutsRouterData<PoFulfill>>,
) -> Result<Self, Self::Error> {
match item.router_data.get_payout_method_data()? {
PayoutMethodData::BankRedirect(BankRedirect::Interac(interac_data)) => {
let customer_profile = LoonioCustomerProfile {
first_name: item.router_data.get_billing_first_name()?,
last_name: item.router_data.get_billing_last_name()?,
email: interac_data.email,
};
Ok(Self {
currency_code: item.router_data.request.destination_currency,
customer_profile,
amount: item.amount,
customer_id: item.router_data.get_customer_id()?,
transaction_id: item.router_data.connector_request_reference_id.clone(),
webhook_url: item.router_data.request.webhook_url.clone(),
})
}
PayoutMethodData::Card(_) | PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => {
Err(errors::ConnectorError::NotSupported {
message: "Payment Method Not Supported".to_string(),
connector: "Loonio",
})?
}
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoonioPayoutFulfillResponse {
pub id: i64,
pub api_transaction_id: String,
#[serde(rename = "type")]
pub transaction_type: String,
pub state: LoonioPayoutStatus,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoonioPayoutStatus {
Created,
Prepared,
Pending,
Settled,
Available,
Rejected,
Abandoned,
ConnectedAbandoned,
ConnectedInsufficientFunds,
Failed,
Nsf,
Returned,
Rollback,
}
#[cfg(feature = "payouts")]
impl From<LoonioPayoutStatus> for enums::PayoutStatus {
fn from(item: LoonioPayoutStatus) -> Self {
match item {
LoonioPayoutStatus::Created | LoonioPayoutStatus::Prepared => Self::Initiated,
LoonioPayoutStatus::Pending => Self::Pending,
LoonioPayoutStatus::Settled | LoonioPayoutStatus::Available => Self::Success,
LoonioPayoutStatus::Rejected
| LoonioPayoutStatus::Abandoned
| LoonioPayoutStatus::ConnectedAbandoned
| LoonioPayoutStatus::ConnectedInsufficientFunds
| LoonioPayoutStatus::Failed
| LoonioPayoutStatus::Nsf
| LoonioPayoutStatus::Returned
| LoonioPayoutStatus::Rollback => Self::Failed,
}
}
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, LoonioPayoutFulfillResponse>>
for PayoutsRouterData<F>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, LoonioPayoutFulfillResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::from(item.response.state)),
connector_payout_id: Some(item.response.api_transaction_id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoonioPayoutSyncResponse {
pub transaction_id: String,
pub state: LoonioPayoutStatus,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, LoonioPayoutSyncResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, LoonioPayoutSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::from(item.response.state)),
connector_payout_id: Some(item.response.transaction_id.to_string()),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4402
}
|
large_file_-9012272929115640916
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
</path>
<file>
use api_models::payments::{
ApplePayCombinedMetadata, ApplepayCombinedSessionTokenData, ApplepaySessionTokenData,
ApplepaySessionTokenMetadata,
};
use base64::Engine;
use common_enums::{enums, Currency};
use common_utils::{
consts::BASE64_ENGINE, ext_traits::ValueExt, pii, request::Method, types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{ser::Serializer, Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, CardData as _, PaymentsCancelRequestData, PaymentsSyncRequestData, RouterData as _,
},
};
#[derive(Debug, Serialize)]
pub struct FiservRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(FloatMajorUnit, T)> for FiservRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, router_data): (FloatMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data,
})
}
}
impl Serialize for FiservCheckoutChargesRequest {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Checkout(inner) => inner.serialize(serializer),
Self::Charges(inner) => inner.serialize(serializer),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservPaymentsRequest {
amount: Amount,
merchant_details: MerchantDetails,
#[serde(flatten)]
checkout_charges_request: FiservCheckoutChargesRequest,
}
#[derive(Debug)]
pub enum FiservCheckoutChargesRequest {
Checkout(CheckoutPaymentsRequest),
Charges(ChargesPaymentRequest),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckoutPaymentsRequest {
order: FiservOrder,
payment_method: FiservPaymentMethod,
interactions: FiservInteractions,
transaction_details: TransactionDetails,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FiservChannel {
Web,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FiservPaymentInitiator {
Merchant,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FiservCustomerConfirmation {
ReviewAndPay,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservInteractions {
channel: FiservChannel,
customer_confirmation: FiservCustomerConfirmation,
payment_initiator: FiservPaymentInitiator,
return_urls: FiservReturnUrls,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservReturnUrls {
success_url: String,
cancel_url: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservPaymentMethod {
provider: FiservWallet,
#[serde(rename = "type")]
wallet_type: FiservWalletType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservOrder {
intent: FiservIntent,
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FiservIntent {
Authorize,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ChargesPaymentRequest {
source: Source,
transaction_interaction: Option<TransactionInteraction>,
transaction_details: TransactionDetails,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FiservWallet {
ApplePay,
GooglePay,
PayPal,
}
#[derive(Debug, Serialize)]
#[serde(tag = "sourceType")]
pub enum Source {
#[serde(rename = "GooglePay")]
GooglePay(GooglePayData),
#[serde(rename = "PaymentCard")]
PaymentCard { card: CardData },
#[serde(rename = "ApplePay")]
ApplePay(ApplePayWalletDetails),
#[serde(rename = "DecryptedWallet")]
DecryptedWallet(DecryptedWalletDetails),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayWalletDetails {
pub data: Secret<String>,
pub header: ApplePayHeader,
pub signature: Secret<String>,
pub version: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub application_data: Option<Secret<String>>,
pub apple_pay_merchant_id: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayHeader {
#[serde(skip_serializing_if = "Option::is_none")]
pub application_data_hash: Option<Secret<String>>,
pub ephemeral_public_key: Secret<String>,
pub public_key_hash: Secret<String>,
pub transaction_id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DecryptedWalletDetails {
pub card: WalletCardData,
#[serde(rename = "cavv")]
pub cryptogram: Secret<String>,
#[serde(rename = "xid")]
pub transaction_id: Secret<String>,
pub wallet_type: FiservWalletType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FiservWalletType {
ApplePay,
GooglePay,
PaypalWallet,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayData {
data: Secret<String>,
signature: Secret<String>,
version: String,
intermediate_signing_key: IntermediateSigningKey,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardData {
card_data: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
security_code: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletCardData {
card_data: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
}
#[derive(Default, Debug, Serialize)]
pub struct Amount {
total: FloatMajorUnit,
currency: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionDetails {
#[serde(skip_serializing_if = "Option::is_none")]
capture_flag: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
reversal_reason_code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_transaction_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
operation_type: Option<OperationType>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum OperationType {
Create,
Capture,
Authorize,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantDetails {
merchant_id: Secret<String>,
terminal_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionInteraction {
origin: TransactionInteractionOrigin,
eci_indicator: TransactionInteractionEciIndicator,
pos_condition_code: TransactionInteractionPosConditionCode,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum TransactionInteractionOrigin {
#[default]
Ecom,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionInteractionEciIndicator {
#[default]
ChannelEncrypted,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionInteractionPosConditionCode {
#[default]
CardNotPresentEcom,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IntermediateSigningKey {
signed_key: Secret<String>,
signatures: Vec<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SignedKey {
key_value: String,
key_expiration: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SignedMessage {
encrypted_message: String,
ephemeral_public_key: String,
tag: String,
}
#[derive(Debug, Default)]
pub struct FullyParsedGooglePayToken {
pub signature: Secret<String>,
pub protocol_version: String,
pub encrypted_message: String,
pub ephemeral_public_key: String,
pub tag: String,
pub key_value: String,
pub key_expiration: String,
pub signatures: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RawGooglePayToken {
pub signature: Secret<String>,
pub protocol_version: String,
pub signed_message: Secret<String>,
pub intermediate_signing_key: IntermediateSigningKey,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ApplePayDecryptedData {
pub data: Secret<String>,
pub signature: Secret<String>,
pub version: Secret<String>,
pub header: ApplePayHeader,
}
pub fn parse_googlepay_token_safely(token_json_str: &str) -> FullyParsedGooglePayToken {
let mut result = FullyParsedGooglePayToken::default();
if let Ok(raw_token) = serde_json::from_str::<RawGooglePayToken>(token_json_str) {
result.signature = raw_token.signature;
result.protocol_version = raw_token.protocol_version;
result.signatures = raw_token
.intermediate_signing_key
.signatures
.into_iter()
.map(|s| s.expose().to_owned())
.collect();
if let Ok(key) = serde_json::from_str::<SignedKey>(
&raw_token.intermediate_signing_key.signed_key.expose(),
) {
result.key_value = key.key_value;
result.key_expiration = key.key_expiration;
}
if let Ok(message) =
serde_json::from_str::<SignedMessage>(&raw_token.signed_message.expose())
{
result.encrypted_message = message.encrypted_message;
result.ephemeral_public_key = message.ephemeral_public_key;
result.tag = message.tag;
}
}
result
}
impl TryFrom<&FiservRouterData<&types::PaymentsAuthorizeRouterData>> for FiservPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &FiservRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let auth: FiservAuthType = FiservAuthType::try_from(&item.router_data.connector_auth_type)?;
let amount = Amount {
total: item.amount,
currency: item.router_data.request.currency.to_string(),
};
let metadata = item.router_data.get_connector_meta()?.clone();
let session: FiservSessionObject = metadata
.expose()
.parse_value("FiservSessionObject")
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "Merchant connector account metadata",
})?;
let merchant_details = MerchantDetails {
merchant_id: auth.merchant_account,
terminal_id: Some(session.terminal_id),
};
let checkout_charges_request = match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ref ccard) => {
Ok(FiservCheckoutChargesRequest::Charges(
ChargesPaymentRequest {
source: Source::PaymentCard {
card: CardData {
card_data: ccard.card_number.clone(),
expiration_month: ccard.card_exp_month.clone(),
expiration_year: ccard.get_expiry_year_4_digit(),
security_code: Some(ccard.card_cvc.clone()),
},
},
transaction_details: TransactionDetails {
capture_flag: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None
)),
reversal_reason_code: None,
merchant_transaction_id: Some(
item.router_data.connector_request_reference_id.clone(),
),
operation_type: None,
},
transaction_interaction: Some(TransactionInteraction {
//Payment is being made in online mode, card not present
origin: TransactionInteractionOrigin::Ecom,
// transaction encryption such as SSL/TLS, but authentication was not performed
eci_indicator: TransactionInteractionEciIndicator::ChannelEncrypted,
//card not present in online transaction
pos_condition_code:
TransactionInteractionPosConditionCode::CardNotPresentEcom,
}),
},
))
}
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::GooglePay(data) => {
let token_string = data
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?
.to_owned();
let parsed = parse_googlepay_token_safely(&token_string);
Ok(FiservCheckoutChargesRequest::Charges(
ChargesPaymentRequest {
source: Source::GooglePay(GooglePayData {
data: Secret::new(parsed.encrypted_message),
signature: Secret::new(parsed.signature.expose().to_owned()),
version: parsed.protocol_version,
intermediate_signing_key: IntermediateSigningKey {
signed_key: Secret::new(
serde_json::json!({
"keyValue": parsed.key_value,
"keyExpiration": parsed.key_expiration
})
.to_string(),
),
signatures: parsed
.signatures
.into_iter()
.map(|s| Secret::new(s.to_owned()))
.collect(),
},
}),
transaction_details: TransactionDetails {
capture_flag: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None
)),
reversal_reason_code: None,
merchant_transaction_id: Some(
item.router_data.connector_request_reference_id.clone(),
),
operation_type: None,
},
transaction_interaction: None,
},
))
}
WalletData::PaypalRedirect(_) => {
let return_url = item
.router_data
.request
.complete_authorize_url
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "return_url",
})?;
Ok(FiservCheckoutChargesRequest::Checkout(
CheckoutPaymentsRequest {
payment_method: FiservPaymentMethod {
provider: FiservWallet::PayPal,
wallet_type: FiservWalletType::PaypalWallet,
},
order: FiservOrder {
intent: FiservIntent::Authorize,
},
interactions: FiservInteractions {
channel: FiservChannel::Web,
customer_confirmation: FiservCustomerConfirmation::ReviewAndPay,
payment_initiator: FiservPaymentInitiator::Merchant,
return_urls: FiservReturnUrls {
success_url: return_url.clone(),
cancel_url: return_url,
},
},
transaction_details: TransactionDetails {
operation_type: Some(OperationType::Create),
capture_flag: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None
)),
reversal_reason_code: None,
merchant_transaction_id: Some(
item.router_data.connector_request_reference_id.clone(),
),
},
},
))
}
WalletData::ApplePay(apple_pay_data) => match item
.router_data
.payment_method_token
.clone()
{
Some(PaymentMethodToken::ApplePayDecrypt(pre_decrypt_data)) => Ok(
FiservCheckoutChargesRequest::Charges(ChargesPaymentRequest {
source: Source::DecryptedWallet(DecryptedWalletDetails {
wallet_type: FiservWalletType::ApplePay,
cryptogram: pre_decrypt_data
.payment_data
.online_payment_cryptogram
.clone(),
transaction_id: Secret::new(apple_pay_data.transaction_identifier),
card: WalletCardData {
card_data: pre_decrypt_data
.application_primary_account_number
.clone(),
expiration_month: pre_decrypt_data
.get_expiry_month()
.change_context(
errors::ConnectorError::MissingRequiredField {
field_name: "apple_pay_expiry_month",
},
)?,
expiration_year: pre_decrypt_data.get_four_digit_expiry_year(),
},
}),
transaction_details: TransactionDetails {
capture_flag: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None
)),
reversal_reason_code: None,
merchant_transaction_id: Some(
item.router_data.connector_request_reference_id.clone(),
),
operation_type: None,
},
transaction_interaction: None,
}),
),
_ => {
let decoded_bytes = match apple_pay_data.payment_data {
common_types::payments::ApplePayPaymentData::Encrypted(
ref encrypted_str,
) => BASE64_ENGINE
.decode(encrypted_str)
.change_context(errors::ConnectorError::ParsingFailed)?,
_ => {
return Err(errors::ConnectorError::ParsingFailed.into());
}
};
let payment_data_decoded: ApplePayDecryptedData =
serde_json::from_slice(&decoded_bytes)
.change_context(errors::ConnectorError::ParsingFailed)?;
let data = payment_data_decoded.data;
let signature = payment_data_decoded.signature;
let version = payment_data_decoded.version;
let header = ApplePayHeader {
ephemeral_public_key: payment_data_decoded.header.ephemeral_public_key,
public_key_hash: payment_data_decoded.header.public_key_hash,
transaction_id: payment_data_decoded.header.transaction_id,
application_data_hash: None,
};
let apple_pay_metadata = item.router_data.get_connector_meta()?.expose();
let applepay_metadata = apple_pay_metadata
.clone()
.parse_value::<ApplepayCombinedSessionTokenData>(
"ApplepayCombinedSessionTokenData",
)
.map(|combined_metadata| {
ApplepaySessionTokenMetadata::ApplePayCombined(
combined_metadata.apple_pay_combined,
)
})
.or_else(|_| {
apple_pay_metadata
.parse_value::<ApplepaySessionTokenData>(
"ApplepaySessionTokenData",
)
.map(|old_metadata| {
ApplepaySessionTokenMetadata::ApplePay(
old_metadata.apple_pay,
)
})
})
.change_context(errors::ConnectorError::ParsingFailed)?;
let merchant_identifier = match applepay_metadata {
ApplepaySessionTokenMetadata::ApplePayCombined(ref combined) => {
match combined {
ApplePayCombinedMetadata::Simplified { .. } => {
return Err(
errors::ConnectorError::MissingApplePayTokenData.into(),
)
}
ApplePayCombinedMetadata::Manual {
session_token_data, ..
} => &session_token_data.merchant_identifier,
}
}
ApplepaySessionTokenMetadata::ApplePay(ref data) => {
&data.session_token_data.merchant_identifier
}
};
Ok(FiservCheckoutChargesRequest::Charges(
ChargesPaymentRequest {
source: Source::ApplePay(ApplePayWalletDetails {
data,
header,
signature,
version,
application_data: None,
apple_pay_merchant_id: Secret::new(
merchant_identifier.to_owned(),
),
}),
transaction_details: TransactionDetails {
capture_flag: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None
)),
reversal_reason_code: None,
merchant_transaction_id: Some(
item.router_data.connector_request_reference_id.clone(),
),
operation_type: None,
},
transaction_interaction: None,
},
))
}
},
_ => Err(error_stack::report!(
errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiserv"),
)
)),
},
PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Err(
error_stack::report!(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiserv"),
)),
),
}?;
Ok(Self {
amount,
checkout_charges_request,
merchant_details,
})
}
}
pub struct FiservAuthType {
pub(super) api_key: Secret<String>,
pub(super) merchant_account: Secret<String>,
pub(super) api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for FiservAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = auth_type
{
Ok(Self {
api_key: api_key.to_owned(),
merchant_account: key1.to_owned(),
api_secret: api_secret.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservCancelRequest {
transaction_details: TransactionDetails,
merchant_details: MerchantDetails,
reference_transaction_details: ReferenceTransactionDetails,
}
impl TryFrom<&types::PaymentsCancelRouterData> for FiservCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let auth: FiservAuthType = FiservAuthType::try_from(&item.connector_auth_type)?;
let metadata = item.get_connector_meta()?.clone();
let session: FiservSessionObject = metadata
.expose()
.parse_value("FiservSessionObject")
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "Merchant connector account metadata",
})?;
Ok(Self {
merchant_details: MerchantDetails {
merchant_id: auth.merchant_account,
terminal_id: Some(session.terminal_id),
},
reference_transaction_details: ReferenceTransactionDetails {
reference_transaction_id: item.request.connector_transaction_id.to_string(),
},
transaction_details: TransactionDetails {
capture_flag: None,
reversal_reason_code: Some(item.request.get_cancellation_reason()?),
merchant_transaction_id: Some(item.connector_request_reference_id.clone()),
operation_type: None,
},
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorResponse {
pub error: Option<Vec<ErrorDetails>>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorDetails {
#[serde(rename = "type")]
pub error_type: Option<String>,
pub code: Option<String>,
pub field: Option<String>,
pub message: Option<String>,
pub additional_info: Option<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FiservPaymentStatus {
Succeeded,
Failed,
Captured,
Declined,
Voided,
Authorized,
#[default]
Processing,
Created,
}
impl From<FiservPaymentStatus> for enums::AttemptStatus {
fn from(item: FiservPaymentStatus) -> Self {
match item {
FiservPaymentStatus::Captured | FiservPaymentStatus::Succeeded => Self::Charged,
FiservPaymentStatus::Declined | FiservPaymentStatus::Failed => Self::Failure,
FiservPaymentStatus::Processing => Self::Authorizing,
FiservPaymentStatus::Voided => Self::Voided,
FiservPaymentStatus::Authorized => Self::Authorized,
FiservPaymentStatus::Created => Self::AuthenticationPending,
}
}
}
impl From<FiservPaymentStatus> for enums::RefundStatus {
fn from(item: FiservPaymentStatus) -> Self {
match item {
FiservPaymentStatus::Succeeded
| FiservPaymentStatus::Authorized
| FiservPaymentStatus::Captured => Self::Success,
FiservPaymentStatus::Declined | FiservPaymentStatus::Failed => Self::Failure,
FiservPaymentStatus::Voided
| FiservPaymentStatus::Processing
| FiservPaymentStatus::Created => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessorResponseDetails {
pub approval_status: Option<String>,
pub approval_code: Option<String>,
pub reference_number: Option<String>,
pub processor: Option<String>,
pub host: Option<String>,
pub network_routed: Option<String>,
pub network_international_id: Option<String>,
pub response_code: Option<String>,
pub response_message: Option<String>,
pub host_response_code: Option<String>,
pub host_response_message: Option<String>,
pub additional_info: Option<Vec<AdditionalInfo>>,
pub bank_association_details: Option<BankAssociationDetails>,
pub response_indicators: Option<ResponseIndicators>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdditionalInfo {
pub name: Option<String>,
pub value: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BankAssociationDetails {
pub association_response_code: Option<String>,
pub avs_security_code_response: Option<AvsSecurityCodeResponse>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AvsSecurityCodeResponse {
pub street_match: Option<String>,
pub postal_code_match: Option<String>,
pub security_code_match: Option<String>,
pub association: Option<Association>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Association {
pub avs_code: Option<String>,
pub security_code_response: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResponseIndicators {
pub alternate_route_debit_indicator: Option<bool>,
pub signature_line_indicator: Option<bool>,
pub signature_debit_route_indicator: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservChargesResponse {
pub gateway_response: GatewayResponse,
pub payment_receipt: PaymentReceipt,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservCheckoutResponse {
pub gateway_response: GatewayResponse,
pub payment_receipt: PaymentReceipt,
pub interactions: FiservResponseInteractions,
pub order: Option<FiservResponseOrders>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservResponseInteractions {
actions: FiservResponseActions,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservResponseActions {
#[serde(rename = "type")]
action_type: String,
url: url::Url,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservResponseOrders {
intent: FiservIntent,
order_id: String,
order_status: FiservOrderStatus,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FiservOrderStatus {
PayerActionRequired,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FiservPaymentsResponse {
Charges(FiservChargesResponse),
Checkout(FiservCheckoutResponse),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentReceipt {
pub approved_amount: ApprovedAmount,
pub processor_response_details: Option<ProcessorResponseDetails>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApprovedAmount {
pub total: FloatMajorUnit,
pub currency: Currency,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(transparent)]
pub struct FiservSyncResponse {
pub sync_responses: Vec<FiservPaymentsResponse>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GatewayResponse {
gateway_transaction_id: Option<String>,
transaction_state: FiservPaymentStatus,
transaction_processing_details: TransactionProcessingDetails,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionProcessingDetails {
order_id: String,
transaction_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, FiservPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FiservPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (gateway_resp, redirect_url, order_id) = match &item.response {
FiservPaymentsResponse::Charges(res) => (res.gateway_response.clone(), None, None),
FiservPaymentsResponse::Checkout(res) => (
res.gateway_response.clone(),
Some(res.interactions.actions.url.clone()),
res.order.as_ref().map(|o| o.order_id.clone()),
),
};
let redirection_data = redirect_url.map(|url| RedirectForm::from((url, Method::Get)));
let connector_metadata: Option<serde_json::Value> = Some(serde_json::json!({
"order_id": order_id,
}));
Ok(Self {
status: enums::AttemptStatus::from(gateway_resp.transaction_state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
gateway_resp.transaction_processing_details.transaction_id,
),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(
gateway_resp.transaction_processing_details.order_id,
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FiservSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FiservSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let gateway_resp = match item.response.sync_responses.first() {
Some(gateway_response) => gateway_response,
None => Err(errors::ConnectorError::ResponseHandlingFailed)?,
};
let connector_response_reference_id = match gateway_resp {
FiservPaymentsResponse::Charges(res) => {
&res.gateway_response.transaction_processing_details.order_id
}
FiservPaymentsResponse::Checkout(res) => {
&res.gateway_response.transaction_processing_details.order_id
}
};
let transaction_id = match gateway_resp {
FiservPaymentsResponse::Charges(res) => {
&res.gateway_response
.transaction_processing_details
.transaction_id
}
FiservPaymentsResponse::Checkout(res) => {
&res.gateway_response
.transaction_processing_details
.transaction_id
}
};
let transaction_state = match gateway_resp {
FiservPaymentsResponse::Charges(res) => &res.gateway_response.transaction_state,
FiservPaymentsResponse::Checkout(res) => &res.gateway_response.transaction_state,
};
Ok(Self {
status: enums::AttemptStatus::from(transaction_state.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(connector_response_reference_id.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservCaptureRequest {
amount: Amount,
transaction_details: TransactionDetails,
merchant_details: MerchantDetails,
reference_transaction_details: ReferenceTransactionDetails,
#[serde(skip_serializing_if = "Option::is_none")]
order: Option<FiservOrderRequest>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservOrderRequest {
order_id: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReferenceTransactionDetails {
reference_transaction_id: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FiservSessionObject {
pub terminal_id: Secret<String>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for FiservSessionObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
impl TryFrom<&FiservRouterData<&types::PaymentsCaptureRouterData>> for FiservCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &FiservRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let auth: FiservAuthType = FiservAuthType::try_from(&item.router_data.connector_auth_type)?;
let metadata = item
.router_data
.connector_meta_data
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
let session: FiservSessionObject = metadata
.expose()
.parse_value("FiservSessionObject")
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "Merchant connector account metadata",
})?;
let order_id = item
.router_data
.request
.connector_meta
.as_ref()
.and_then(|v| v.get("order_id"))
.and_then(|v| v.as_str())
.map(|s| s.to_string());
Ok(Self {
amount: Amount {
total: item.amount,
currency: item.router_data.request.currency.to_string(),
},
order: Some(FiservOrderRequest { order_id }),
transaction_details: TransactionDetails {
capture_flag: Some(true),
reversal_reason_code: None,
merchant_transaction_id: Some(
item.router_data.connector_request_reference_id.clone(),
),
operation_type: Some(OperationType::Capture),
},
merchant_details: MerchantDetails {
merchant_id: auth.merchant_account,
terminal_id: Some(session.terminal_id),
},
reference_transaction_details: ReferenceTransactionDetails {
reference_transaction_id: item
.router_data
.request
.connector_transaction_id
.to_string(),
},
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservSyncRequest {
merchant_details: MerchantDetails,
reference_transaction_details: ReferenceTransactionDetails,
}
impl TryFrom<&types::PaymentsSyncRouterData> for FiservSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let auth: FiservAuthType = FiservAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
merchant_details: MerchantDetails {
merchant_id: auth.merchant_account,
terminal_id: None,
},
reference_transaction_details: ReferenceTransactionDetails {
reference_transaction_id: item
.request
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
},
})
}
}
impl TryFrom<&types::RefundSyncRouterData> for FiservSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
let auth: FiservAuthType = FiservAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
merchant_details: MerchantDetails {
merchant_id: auth.merchant_account,
terminal_id: None,
},
reference_transaction_details: ReferenceTransactionDetails {
reference_transaction_id: item
.request
.connector_refund_id
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?,
},
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FiservRefundRequest {
amount: Amount,
merchant_details: MerchantDetails,
reference_transaction_details: ReferenceTransactionDetails,
}
impl<F> TryFrom<&FiservRouterData<&types::RefundsRouterData<F>>> for FiservRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &FiservRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let auth: FiservAuthType = FiservAuthType::try_from(&item.router_data.connector_auth_type)?;
let metadata = item
.router_data
.connector_meta_data
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
let session: FiservSessionObject = metadata
.expose()
.parse_value("FiservSessionObject")
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "Merchant connector account metadata",
})?;
Ok(Self {
amount: Amount {
total: item.amount,
currency: item.router_data.request.currency.to_string(),
},
merchant_details: MerchantDetails {
merchant_id: auth.merchant_account,
terminal_id: Some(session.terminal_id),
},
reference_transaction_details: ReferenceTransactionDetails {
reference_transaction_id: item
.router_data
.request
.connector_transaction_id
.to_string(),
},
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
pub gateway_response: GatewayResponse,
pub payment_receipt: PaymentReceipt,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item
.response
.gateway_response
.transaction_processing_details
.transaction_id,
refund_status: enums::RefundStatus::from(
item.response.gateway_response.transaction_state,
),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, FiservSyncResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, FiservSyncResponse>,
) -> Result<Self, Self::Error> {
let gateway_resp = item
.response
.sync_responses
.first()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let transaction_id = match gateway_resp {
FiservPaymentsResponse::Charges(res) => {
&res.gateway_response
.transaction_processing_details
.transaction_id
}
FiservPaymentsResponse::Checkout(res) => {
&res.gateway_response
.transaction_processing_details
.transaction_id
}
};
let transaction_state = match gateway_resp {
FiservPaymentsResponse::Charges(res) => &res.gateway_response.transaction_state,
FiservPaymentsResponse::Checkout(res) => &res.gateway_response.transaction_state,
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: transaction_id.clone(),
refund_status: enums::RefundStatus::from(transaction_state.clone()),
}),
..item.data
})
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 9250
}
|
large_file_-3132723007297421764
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
</path>
<file>
use api_models::webhooks::IncomingWebhookEvent;
use cards::CardNumber;
use common_enums::enums;
use common_utils::{
pii::{self, SecretSerdeValue},
request::Method,
types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{
BankRedirectData, BankTransferData, Card as CardData, CryptoData, GiftCardData,
PayLaterData, PaymentMethodData, VoucherData, WalletData,
},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{
CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsPreProcessingData, ResponseId,
},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsPreProcessingRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{
PaymentsPreprocessingResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
},
utils::{
self, to_connector_meta, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData, RouterData as _,
},
};
type Error = error_stack::Report<errors::ConnectorError>;
trait Shift4AuthorizePreprocessingCommon {
fn is_automatic_capture(&self) -> Result<bool, Error>;
fn get_router_return_url(&self) -> Option<String>;
fn get_email_optional(&self) -> Option<pii::Email>;
fn get_complete_authorize_url(&self) -> Option<String>;
fn get_currency_required(&self) -> Result<enums::Currency, Error>;
fn get_metadata(&self) -> Result<Option<serde_json::Value>, Error>;
fn get_payment_method_data_required(&self) -> Result<PaymentMethodData, Error>;
}
pub struct Shift4RouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for Shift4RouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
impl Shift4AuthorizePreprocessingCommon for PaymentsAuthorizeData {
fn get_email_optional(&self) -> Option<pii::Email> {
self.email.clone()
}
fn get_complete_authorize_url(&self) -> Option<String> {
self.complete_authorize_url.clone()
}
fn get_currency_required(
&self,
) -> Result<enums::Currency, error_stack::Report<errors::ConnectorError>> {
Ok(self.currency)
}
fn get_payment_method_data_required(
&self,
) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>> {
Ok(self.payment_method_data.clone())
}
fn is_automatic_capture(&self) -> Result<bool, Error> {
self.is_auto_capture()
}
fn get_router_return_url(&self) -> Option<String> {
self.router_return_url.clone()
}
fn get_metadata(
&self,
) -> Result<Option<serde_json::Value>, error_stack::Report<errors::ConnectorError>> {
Ok(self.metadata.clone())
}
}
impl Shift4AuthorizePreprocessingCommon for PaymentsPreProcessingData {
fn get_email_optional(&self) -> Option<pii::Email> {
self.email.clone()
}
fn get_complete_authorize_url(&self) -> Option<String> {
self.complete_authorize_url.clone()
}
fn get_currency_required(&self) -> Result<enums::Currency, Error> {
self.get_currency()
}
fn get_payment_method_data_required(&self) -> Result<PaymentMethodData, Error> {
self.payment_method_data.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "payment_method_data",
}
.into(),
)
}
fn is_automatic_capture(&self) -> Result<bool, Error> {
self.is_auto_capture()
}
fn get_router_return_url(&self) -> Option<String> {
self.router_return_url.clone()
}
fn get_metadata(
&self,
) -> Result<Option<serde_json::Value>, error_stack::Report<errors::ConnectorError>> {
Ok(None)
}
}
#[derive(Debug, Serialize)]
pub struct Shift4PaymentsRequest {
amount: MinorUnit,
currency: enums::Currency,
captured: bool,
metadata: Option<serde_json::Value>,
#[serde(flatten)]
payment_method: Shift4PaymentMethod,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum Shift4PaymentMethod {
CardsNon3DSRequest(Box<CardsNon3DSRequest>),
BankRedirectRequest(Box<BankRedirectRequest>),
Cards3DSRequest(Box<Cards3DSRequest>),
VoucherRequest(Box<VoucherRequest>),
WalletRequest(Box<WalletRequest>),
PayLaterRequest(Box<PayLaterRequest>),
CryptoRequest(Box<CryptoRequest>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletRequest {
flow: Flow,
payment_method: PaymentMethod,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayLaterRequest {
flow: Flow,
payment_method: PaymentMethod,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CryptoRequest {
flow: Flow,
payment_method: PaymentMethod,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoucherRequest {
flow: Flow,
payment_method: PaymentMethod,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankRedirectRequest {
payment_method: PaymentMethod,
flow: Flow,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Cards3DSRequest {
#[serde(rename = "card[number]")]
pub card_number: CardNumber,
#[serde(rename = "card[expMonth]")]
pub card_exp_month: Secret<String>,
#[serde(rename = "card[expYear]")]
pub card_exp_year: Secret<String>,
return_url: String,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardsNon3DSRequest {
card: CardPayment,
description: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Flow {
pub return_url: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PaymentMethodType {
Eps,
Giropay,
Ideal,
Sofort,
Boleto,
Trustly,
Alipay,
Wechatpay,
Blik,
KlarnaDebitRisk,
Bitpay,
Paysera,
Skrill,
}
#[derive(Debug, Serialize)]
pub struct PaymentMethod {
#[serde(rename = "type")]
method_type: PaymentMethodType,
billing: Billing,
}
#[derive(Debug, Serialize)]
pub struct Billing {
name: Option<Secret<String>>,
email: Option<pii::Email>,
address: Option<Address>,
#[serde(skip_serializing_if = "Option::is_none")]
vat: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct Address {
line1: Option<Secret<String>>,
line2: Option<Secret<String>>,
zip: Option<Secret<String>>,
state: Option<Secret<String>>,
city: Option<String>,
country: Option<api_models::enums::CountryAlpha2>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct DeviceData;
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Card {
pub number: CardNumber,
pub exp_month: Secret<String>,
pub exp_year: Secret<String>,
pub cardholder_name: Secret<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(untagged)]
pub enum CardPayment {
RawCard(Box<Card>),
CardToken(Secret<String>),
}
impl<T, Req> TryFrom<&Shift4RouterData<&RouterData<T, Req, PaymentsResponseData>>>
for Shift4PaymentsRequest
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
item: &Shift4RouterData<&RouterData<T, Req, PaymentsResponseData>>,
) -> Result<Self, Self::Error> {
let submit_for_settlement = item.router_data.request.is_automatic_capture()?;
let amount = item.amount.to_owned();
let currency = item.router_data.request.get_currency_required()?;
let metadata = item.router_data.request.get_metadata()?;
let payment_method = Shift4PaymentMethod::try_from(item.router_data)?;
Ok(Self {
amount,
currency,
captured: submit_for_settlement,
metadata,
payment_method,
})
}
}
impl TryFrom<&PayLaterData> for PaymentMethodType {
type Error = Error;
fn try_from(value: &PayLaterData) -> Result<Self, Self::Error> {
match value {
PayLaterData::KlarnaRedirect { .. } => Ok(Self::KlarnaDebitRisk),
PayLaterData::AffirmRedirect { .. }
| PayLaterData::AfterpayClearpayRedirect { .. }
| PayLaterData::PayBrightRedirect { .. }
| PayLaterData::WalleyRedirect { .. }
| PayLaterData::AlmaRedirect { .. }
| PayLaterData::AtomeRedirect { .. }
| PayLaterData::FlexitiRedirect { .. }
| PayLaterData::KlarnaSdk { .. }
| PayLaterData::BreadpayRedirect { .. } => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into()),
}
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &PayLaterData)>
for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, pay_later_data): (&RouterData<T, Req, PaymentsResponseData>, &PayLaterData),
) -> Result<Self, Self::Error> {
let flow = Flow::try_from(item.request.get_router_return_url())?;
let method_type = PaymentMethodType::try_from(pay_later_data)?;
let billing = Billing::try_from(item)?;
let payment_method = PaymentMethod {
method_type,
billing,
};
Ok(Self::BankRedirectRequest(Box::new(BankRedirectRequest {
payment_method,
flow,
})))
}
}
impl<T, Req> TryFrom<&RouterData<T, Req, PaymentsResponseData>> for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(item: &RouterData<T, Req, PaymentsResponseData>) -> Result<Self, Self::Error> {
match item.request.get_payment_method_data_required()? {
PaymentMethodData::Card(ref ccard) => Self::try_from((item, ccard)),
PaymentMethodData::BankRedirect(ref redirect) => Self::try_from((item, redirect)),
PaymentMethodData::Wallet(ref wallet_data) => Self::try_from((item, wallet_data)),
PaymentMethodData::BankTransfer(ref bank_transfer_data) => {
Self::try_from(bank_transfer_data.as_ref())
}
PaymentMethodData::Voucher(ref voucher_data) => Self::try_from((item, voucher_data)),
PaymentMethodData::GiftCard(ref giftcard_data) => {
Self::try_from(giftcard_data.as_ref())
}
PaymentMethodData::PayLater(ref pay_later_data) => {
Self::try_from((item, pay_later_data))
}
PaymentMethodData::Crypto(ref crypto_data) => Self::try_from((item, crypto_data)),
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into())
}
}
}
}
impl TryFrom<&WalletData> for PaymentMethodType {
type Error = Error;
fn try_from(value: &WalletData) -> Result<Self, Self::Error> {
match value {
WalletData::AliPayRedirect { .. } => Ok(Self::Alipay),
WalletData::WeChatPayRedirect { .. } => Ok(Self::Wechatpay),
WalletData::Paysera(_) => Ok(Self::Paysera),
WalletData::Skrill(_) => Ok(Self::Skrill),
WalletData::AliPayQr(_)
| WalletData::AmazonPay(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::GooglePay(_)
| WalletData::BluecodeRedirect {}
| WalletData::PaypalRedirect(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into()),
}
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &WalletData)>
for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, wallet_data): (&RouterData<T, Req, PaymentsResponseData>, &WalletData),
) -> Result<Self, Self::Error> {
let flow = Flow::try_from(item.request.get_router_return_url())?;
let method_type = PaymentMethodType::try_from(wallet_data)?;
let billing = Billing::try_from(item)?;
let payment_method = PaymentMethod {
method_type,
billing,
};
Ok(Self::WalletRequest(Box::new(WalletRequest {
payment_method,
flow,
})))
}
}
impl TryFrom<&BankTransferData> for Shift4PaymentMethod {
type Error = Error;
fn try_from(bank_transfer_data: &BankTransferData) -> Result<Self, Self::Error> {
match bank_transfer_data {
BankTransferData::MultibancoBankTransfer { .. }
| BankTransferData::AchBankTransfer { .. }
| BankTransferData::SepaBankTransfer { .. }
| BankTransferData::BacsBankTransfer { .. }
| BankTransferData::PermataBankTransfer { .. }
| BankTransferData::BcaBankTransfer { .. }
| BankTransferData::BniVaBankTransfer { .. }
| BankTransferData::BriVaBankTransfer { .. }
| BankTransferData::CimbVaBankTransfer { .. }
| BankTransferData::DanamonVaBankTransfer { .. }
| BankTransferData::MandiriVaBankTransfer { .. }
| BankTransferData::Pix { .. }
| BankTransferData::Pse {}
| BankTransferData::InstantBankTransfer {}
| BankTransferData::InstantBankTransferFinland { .. }
| BankTransferData::InstantBankTransferPoland { .. }
| BankTransferData::IndonesianBankTransfer { .. }
| BankTransferData::LocalBankTransfer { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into())
}
}
}
}
impl TryFrom<&VoucherData> for PaymentMethodType {
type Error = Error;
fn try_from(value: &VoucherData) -> Result<Self, Self::Error> {
match value {
VoucherData::Boleto { .. } => Ok(Self::Boleto),
VoucherData::Alfamart { .. }
| VoucherData::Indomaret { .. }
| VoucherData::Efecty
| VoucherData::PagoEfectivo
| VoucherData::RedCompra
| VoucherData::Oxxo
| VoucherData::RedPagos
| VoucherData::SevenEleven { .. }
| VoucherData::Lawson { .. }
| VoucherData::MiniStop { .. }
| VoucherData::FamilyMart { .. }
| VoucherData::Seicomart { .. }
| VoucherData::PayEasy { .. } => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into()),
}
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &VoucherData)>
for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, voucher_data): (&RouterData<T, Req, PaymentsResponseData>, &VoucherData),
) -> Result<Self, Self::Error> {
let mut billing = Billing::try_from(item)?;
match voucher_data {
VoucherData::Boleto(boleto_data) => {
billing.vat = boleto_data.social_security_number.clone();
}
_ => {
billing.vat = None;
}
};
let method_type = PaymentMethodType::try_from(voucher_data)?;
let payment_method_details = PaymentMethod {
method_type,
billing,
};
let flow = Flow::try_from(item.request.get_router_return_url())?;
Ok(Self::VoucherRequest(Box::new(VoucherRequest {
payment_method: payment_method_details,
flow,
})))
}
}
impl TryFrom<&GiftCardData> for Shift4PaymentMethod {
type Error = Error;
fn try_from(gift_card_data: &GiftCardData) -> Result<Self, Self::Error> {
match gift_card_data {
GiftCardData::Givex(_)
| GiftCardData::PaySafeCard {}
| GiftCardData::BhnCardNetwork(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into()),
}
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &CardData)> for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, card): (&RouterData<T, Req, PaymentsResponseData>, &CardData),
) -> Result<Self, Self::Error> {
let card_object = Card {
number: card.card_number.clone(),
exp_month: card.card_exp_month.clone(),
exp_year: card.card_exp_year.clone(),
cardholder_name: item
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string())),
};
if item.is_three_ds() {
Ok(Self::Cards3DSRequest(Box::new(Cards3DSRequest {
card_number: card_object.number,
card_exp_month: card_object.exp_month,
card_exp_year: card_object.exp_year,
return_url: item
.request
.get_complete_authorize_url()
.clone()
.ok_or_else(|| errors::ConnectorError::RequestEncodingFailed)?,
})))
} else {
Ok(Self::CardsNon3DSRequest(Box::new(CardsNon3DSRequest {
card: CardPayment::RawCard(Box::new(card_object)),
description: item.description.clone(),
})))
}
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &BankRedirectData)>
for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, redirect_data): (&RouterData<T, Req, PaymentsResponseData>, &BankRedirectData),
) -> Result<Self, Self::Error> {
let flow = Flow::try_from(item.request.get_router_return_url())?;
let method_type = PaymentMethodType::try_from(redirect_data)?;
let billing = Billing::try_from(item)?;
let payment_method = PaymentMethod {
method_type,
billing,
};
Ok(Self::BankRedirectRequest(Box::new(BankRedirectRequest {
payment_method,
flow,
})))
}
}
impl TryFrom<&CryptoData> for PaymentMethodType {
type Error = Error;
fn try_from(_value: &CryptoData) -> Result<Self, Self::Error> {
Ok(Self::Bitpay)
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &CryptoData)>
for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, redirect_data): (&RouterData<T, Req, PaymentsResponseData>, &CryptoData),
) -> Result<Self, Self::Error> {
let flow = Flow::try_from(item.request.get_router_return_url())?;
let method_type = PaymentMethodType::try_from(redirect_data)?;
let billing = Billing::try_from(item)?;
let payment_method = PaymentMethod {
method_type,
billing,
};
Ok(Self::CryptoRequest(Box::new(CryptoRequest {
payment_method,
flow,
})))
}
}
impl<T> TryFrom<&Shift4RouterData<&RouterData<T, CompleteAuthorizeData, PaymentsResponseData>>>
for Shift4PaymentsRequest
{
type Error = Error;
fn try_from(
item: &Shift4RouterData<&RouterData<T, CompleteAuthorizeData, PaymentsResponseData>>,
) -> Result<Self, Self::Error> {
match &item.router_data.request.payment_method_data {
Some(PaymentMethodData::Card(_)) => {
let card_token: Shift4CardToken =
to_connector_meta(item.router_data.request.connector_meta.clone())?;
let metadata = item.router_data.request.metadata.clone();
Ok(Self {
amount: item.amount.to_owned(),
currency: item.router_data.request.currency,
metadata,
payment_method: Shift4PaymentMethod::CardsNon3DSRequest(Box::new(
CardsNon3DSRequest {
card: CardPayment::CardToken(card_token.id),
description: item.router_data.description.clone(),
},
)),
captured: item.router_data.request.is_auto_capture()?,
})
}
Some(PaymentMethodData::Wallet(_))
| Some(PaymentMethodData::GiftCard(_))
| Some(PaymentMethodData::CardRedirect(_))
| Some(PaymentMethodData::PayLater(_))
| Some(PaymentMethodData::BankDebit(_))
| Some(PaymentMethodData::BankRedirect(_))
| Some(PaymentMethodData::BankTransfer(_))
| Some(PaymentMethodData::Crypto(_))
| Some(PaymentMethodData::MandatePayment)
| Some(PaymentMethodData::Voucher(_))
| Some(PaymentMethodData::Reward)
| Some(PaymentMethodData::RealTimePayment(_))
| Some(PaymentMethodData::MobilePayment(_))
| Some(PaymentMethodData::Upi(_))
| Some(PaymentMethodData::OpenBanking(_))
| Some(PaymentMethodData::CardToken(_))
| Some(PaymentMethodData::NetworkToken(_))
| Some(PaymentMethodData::CardDetailsForNetworkTransactionId(_))
| None => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into()),
}
}
}
impl TryFrom<&BankRedirectData> for PaymentMethodType {
type Error = Error;
fn try_from(value: &BankRedirectData) -> Result<Self, Self::Error> {
match value {
BankRedirectData::Eps { .. } => Ok(Self::Eps),
BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
BankRedirectData::Ideal { .. } => Ok(Self::Ideal),
BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
BankRedirectData::Trustly { .. } => Ok(Self::Trustly),
BankRedirectData::Blik { .. } => Ok(Self::Blik),
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::Bizum {}
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into())
}
}
}
}
impl TryFrom<Option<String>> for Flow {
type Error = Error;
fn try_from(router_return_url: Option<String>) -> Result<Self, Self::Error> {
Ok(Self {
return_url: router_return_url.ok_or(errors::ConnectorError::RequestEncodingFailed)?,
})
}
}
impl<T, Req> TryFrom<&RouterData<T, Req, PaymentsResponseData>> for Billing
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(item: &RouterData<T, Req, PaymentsResponseData>) -> Result<Self, Self::Error> {
let billing_details = item.get_optional_billing();
let address_details_model = billing_details.as_ref().and_then(|b| b.address.as_ref());
let address = get_address_details(address_details_model);
Ok(Self {
name: item.get_optional_billing_full_name(),
email: item.request.get_email_optional(),
address,
vat: None,
})
}
}
fn get_address_details(
address_details: Option<&hyperswitch_domain_models::address::AddressDetails>,
) -> Option<Address> {
address_details.map(|address| Address {
line1: address.line1.clone(),
line2: address.line1.clone(),
zip: address.zip.clone(),
state: address.state.clone(),
city: address.city.clone(),
country: address.country,
})
}
// Auth Struct
pub struct Shift4AuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for Shift4AuthType {
type Error = Error;
fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::HeaderKey { api_key } = item {
Ok(Self {
api_key: api_key.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Default, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Shift4PaymentStatus {
Successful,
Failed,
#[default]
Pending,
}
fn get_status(
captured: bool,
next_action: Option<&NextAction>,
payment_status: Shift4PaymentStatus,
) -> enums::AttemptStatus {
match payment_status {
Shift4PaymentStatus::Successful => {
if captured {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
Shift4PaymentStatus::Failed => enums::AttemptStatus::Failure,
Shift4PaymentStatus::Pending => match next_action {
Some(NextAction::Redirect) => enums::AttemptStatus::AuthenticationPending,
Some(NextAction::Wait) | Some(NextAction::None) | None => enums::AttemptStatus::Pending,
},
}
}
#[derive(Debug, Deserialize)]
pub struct Shift4WebhookObjectEventType {
#[serde(rename = "type")]
pub event_type: Shift4WebhookEvent,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Shift4WebhookEvent {
ChargeSucceeded,
ChargeFailed,
ChargeUpdated,
ChargeCaptured,
ChargeRefunded,
#[serde(other)]
Unknown,
}
#[derive(Debug, Deserialize)]
pub struct Shift4WebhookObjectData {
pub id: String,
pub refunds: Option<Vec<RefundIdObject>>,
}
#[derive(Debug, Deserialize)]
pub struct RefundIdObject {
pub id: String,
}
#[derive(Debug, Deserialize)]
pub struct Shift4WebhookObjectId {
#[serde(rename = "type")]
pub event_type: Shift4WebhookEvent,
pub data: Shift4WebhookObjectData,
}
#[derive(Debug, Deserialize)]
pub struct Shift4WebhookObjectResource {
pub data: serde_json::Value,
}
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct Shift4NonThreeDsResponse {
pub id: String,
pub currency: String,
pub amount: u32,
pub status: Shift4PaymentStatus,
pub captured: bool,
pub refunded: bool,
pub flow: Option<FlowResponse>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct Shift4ThreeDsResponse {
pub enrolled: bool,
pub version: Option<String>,
#[serde(rename = "redirectUrl")]
pub redirect_url: Option<Url>,
pub token: Token,
}
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct Token {
pub id: Secret<String>,
pub created: i64,
#[serde(rename = "objectType")]
pub object_type: String,
pub first6: String,
pub last4: String,
pub fingerprint: Secret<String>,
pub brand: String,
#[serde(rename = "type")]
pub token_type: String,
pub country: String,
pub used: bool,
#[serde(rename = "threeDSecureInfo")]
pub three_d_secure_info: ThreeDSecureInfo,
}
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct ThreeDSecureInfo {
pub amount: MinorUnit,
pub currency: String,
pub enrolled: bool,
#[serde(rename = "liabilityShift")]
pub liability_shift: Option<String>,
pub version: String,
#[serde(rename = "authenticationFlow")]
pub authentication_flow: Option<SecretSerdeValue>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FlowResponse {
pub next_action: Option<NextAction>,
pub redirect: Option<Redirect>,
pub return_url: Option<Url>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Redirect {
pub redirect_url: Option<Url>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum NextAction {
Redirect,
Wait,
None,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Shift4CardToken {
pub id: Secret<String>,
}
impl TryFrom<PaymentsPreprocessingResponseRouterData<Shift4ThreeDsResponse>>
for PaymentsPreProcessingRouterData
{
type Error = Error;
fn try_from(
item: PaymentsPreprocessingResponseRouterData<Shift4ThreeDsResponse>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.redirect_url
.map(|url| RedirectForm::from((url, Method::Get)));
Ok(Self {
status: if redirection_data.is_some() {
enums::AttemptStatus::AuthenticationPending
} else {
enums::AttemptStatus::Pending
},
request: PaymentsPreProcessingData {
enrolled_for_3ds: item.response.enrolled,
..item.data.request
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(
serde_json::to_value(Shift4CardToken {
id: item.response.token.id,
})
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?,
),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<T, F> TryFrom<ResponseRouterData<F, Shift4NonThreeDsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, Shift4NonThreeDsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let connector_id = ResponseId::ConnectorTransactionId(item.response.id.clone());
Ok(Self {
status: get_status(
item.response.captured,
item.response
.flow
.as_ref()
.and_then(|flow| flow.next_action.as_ref()),
item.response.status,
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: connector_id,
redirection_data: Box::new(
item.response
.flow
.and_then(|flow| flow.redirect)
.and_then(|redirect| redirect.redirect_url)
.map(|url| RedirectForm::from((url, Method::Get))),
),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Shift4RefundRequest {
charge_id: String,
amount: MinorUnit,
}
impl<F> TryFrom<&Shift4RouterData<&RefundsRouterData<F>>> for Shift4RefundRequest {
type Error = Error;
fn try_from(item: &Shift4RouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
charge_id: item.router_data.request.connector_transaction_id.clone(),
amount: item.amount.to_owned(),
})
}
}
impl From<Shift4RefundStatus> for enums::RefundStatus {
fn from(item: Shift4RefundStatus) -> Self {
match item {
Shift4RefundStatus::Successful => Self::Success,
Shift4RefundStatus::Failed => Self::Failure,
Shift4RefundStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
pub id: String,
pub amount: i64,
pub currency: String,
pub charge: String,
pub status: Shift4RefundStatus,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Shift4RefundStatus {
Successful,
Processing,
#[default]
Failed,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
..item.data
})
}
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct ErrorResponse {
pub error: ApiErrorResponse,
}
#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq, Serialize)]
pub struct ApiErrorResponse {
pub code: Option<String>,
pub message: String,
}
pub fn is_transaction_event(event: &Shift4WebhookEvent) -> bool {
matches!(
event,
Shift4WebhookEvent::ChargeCaptured
| Shift4WebhookEvent::ChargeFailed
| Shift4WebhookEvent::ChargeSucceeded
| Shift4WebhookEvent::ChargeUpdated
)
}
pub fn is_refund_event(event: &Shift4WebhookEvent) -> bool {
matches!(event, Shift4WebhookEvent::ChargeRefunded)
}
impl From<Shift4WebhookEvent> for IncomingWebhookEvent {
fn from(event: Shift4WebhookEvent) -> Self {
match event {
Shift4WebhookEvent::ChargeSucceeded | Shift4WebhookEvent::ChargeUpdated => {
//reference : https://dev.shift4.com/docs/api#event-types
Self::PaymentIntentProcessing
}
Shift4WebhookEvent::ChargeCaptured => Self::PaymentIntentSuccess,
Shift4WebhookEvent::ChargeFailed => Self::PaymentIntentFailure,
Shift4WebhookEvent::ChargeRefunded => Self::RefundSuccess,
Shift4WebhookEvent::Unknown => Self::EventNotSupported,
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 8563
}
|
large_file_1053530327650114044
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
</path>
<file>
use common_enums::{
enums::{self, AttemptStatus, PaymentChannel},
CountryAlpha2,
};
use common_utils::{
errors::{CustomResult, ParsingError},
ext_traits::ByteSliceExt,
request::{Method, RequestContent},
types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
payment_methods::storage_enums::MitCategory,
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ErrorResponse, PaymentMethodToken, RouterData,
},
router_flow_types::{Execute, RSync, SetupMandate},
router_request_types::{ResponseId, SetupMandateRequestData},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundsRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{consts, errors, webhooks};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use time::PrimitiveDateTime;
use url::Url;
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
ResponseRouterData, SubmitEvidenceRouterData, UploadFileRouterData,
},
unimplemented_payment_method,
utils::{
self, PaymentsAuthorizeRequestData, PaymentsCaptureRequestData, PaymentsSyncRequestData,
RouterData as OtherRouterData, WalletData as OtherWalletData,
},
};
#[derive(Debug, Serialize)]
pub struct CheckoutRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for CheckoutRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
#[serde(tag = "type", content = "token_data")]
pub enum TokenRequest {
Googlepay(CheckoutGooglePayData),
Applepay(CheckoutApplePayData),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
#[serde(tag = "type", content = "token_data")]
pub enum PreDecryptedTokenRequest {
Applepay(Box<CheckoutApplePayData>),
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckoutGooglePayData {
protocol_version: Secret<String>,
signature: Secret<String>,
signed_message: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckoutApplePayData {
version: Secret<String>,
data: Secret<String>,
signature: Secret<String>,
header: CheckoutApplePayHeader,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckoutApplePayHeader {
ephemeral_public_key: Secret<String>,
public_key_hash: Secret<String>,
transaction_id: Secret<String>,
}
impl TryFrom<&TokenizationRouterData> for TokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Wallet(wallet_data) => match wallet_data.clone() {
WalletData::GooglePay(_data) => {
let json_wallet_data: CheckoutGooglePayData =
wallet_data.get_wallet_token_as_json("Google Pay".to_string())?;
Ok(Self::Googlepay(json_wallet_data))
}
WalletData::ApplePay(_data) => {
let json_wallet_data: CheckoutApplePayData =
wallet_data.get_wallet_token_as_json("Apple Pay".to_string())?;
Ok(Self::Applepay(json_wallet_data))
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::WeChatPayQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)
.into()),
},
PaymentMethodData::Card(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)
.into())
}
}
}
}
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct CheckoutTokenResponse {
token: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, CheckoutTokenResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CheckoutTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.token.expose(),
}),
..item.data
})
}
}
#[skip_serializing_none]
#[derive(Debug, Serialize)]
pub struct CheckoutAddress {
pub address_line1: Option<Secret<String>>,
pub address_line2: Option<Secret<String>>,
pub city: Option<String>,
pub state: Option<Secret<String>>,
pub zip: Option<Secret<String>>,
pub country: Option<CountryAlpha2>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize)]
pub struct CheckoutAccountHolderDetails {
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct CardSource {
#[serde(rename = "type")]
pub source_type: CheckoutSourceTypes,
pub number: cards::CardNumber,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
pub cvv: Option<Secret<String>>,
pub billing_address: Option<CheckoutAddress>,
pub account_holder: Option<CheckoutAccountHolderDetails>,
}
#[derive(Debug, Serialize)]
pub struct WalletSource {
#[serde(rename = "type")]
pub source_type: CheckoutSourceTypes,
pub token: Secret<String>,
pub billing_address: Option<CheckoutAddress>,
}
#[derive(Debug, Serialize)]
pub struct MandateSource {
#[serde(rename = "type")]
pub source_type: CheckoutSourceTypes,
#[serde(rename = "id")]
pub source_id: Option<String>,
pub billing_address: Option<CheckoutAddress>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymentSource {
Card(CardSource),
Wallets(WalletSource),
ApplePayPredecrypt(Box<ApplePayPredecrypt>),
MandatePayment(MandateSource),
GooglePayPredecrypt(Box<GooglePayPredecrypt>),
}
#[derive(Debug, Serialize)]
pub struct GooglePayPredecrypt {
#[serde(rename = "type")]
_type: String,
token: cards::CardNumber,
token_type: String,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
eci: String,
cryptogram: Option<Secret<String>>,
pub billing_address: Option<CheckoutAddress>,
}
#[derive(Debug, Serialize)]
pub struct ApplePayPredecrypt {
token: cards::CardNumber,
#[serde(rename = "type")]
decrypt_type: String,
token_type: String,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
eci: Option<String>,
cryptogram: Secret<String>,
pub billing_address: Option<CheckoutAddress>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CheckoutSourceTypes {
Card,
Token,
#[serde(rename = "id")]
SourceId,
}
#[derive(Debug, Serialize)]
pub enum CheckoutPaymentType {
Regular,
Unscheduled,
#[serde(rename = "MOTO")]
Moto,
Installment,
Recurring,
}
pub struct CheckoutAuthType {
pub(super) api_key: Secret<String>,
pub(super) processing_channel_id: Secret<String>,
pub(super) api_secret: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct ReturnUrl {
pub success_url: Option<String>,
pub failure_url: Option<String>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutCustomer {
pub name: Option<Secret<String>>,
pub email: Option<common_utils::pii::Email>,
pub phone: Option<CheckoutPhoneDetails>,
pub tax_number: Option<Secret<String>>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutPhoneDetails {
pub country_code: Option<String>,
pub number: Option<Secret<String>>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutProcessing {
pub order_id: Option<String>,
pub tax_amount: Option<MinorUnit>,
pub discount_amount: Option<MinorUnit>,
pub duty_amount: Option<MinorUnit>,
pub shipping_amount: Option<MinorUnit>,
pub shipping_tax_amount: Option<MinorUnit>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutShipping {
pub address: Option<CheckoutAddress>,
pub from_address_zip: Option<String>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutLineItem {
pub commodity_code: Option<String>,
pub discount_amount: Option<MinorUnit>,
pub name: Option<String>,
pub quantity: Option<u16>,
pub reference: Option<String>,
pub tax_exempt: Option<bool>,
pub tax_amount: Option<MinorUnit>,
pub total_amount: Option<MinorUnit>,
pub unit_of_measure: Option<String>,
pub unit_price: Option<MinorUnit>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize)]
pub struct PaymentsRequest {
pub source: PaymentSource,
pub amount: MinorUnit,
pub currency: String,
pub processing_channel_id: Secret<String>,
#[serde(rename = "3ds")]
pub three_ds: CheckoutThreeDS,
#[serde(flatten)]
pub return_url: ReturnUrl,
pub capture: bool,
pub reference: String,
pub metadata: Option<Secret<serde_json::Value>>,
pub payment_type: CheckoutPaymentType,
pub merchant_initiated: Option<bool>,
pub previous_payment_id: Option<String>,
pub store_for_future_use: Option<bool>,
// Level 2/3 data fields
pub customer: Option<CheckoutCustomer>,
pub processing: Option<CheckoutProcessing>,
pub shipping: Option<CheckoutShipping>,
pub items: Option<Vec<CheckoutLineItem>>,
pub partial_authorization: Option<CheckoutPartialAuthorization>,
pub payment_ip: Option<Secret<String, common_utils::pii::IpAddress>>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutPartialAuthorization {
pub enabled: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckoutMeta {
pub psync_flow: CheckoutPaymentIntent,
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum CheckoutPaymentIntent {
Capture,
Authorize,
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum CheckoutChallengeIndicator {
NoPreference,
ChallengeRequestedMandate,
ChallengeRequested,
NoChallengeRequested,
}
#[derive(Debug, Serialize)]
pub struct CheckoutThreeDS {
enabled: bool,
force_3ds: bool,
eci: Option<String>,
cryptogram: Option<Secret<String>>,
xid: Option<String>,
version: Option<String>,
challenge_indicator: CheckoutChallengeIndicator,
}
impl TryFrom<&ConnectorAuthType> for CheckoutAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
api_secret,
key1,
} = auth_type
{
Ok(Self {
api_key: api_key.to_owned(),
api_secret: api_secret.to_owned(),
processing_channel_id: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
fn split_account_holder_name(
card_holder_name: Option<Secret<String>>,
) -> (Option<Secret<String>>, Option<Secret<String>>) {
let account_holder_name = card_holder_name
.as_ref()
.map(|name| name.clone().expose().trim().to_string());
match account_holder_name {
Some(name) if !name.is_empty() => match name.rsplit_once(' ') {
Some((first, last)) => (
Some(Secret::new(first.to_string())),
Some(Secret::new(last.to_string())),
),
None => (Some(Secret::new(name)), None),
},
_ => (None, None),
}
}
impl TryFrom<&CheckoutRouterData<&PaymentsAuthorizeRouterData>> for PaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CheckoutRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let capture = matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
);
let payment_type = if matches!(
item.router_data.request.payment_channel,
Some(PaymentChannel::MailOrder | PaymentChannel::TelephoneOrder)
) {
CheckoutPaymentType::Moto
} else if item.router_data.request.is_mandate_payment() {
CheckoutPaymentType::Unscheduled
} else {
CheckoutPaymentType::Regular
};
let (challenge_indicator, store_for_future_use) =
if item.router_data.request.is_mandate_payment() {
(
CheckoutChallengeIndicator::ChallengeRequestedMandate,
Some(true),
)
} else {
(CheckoutChallengeIndicator::ChallengeRequested, None)
};
let billing_details = Some(CheckoutAddress {
city: item.router_data.get_optional_billing_city(),
address_line1: item.router_data.get_optional_billing_line1(),
address_line2: item.router_data.get_optional_billing_line2(),
state: item.router_data.get_optional_billing_state(),
zip: item.router_data.get_optional_billing_zip(),
country: item.router_data.get_optional_billing_country(),
});
let (
source_var,
previous_payment_id,
merchant_initiated,
payment_type,
store_for_future_use,
) = match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => {
let (first_name, last_name) = split_account_holder_name(ccard.card_holder_name);
let payment_source = PaymentSource::Card(CardSource {
source_type: CheckoutSourceTypes::Card,
number: ccard.card_number.clone(),
expiry_month: ccard.card_exp_month.clone(),
expiry_year: ccard.card_exp_year.clone(),
cvv: Some(ccard.card_cvc),
billing_address: billing_details,
account_holder: Some(CheckoutAccountHolderDetails {
first_name,
last_name,
}),
});
Ok((
payment_source,
None,
Some(false),
payment_type,
store_for_future_use,
))
}
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::GooglePay(_) => {
let p_source = match item.router_data.get_payment_method_token()? {
PaymentMethodToken::Token(token) => PaymentSource::Wallets(WalletSource {
source_type: CheckoutSourceTypes::Token,
token,
billing_address: billing_details,
}),
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Checkout"),
)?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Checkout"))?
}
PaymentMethodToken::GooglePayDecrypt(google_pay_decrypted_data) => {
let token = google_pay_decrypted_data
.application_primary_account_number
.clone();
let expiry_month = google_pay_decrypted_data
.get_expiry_month()
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_month",
})?;
let expiry_year = google_pay_decrypted_data
.get_four_digit_expiry_year()
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_year",
})?;
let cryptogram = google_pay_decrypted_data.cryptogram.clone();
PaymentSource::GooglePayPredecrypt(Box::new(GooglePayPredecrypt {
_type: "network_token".to_string(),
token,
token_type: "googlepay".to_string(),
expiry_month,
expiry_year,
eci: "06".to_string(),
cryptogram,
billing_address: billing_details,
}))
}
};
Ok((
p_source,
None,
Some(false),
payment_type,
store_for_future_use,
))
}
WalletData::ApplePay(_) => {
let payment_method_token = item.router_data.get_payment_method_token()?;
match payment_method_token {
PaymentMethodToken::Token(apple_pay_payment_token) => {
let p_source = PaymentSource::Wallets(WalletSource {
source_type: CheckoutSourceTypes::Token,
token: apple_pay_payment_token,
billing_address: billing_details,
});
Ok((
p_source,
None,
Some(false),
payment_type,
store_for_future_use,
))
}
PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
let exp_month = decrypt_data.get_expiry_month().change_context(
errors::ConnectorError::InvalidDataFormat {
field_name: "expiration_month",
},
)?;
let expiry_year_4_digit = decrypt_data.get_four_digit_expiry_year();
let p_source =
PaymentSource::ApplePayPredecrypt(Box::new(ApplePayPredecrypt {
token: decrypt_data.application_primary_account_number,
decrypt_type: "network_token".to_string(),
token_type: "applepay".to_string(),
expiry_month: exp_month,
expiry_year: expiry_year_4_digit,
eci: decrypt_data.payment_data.eci_indicator,
cryptogram: decrypt_data.payment_data.online_payment_cryptogram,
billing_address: billing_details,
}));
Ok((
p_source,
None,
Some(false),
payment_type,
store_for_future_use,
))
}
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Checkout"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Checkout"))?
}
}
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)),
},
PaymentMethodData::MandatePayment => {
let mandate_source = PaymentSource::MandatePayment(MandateSource {
source_type: CheckoutSourceTypes::SourceId,
source_id: item.router_data.request.connector_mandate_id(),
billing_address: billing_details,
});
let previous_id = Some(
item.router_data
.request
.get_connector_mandate_request_reference_id()?,
);
let p_type = match item.router_data.request.mit_category {
Some(MitCategory::Installment) => CheckoutPaymentType::Installment,
Some(MitCategory::Recurring) => CheckoutPaymentType::Recurring,
Some(MitCategory::Unscheduled) | None => CheckoutPaymentType::Unscheduled,
_ => CheckoutPaymentType::Unscheduled,
};
Ok((mandate_source, previous_id, Some(true), p_type, None))
}
PaymentMethodData::CardDetailsForNetworkTransactionId(ccard) => {
let (first_name, last_name) = split_account_holder_name(ccard.card_holder_name);
let payment_source = PaymentSource::Card(CardSource {
source_type: CheckoutSourceTypes::Card,
number: ccard.card_number.clone(),
expiry_month: ccard.card_exp_month.clone(),
expiry_year: ccard.card_exp_year.clone(),
cvv: None,
billing_address: billing_details,
account_holder: Some(CheckoutAccountHolderDetails {
first_name,
last_name,
}),
});
let previous_id = Some(
item.router_data
.request
.get_optional_network_transaction_id()
.ok_or_else(utils::missing_field_err("network_transaction_id"))
.attach_printable("Checkout unable to find NTID for MIT")?,
);
let p_type = match item.router_data.request.mit_category {
Some(MitCategory::Installment) => CheckoutPaymentType::Installment,
Some(MitCategory::Recurring) => CheckoutPaymentType::Recurring,
Some(MitCategory::Unscheduled) | None => CheckoutPaymentType::Unscheduled,
_ => CheckoutPaymentType::Unscheduled,
};
Ok((payment_source, previous_id, Some(true), p_type, None))
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)),
}?;
let authentication_data = item.router_data.request.authentication_data.as_ref();
let three_ds = match item.router_data.auth_type {
enums::AuthenticationType::ThreeDs => CheckoutThreeDS {
enabled: true,
force_3ds: true,
eci: authentication_data.and_then(|auth| auth.eci.clone()),
cryptogram: authentication_data.map(|auth| auth.cavv.clone()),
xid: authentication_data
.and_then(|auth| auth.threeds_server_transaction_id.clone()),
version: authentication_data.and_then(|auth| {
auth.message_version
.clone()
.map(|version| version.to_string())
}),
challenge_indicator,
},
enums::AuthenticationType::NoThreeDs => CheckoutThreeDS {
enabled: false,
force_3ds: false,
eci: None,
cryptogram: None,
xid: None,
version: None,
challenge_indicator: CheckoutChallengeIndicator::NoPreference,
},
};
let return_url = ReturnUrl {
success_url: item
.router_data
.request
.router_return_url
.as_ref()
.map(|return_url| format!("{return_url}?status=success")),
failure_url: item
.router_data
.request
.router_return_url
.as_ref()
.map(|return_url| format!("{return_url}?status=failure")),
};
let connector_auth = &item.router_data.connector_auth_type;
let auth_type: CheckoutAuthType = connector_auth.try_into()?;
let processing_channel_id = auth_type.processing_channel_id;
let metadata = item.router_data.request.metadata.clone().map(Into::into);
let (customer, processing, shipping, items) = if let Some(l2l3_data) =
&item.router_data.l2_l3_data
{
(
Some(CheckoutCustomer {
name: l2l3_data.customer_name.clone(),
email: l2l3_data.customer_email.clone(),
phone: Some(CheckoutPhoneDetails {
country_code: l2l3_data.customer_phone_country_code.clone(),
number: l2l3_data.customer_phone_number.clone(),
}),
tax_number: l2l3_data.customer_tax_registration_id.clone(),
}),
Some(CheckoutProcessing {
order_id: l2l3_data.merchant_order_reference_id.clone(),
tax_amount: l2l3_data.order_tax_amount,
discount_amount: l2l3_data.discount_amount,
duty_amount: l2l3_data.duty_amount,
shipping_amount: l2l3_data.shipping_cost,
shipping_tax_amount: l2l3_data.shipping_amount_tax,
}),
Some(CheckoutShipping {
address: Some(CheckoutAddress {
country: l2l3_data.get_shipping_country(),
address_line1: l2l3_data.get_shipping_address_line1(),
address_line2: l2l3_data.get_shipping_address_line2(),
city: l2l3_data.get_shipping_city(),
state: l2l3_data.get_shipping_state(),
zip: l2l3_data.get_shipping_zip(),
}),
from_address_zip: l2l3_data.get_shipping_origin_zip().map(|zip| zip.expose()),
}),
l2l3_data.order_details.as_ref().map(|details| {
details
.iter()
.map(|item| CheckoutLineItem {
commodity_code: item.commodity_code.clone(),
discount_amount: item.unit_discount_amount,
name: Some(item.product_name.clone()),
quantity: Some(item.quantity),
reference: item.product_id.clone(),
tax_exempt: None,
tax_amount: item.total_tax_amount,
total_amount: item.total_amount,
unit_of_measure: item.unit_of_measure.clone(),
unit_price: Some(item.amount),
})
.collect()
}),
)
} else {
(None, None, None, None)
};
let partial_authorization = item.router_data.request.enable_partial_authorization.map(
|enable_partial_authorization| CheckoutPartialAuthorization {
enabled: *enable_partial_authorization,
},
);
let payment_ip = item.router_data.request.get_ip_address_as_optional();
let request = Self {
source: source_var,
amount: item.amount.to_owned(),
currency: item.router_data.request.currency.to_string(),
processing_channel_id,
three_ds,
return_url,
capture,
reference: item.router_data.connector_request_reference_id.clone(),
metadata,
payment_type,
merchant_initiated,
previous_payment_id,
store_for_future_use,
customer,
processing,
shipping,
items,
partial_authorization,
payment_ip,
};
Ok(request)
}
}
#[derive(Default, Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub enum CheckoutPaymentStatus {
Authorized,
#[default]
Pending,
#[serde(rename = "Card Verified")]
CardVerified,
Declined,
Captured,
#[serde(rename = "Retry Scheduled")]
RetryScheduled,
Voided,
#[serde(rename = "Partially Captured")]
PartiallyCaptured,
#[serde(rename = "Partially Refunded")]
PartiallyRefunded,
Refunded,
Canceled,
Expired,
}
impl TryFrom<CheckoutWebhookEventType> for CheckoutPaymentStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: CheckoutWebhookEventType) -> Result<Self, Self::Error> {
match value {
CheckoutWebhookEventType::PaymentApproved => Ok(Self::Authorized),
CheckoutWebhookEventType::PaymentCaptured => Ok(Self::Captured),
CheckoutWebhookEventType::PaymentDeclined => Ok(Self::Declined),
CheckoutWebhookEventType::AuthenticationStarted
| CheckoutWebhookEventType::AuthenticationApproved
| CheckoutWebhookEventType::AuthenticationAttempted => Ok(Self::Pending),
CheckoutWebhookEventType::AuthenticationExpired
| CheckoutWebhookEventType::AuthenticationFailed
| CheckoutWebhookEventType::PaymentAuthenticationFailed
| CheckoutWebhookEventType::PaymentCaptureDeclined => Ok(Self::Declined),
CheckoutWebhookEventType::PaymentCanceled => Ok(Self::Canceled),
CheckoutWebhookEventType::PaymentVoided => Ok(Self::Voided),
CheckoutWebhookEventType::PaymentRefunded
| CheckoutWebhookEventType::PaymentRefundDeclined
| CheckoutWebhookEventType::DisputeReceived
| CheckoutWebhookEventType::DisputeExpired
| CheckoutWebhookEventType::DisputeAccepted
| CheckoutWebhookEventType::DisputeCanceled
| CheckoutWebhookEventType::DisputeEvidenceSubmitted
| CheckoutWebhookEventType::DisputeEvidenceAcknowledgedByScheme
| CheckoutWebhookEventType::DisputeEvidenceRequired
| CheckoutWebhookEventType::DisputeArbitrationLost
| CheckoutWebhookEventType::DisputeArbitrationWon
| CheckoutWebhookEventType::DisputeWon
| CheckoutWebhookEventType::DisputeLost
| CheckoutWebhookEventType::Unknown => {
Err(errors::ConnectorError::WebhookEventTypeNotFound.into())
}
}
}
}
fn get_attempt_status_cap(
item: (CheckoutPaymentStatus, Option<enums::CaptureMethod>),
) -> AttemptStatus {
let (status, capture_method) = item;
match status {
CheckoutPaymentStatus::Authorized => {
if capture_method == Some(enums::CaptureMethod::Automatic) || capture_method.is_none() {
AttemptStatus::Charged
} else {
AttemptStatus::Authorized
}
}
CheckoutPaymentStatus::Captured
| CheckoutPaymentStatus::PartiallyRefunded
| CheckoutPaymentStatus::Refunded
| CheckoutPaymentStatus::CardVerified => AttemptStatus::Charged,
CheckoutPaymentStatus::PartiallyCaptured => AttemptStatus::PartialCharged,
CheckoutPaymentStatus::Declined
| CheckoutPaymentStatus::Expired
| CheckoutPaymentStatus::Canceled => AttemptStatus::Failure,
CheckoutPaymentStatus::Pending => AttemptStatus::AuthenticationPending,
CheckoutPaymentStatus::RetryScheduled => AttemptStatus::Pending,
CheckoutPaymentStatus::Voided => AttemptStatus::Voided,
}
}
fn get_attempt_status_intent(
item: (CheckoutPaymentStatus, CheckoutPaymentIntent),
) -> AttemptStatus {
let (status, psync_flow) = item;
match status {
CheckoutPaymentStatus::Authorized => {
if psync_flow == CheckoutPaymentIntent::Capture {
AttemptStatus::Charged
} else {
AttemptStatus::Authorized
}
}
CheckoutPaymentStatus::Captured
| CheckoutPaymentStatus::PartiallyRefunded
| CheckoutPaymentStatus::Refunded
| CheckoutPaymentStatus::CardVerified => AttemptStatus::Charged,
CheckoutPaymentStatus::PartiallyCaptured => AttemptStatus::PartialCharged,
CheckoutPaymentStatus::Declined
| CheckoutPaymentStatus::Expired
| CheckoutPaymentStatus::Canceled => AttemptStatus::Failure,
CheckoutPaymentStatus::Pending => AttemptStatus::AuthenticationPending,
CheckoutPaymentStatus::RetryScheduled => AttemptStatus::Pending,
CheckoutPaymentStatus::Voided => AttemptStatus::Voided,
}
}
fn get_attempt_status_bal(item: (CheckoutPaymentStatus, Option<Balances>)) -> AttemptStatus {
let (status, balances) = item;
match status {
CheckoutPaymentStatus::Authorized => {
if let Some(Balances {
available_to_capture: 0,
}) = balances
{
AttemptStatus::Charged
} else {
AttemptStatus::Authorized
}
}
CheckoutPaymentStatus::Captured
| CheckoutPaymentStatus::PartiallyRefunded
| CheckoutPaymentStatus::Refunded => AttemptStatus::Charged,
CheckoutPaymentStatus::PartiallyCaptured => AttemptStatus::PartialCharged,
CheckoutPaymentStatus::Declined
| CheckoutPaymentStatus::Expired
| CheckoutPaymentStatus::Canceled => AttemptStatus::Failure,
CheckoutPaymentStatus::Pending => AttemptStatus::AuthenticationPending,
CheckoutPaymentStatus::CardVerified | CheckoutPaymentStatus::RetryScheduled => {
AttemptStatus::Pending
}
CheckoutPaymentStatus::Voided => AttemptStatus::Voided,
}
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Href {
#[serde(rename = "href")]
redirection_url: Url,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct Links {
redirect: Option<Href>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct Source {
id: Option<String>,
avs_check: Option<String>,
cvv_check: Option<String>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct PaymentsResponse {
id: String,
amount: Option<MinorUnit>,
currency: Option<String>,
scheme_id: Option<String>,
processing: Option<PaymentProcessingDetails>,
action_id: Option<String>,
status: CheckoutPaymentStatus,
#[serde(rename = "_links")]
links: Links,
balances: Option<Balances>,
reference: Option<String>,
response_code: Option<String>,
response_summary: Option<String>,
approved: Option<bool>,
processed_on: Option<String>,
source: Option<Source>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct PaymentProcessingDetails {
/// The Merchant Advice Code (MAC) provided by Mastercard, which contains additional information about the transaction.
pub partner_merchant_advice_code: Option<String>,
/// The original authorization response code sent by the scheme.
pub partner_response_code: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum PaymentsResponseEnum {
ActionResponse(Vec<ActionResponse>),
PaymentResponse(Box<PaymentsResponse>),
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct Balances {
available_to_capture: i32,
}
fn get_connector_meta(
capture_method: enums::CaptureMethod,
) -> CustomResult<serde_json::Value, errors::ConnectorError> {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::SequentialAutomatic => {
Ok(serde_json::json!(CheckoutMeta {
psync_flow: CheckoutPaymentIntent::Capture,
}))
}
enums::CaptureMethod::Manual | enums::CaptureMethod::ManualMultiple => {
Ok(serde_json::json!(CheckoutMeta {
psync_flow: CheckoutPaymentIntent::Authorize,
}))
}
enums::CaptureMethod::Scheduled => {
Err(errors::ConnectorError::CaptureMethodNotSupported.into())
}
}
}
impl TryFrom<PaymentsResponseRouterData<PaymentsResponse>> for PaymentsAuthorizeRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: PaymentsResponseRouterData<PaymentsResponse>) -> Result<Self, Self::Error> {
let status =
get_attempt_status_cap((item.response.status, item.data.request.capture_method));
if status == AttemptStatus::Failure {
let error_response = ErrorResponse {
status_code: item.http_code,
code: item
.response
.response_code
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: item
.response
.response_summary
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: item.response.response_summary,
attempt_status: None,
connector_transaction_id: Some(item.response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
};
return Ok(Self {
status,
response: Err(error_response),
..item.data
});
}
let connector_meta =
get_connector_meta(item.data.request.capture_method.unwrap_or_default())?;
let redirection_data = item
.response
.links
.redirect
.map(|href| RedirectForm::from((href.redirection_url, Method::Get)));
let mandate_reference = if item.data.request.is_mandate_payment() {
item.response
.source
.as_ref()
.and_then(|src| src.id.clone())
.map(|id| MandateReference {
connector_mandate_id: Some(id),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: Some(item.response.id.clone()),
})
} else {
None
};
let additional_information =
convert_to_additional_payment_method_connector_response(item.response.source.as_ref())
.map(ConnectorResponseData::with_additional_payment_method_data);
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: Some(connector_meta),
network_txn_id: item.response.scheme_id.clone(),
connector_response_reference_id: Some(
item.response.reference.unwrap_or(item.response.id),
),
incremental_authorization_allowed: None,
charges: None,
};
let (amount_captured, minor_amount_capturable) = match item.data.request.capture_method {
Some(enums::CaptureMethod::Manual) | Some(enums::CaptureMethod::ManualMultiple) => {
(None, item.response.amount)
}
_ => (item.response.amount.map(MinorUnit::get_amount_as_i64), None),
};
let authorized_amount = item
.data
.request
.enable_partial_authorization
.filter(|flag| flag.is_true())
.and(item.response.amount);
Ok(Self {
status,
response: Ok(payments_response_data),
connector_response: additional_information,
authorized_amount,
amount_captured,
minor_amount_capturable,
..item.data
})
}
}
impl
TryFrom<
ResponseRouterData<
SetupMandate,
PaymentsResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
> for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
SetupMandate,
PaymentsResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let connector_meta =
get_connector_meta(item.data.request.capture_method.unwrap_or_default())?;
let redirection_data = item
.response
.links
.redirect
.map(|href| RedirectForm::from((href.redirection_url, Method::Get)));
let status =
get_attempt_status_cap((item.response.status, item.data.request.capture_method));
let network_advice_code = item
.response
.processing
.as_ref()
.and_then(|processing| {
processing
.partner_merchant_advice_code
.as_ref()
.or(processing.partner_response_code.as_ref())
})
.cloned();
let error_response = if status == AttemptStatus::Failure {
Some(ErrorResponse {
status_code: item.http_code,
code: item
.response
.response_code
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: item
.response
.response_summary
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: item.response.response_summary,
attempt_status: None,
connector_transaction_id: Some(item.response.id.clone()),
network_advice_code,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
let mandate_reference = item
.response
.source
.as_ref()
.and_then(|src| src.id.clone())
.map(|id| MandateReference {
connector_mandate_id: Some(id),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: Some(item.response.id.clone()),
});
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: Some(connector_meta),
network_txn_id: item.response.scheme_id.clone(),
connector_response_reference_id: Some(
item.response.reference.unwrap_or(item.response.id),
),
incremental_authorization_allowed: None,
charges: None,
};
Ok(Self {
status,
response: error_response.map_or_else(|| Ok(payments_response_data), Err),
..item.data
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<PaymentsResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<PaymentsResponse>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.links
.redirect
.map(|href| RedirectForm::from((href.redirection_url, Method::Get)));
let checkout_meta: CheckoutMeta =
utils::to_connector_meta(item.data.request.connector_meta.clone())?;
let status = get_attempt_status_intent((item.response.status, checkout_meta.psync_flow));
let error_response = if status == AttemptStatus::Failure {
Some(ErrorResponse {
status_code: item.http_code,
code: item
.response
.response_code
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: item
.response
.response_summary
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: item.response.response_summary,
attempt_status: None,
connector_transaction_id: Some(item.response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
let mandate_reference = if item.data.request.is_mandate_payment() {
item.response
.source
.as_ref()
.and_then(|src| src.id.clone())
.map(|id| MandateReference {
connector_mandate_id: Some(id),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: Some(item.response.id.clone()),
})
} else {
None
};
let additional_information =
convert_to_additional_payment_method_connector_response(item.response.source.as_ref())
.map(ConnectorResponseData::with_additional_payment_method_data);
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: item.response.scheme_id.clone(),
connector_response_reference_id: Some(
item.response.reference.unwrap_or(item.response.id),
),
incremental_authorization_allowed: None,
charges: None,
};
Ok(Self {
status,
response: error_response.map_or_else(|| Ok(payments_response_data), Err),
connector_response: additional_information,
..item.data
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<PaymentsResponseEnum>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<PaymentsResponseEnum>,
) -> Result<Self, Self::Error> {
let capture_sync_response_list = match item.response {
PaymentsResponseEnum::PaymentResponse(payments_response) => {
// for webhook consumption flow
utils::construct_captures_response_hashmap(vec![payments_response])?
}
PaymentsResponseEnum::ActionResponse(action_list) => {
// for captures sync
utils::construct_captures_response_hashmap(action_list)?
}
};
Ok(Self {
response: Ok(PaymentsResponseData::MultipleCaptureResponse {
capture_sync_response_list,
}),
..item.data
})
}
}
#[derive(Clone, Default, Debug, Eq, PartialEq, Serialize)]
pub struct PaymentVoidRequest {
reference: String,
}
#[derive(Clone, Default, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct PaymentVoidResponse {
#[serde(skip)]
pub(super) status: u16,
action_id: String,
reference: String,
scheme_id: Option<String>,
}
impl From<&PaymentVoidResponse> for AttemptStatus {
fn from(item: &PaymentVoidResponse) -> Self {
if item.status == 202 {
Self::Voided
} else {
Self::VoidFailed
}
}
}
impl TryFrom<PaymentsCancelResponseRouterData<PaymentVoidResponse>> for PaymentsCancelRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<PaymentVoidResponse>,
) -> Result<Self, Self::Error> {
let response = &item.response;
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.action_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: item.response.scheme_id.clone(),
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
status: response.into(),
..item.data
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for PaymentVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Ok(Self {
reference: item.request.connector_transaction_id.clone(),
})
}
}
#[derive(Debug, Serialize)]
pub enum CaptureType {
Final,
NonFinal,
}
#[derive(Debug, Serialize)]
pub struct PaymentCaptureRequest {
pub amount: Option<MinorUnit>,
pub capture_type: Option<CaptureType>,
pub processing_channel_id: Secret<String>,
pub reference: Option<String>,
}
impl TryFrom<&CheckoutRouterData<&PaymentsCaptureRouterData>> for PaymentCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CheckoutRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let connector_auth = &item.router_data.connector_auth_type;
let auth_type: CheckoutAuthType = connector_auth.try_into()?;
let processing_channel_id = auth_type.processing_channel_id;
let capture_type = if item.router_data.request.is_multiple_capture() {
CaptureType::NonFinal
} else {
CaptureType::Final
};
let reference = item
.router_data
.request
.multiple_capture_data
.as_ref()
.map(|multiple_capture_data| multiple_capture_data.capture_reference.clone());
Ok(Self {
amount: Some(item.amount.to_owned()),
capture_type: Some(capture_type),
processing_channel_id,
reference, // hyperswitch's reference for this capture
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaymentCaptureResponse {
pub action_id: String,
pub reference: Option<String>,
pub scheme_id: Option<String>,
}
impl TryFrom<PaymentsCaptureResponseRouterData<PaymentCaptureResponse>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<PaymentCaptureResponse>,
) -> Result<Self, Self::Error> {
let connector_meta = serde_json::json!(CheckoutMeta {
psync_flow: CheckoutPaymentIntent::Capture,
});
let (status, amount_captured) = if item.http_code == 202 {
(
AttemptStatus::Charged,
Some(item.data.request.amount_to_capture),
)
} else {
(AttemptStatus::Pending, None)
};
// if multiple capture request, return capture action_id so that it will be updated in the captures table.
// else return previous connector_transaction_id.
let resource_id = if item.data.request.is_multiple_capture() {
item.response.action_id
} else {
item.data.request.connector_transaction_id.to_owned()
};
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(resource_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: item.response.scheme_id.clone(),
connector_response_reference_id: item.response.reference,
incremental_authorization_allowed: None,
charges: None,
}),
status,
amount_captured,
..item.data
})
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RefundRequest {
amount: Option<MinorUnit>,
reference: String,
}
impl<F> TryFrom<&CheckoutRouterData<&RefundsRouterData<F>>> for RefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &CheckoutRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let reference = item.router_data.request.refund_id.clone();
Ok(Self {
amount: Some(item.amount.to_owned()),
reference,
})
}
}
#[allow(dead_code)]
#[derive(Deserialize, Debug, Serialize)]
pub struct RefundResponse {
action_id: String,
reference: String,
}
#[derive(Deserialize)]
pub struct CheckoutRefundResponse {
pub(super) status: u16,
pub(super) response: RefundResponse,
}
impl From<&CheckoutRefundResponse> for enums::RefundStatus {
fn from(item: &CheckoutRefundResponse) -> Self {
if item.status == 202 {
Self::Success
} else {
Self::Failure
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, CheckoutRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, CheckoutRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(&item.response);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.response.action_id.clone(),
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, CheckoutRefundResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, CheckoutRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(&item.response);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.response.action_id.clone(),
refund_status,
}),
..item.data
})
}
}
#[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct CheckoutErrorResponse {
pub request_id: Option<String>,
pub error_type: Option<String>,
pub error_codes: Option<Vec<String>>,
}
#[derive(Deserialize, Debug, PartialEq, Serialize)]
pub enum ActionType {
Authorization,
Void,
Capture,
Refund,
Payout,
Return,
#[serde(rename = "Card Verification")]
CardVerification,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct ActionResponse {
#[serde(rename = "id")]
pub action_id: String,
pub amount: MinorUnit,
#[serde(rename = "type")]
pub action_type: ActionType,
pub approved: Option<bool>,
pub reference: Option<String>,
}
impl From<&ActionResponse> for enums::RefundStatus {
fn from(item: &ActionResponse) -> Self {
match item.approved {
Some(true) => Self::Success,
Some(false) => Self::Failure,
None => Self::Pending,
}
}
}
impl utils::MultipleCaptureSyncResponse for ActionResponse {
fn get_connector_capture_id(&self) -> String {
self.action_id.clone()
}
fn get_capture_attempt_status(&self) -> AttemptStatus {
match self.approved {
Some(true) => AttemptStatus::Charged,
Some(false) => AttemptStatus::Failure,
None => AttemptStatus::Pending,
}
}
fn get_connector_reference_id(&self) -> Option<String> {
self.reference.clone()
}
fn is_capture_response(&self) -> bool {
self.action_type == ActionType::Capture
}
fn get_amount_captured(&self) -> Result<Option<MinorUnit>, error_stack::Report<ParsingError>> {
Ok(Some(self.amount))
}
}
impl utils::MultipleCaptureSyncResponse for Box<PaymentsResponse> {
fn get_connector_capture_id(&self) -> String {
self.action_id.clone().unwrap_or("".into())
}
fn get_capture_attempt_status(&self) -> AttemptStatus {
get_attempt_status_bal((self.status.clone(), self.balances.clone()))
}
fn get_connector_reference_id(&self) -> Option<String> {
self.reference.clone()
}
fn is_capture_response(&self) -> bool {
self.status == CheckoutPaymentStatus::Captured
}
fn get_amount_captured(&self) -> Result<Option<MinorUnit>, error_stack::Report<ParsingError>> {
Ok(self.amount)
}
}
#[derive(Debug, Clone, serde::Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CheckoutRedirectResponseStatus {
Success,
Failure,
}
#[derive(Debug, Clone, serde::Deserialize, Eq, PartialEq)]
pub struct CheckoutRedirectResponse {
pub status: Option<CheckoutRedirectResponseStatus>,
#[serde(rename = "cko-session-id")]
pub cko_session_id: Option<String>,
}
impl TryFrom<RefundsResponseRouterData<Execute, &ActionResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, &ActionResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.action_id.clone(),
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, &ActionResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, &ActionResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.action_id.clone(),
refund_status,
}),
..item.data
})
}
}
impl From<CheckoutRedirectResponseStatus> for AttemptStatus {
fn from(item: CheckoutRedirectResponseStatus) -> Self {
match item {
CheckoutRedirectResponseStatus::Success => Self::AuthenticationSuccessful,
CheckoutRedirectResponseStatus::Failure => Self::Failure,
}
}
}
pub fn is_refund_event(event_code: &CheckoutWebhookEventType) -> bool {
matches!(
event_code,
CheckoutWebhookEventType::PaymentRefunded | CheckoutWebhookEventType::PaymentRefundDeclined
)
}
pub fn is_chargeback_event(event_code: &CheckoutWebhookEventType) -> bool {
matches!(
event_code,
CheckoutWebhookEventType::DisputeReceived
| CheckoutWebhookEventType::DisputeExpired
| CheckoutWebhookEventType::DisputeAccepted
| CheckoutWebhookEventType::DisputeCanceled
| CheckoutWebhookEventType::DisputeEvidenceSubmitted
| CheckoutWebhookEventType::DisputeEvidenceAcknowledgedByScheme
| CheckoutWebhookEventType::DisputeEvidenceRequired
| CheckoutWebhookEventType::DisputeArbitrationLost
| CheckoutWebhookEventType::DisputeArbitrationWon
| CheckoutWebhookEventType::DisputeWon
| CheckoutWebhookEventType::DisputeLost
)
}
#[derive(Debug, Deserialize, strum::Display, Clone)]
#[serde(rename_all = "snake_case")]
pub enum CheckoutWebhookEventType {
AuthenticationStarted,
AuthenticationApproved,
AuthenticationAttempted,
AuthenticationExpired,
AuthenticationFailed,
PaymentApproved,
PaymentCaptured,
PaymentDeclined,
PaymentRefunded,
PaymentRefundDeclined,
PaymentAuthenticationFailed,
PaymentCanceled,
PaymentCaptureDeclined,
PaymentVoided,
DisputeReceived,
DisputeExpired,
DisputeAccepted,
DisputeCanceled,
DisputeEvidenceSubmitted,
DisputeEvidenceAcknowledgedByScheme,
DisputeEvidenceRequired,
DisputeArbitrationLost,
DisputeArbitrationWon,
DisputeWon,
DisputeLost,
#[serde(other)]
Unknown,
}
#[derive(Debug, Deserialize)]
pub struct CheckoutWebhookEventTypeBody {
#[serde(rename = "type")]
pub transaction_type: CheckoutWebhookEventType,
}
#[derive(Debug, Deserialize)]
pub struct CheckoutWebhookData {
pub id: String,
pub payment_id: Option<String>,
pub action_id: Option<String>,
pub reference: Option<String>,
pub amount: MinorUnit,
pub balances: Option<Balances>,
pub response_code: Option<String>,
pub response_summary: Option<String>,
pub currency: String,
pub processed_on: Option<String>,
pub approved: Option<bool>,
}
#[derive(Debug, Deserialize)]
pub struct CheckoutWebhookBody {
#[serde(rename = "type")]
pub transaction_type: CheckoutWebhookEventType,
pub data: CheckoutWebhookData,
#[serde(rename = "_links")]
pub links: Links,
pub source: Option<Source>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckoutDisputeWebhookData {
pub id: String,
pub payment_id: Option<String>,
pub action_id: Option<String>,
pub amount: MinorUnit,
pub currency: enums::Currency,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub evidence_required_by: Option<PrimitiveDateTime>,
pub reason_code: Option<String>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub date: Option<PrimitiveDateTime>,
}
#[derive(Debug, Deserialize)]
pub struct CheckoutDisputeWebhookBody {
#[serde(rename = "type")]
pub transaction_type: CheckoutDisputeTransactionType,
pub data: CheckoutDisputeWebhookData,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub created_on: Option<PrimitiveDateTime>,
}
#[derive(Debug, Deserialize, strum::Display, Clone)]
#[serde(rename_all = "snake_case")]
pub enum CheckoutDisputeTransactionType {
DisputeReceived,
DisputeExpired,
DisputeAccepted,
DisputeCanceled,
DisputeEvidenceSubmitted,
DisputeEvidenceAcknowledgedByScheme,
DisputeEvidenceRequired,
DisputeArbitrationLost,
DisputeArbitrationWon,
DisputeWon,
DisputeLost,
}
impl From<CheckoutWebhookEventType> for api_models::webhooks::IncomingWebhookEvent {
fn from(transaction_type: CheckoutWebhookEventType) -> Self {
match transaction_type {
CheckoutWebhookEventType::AuthenticationStarted
| CheckoutWebhookEventType::AuthenticationApproved
| CheckoutWebhookEventType::AuthenticationAttempted => Self::EventNotSupported,
CheckoutWebhookEventType::AuthenticationExpired
| CheckoutWebhookEventType::AuthenticationFailed
| CheckoutWebhookEventType::PaymentAuthenticationFailed => {
Self::PaymentIntentAuthorizationFailure
}
CheckoutWebhookEventType::PaymentApproved => Self::EventNotSupported,
CheckoutWebhookEventType::PaymentCaptured => Self::PaymentIntentSuccess,
CheckoutWebhookEventType::PaymentDeclined => Self::PaymentIntentFailure,
CheckoutWebhookEventType::PaymentRefunded => Self::RefundSuccess,
CheckoutWebhookEventType::PaymentRefundDeclined => Self::RefundFailure,
CheckoutWebhookEventType::PaymentCanceled => Self::PaymentIntentCancelFailure,
CheckoutWebhookEventType::PaymentCaptureDeclined => Self::PaymentIntentCaptureFailure,
CheckoutWebhookEventType::PaymentVoided => Self::PaymentIntentCancelled,
CheckoutWebhookEventType::DisputeReceived
| CheckoutWebhookEventType::DisputeEvidenceRequired => Self::DisputeOpened,
CheckoutWebhookEventType::DisputeExpired => Self::DisputeExpired,
CheckoutWebhookEventType::DisputeAccepted => Self::DisputeAccepted,
CheckoutWebhookEventType::DisputeCanceled => Self::DisputeCancelled,
CheckoutWebhookEventType::DisputeEvidenceSubmitted
| CheckoutWebhookEventType::DisputeEvidenceAcknowledgedByScheme => {
Self::DisputeChallenged
}
CheckoutWebhookEventType::DisputeWon
| CheckoutWebhookEventType::DisputeArbitrationWon => Self::DisputeWon,
CheckoutWebhookEventType::DisputeLost
| CheckoutWebhookEventType::DisputeArbitrationLost => Self::DisputeLost,
CheckoutWebhookEventType::Unknown => Self::EventNotSupported,
}
}
}
impl From<CheckoutDisputeTransactionType> for api_models::enums::DisputeStage {
fn from(code: CheckoutDisputeTransactionType) -> Self {
match code {
CheckoutDisputeTransactionType::DisputeArbitrationLost
| CheckoutDisputeTransactionType::DisputeArbitrationWon => Self::PreArbitration,
CheckoutDisputeTransactionType::DisputeReceived
| CheckoutDisputeTransactionType::DisputeExpired
| CheckoutDisputeTransactionType::DisputeAccepted
| CheckoutDisputeTransactionType::DisputeCanceled
| CheckoutDisputeTransactionType::DisputeEvidenceSubmitted
| CheckoutDisputeTransactionType::DisputeEvidenceAcknowledgedByScheme
| CheckoutDisputeTransactionType::DisputeEvidenceRequired
| CheckoutDisputeTransactionType::DisputeWon
| CheckoutDisputeTransactionType::DisputeLost => Self::Dispute,
}
}
}
#[derive(Debug, Deserialize)]
pub struct CheckoutWebhookObjectResource {
pub data: serde_json::Value,
}
#[derive(Debug, Serialize)]
pub struct CheckoutFileRequest {
pub purpose: &'static str,
#[serde(skip)]
pub file: Vec<u8>,
#[serde(skip)]
pub file_key: String,
#[serde(skip)]
pub file_type: String,
}
pub fn construct_file_upload_request(
file_upload_router_data: UploadFileRouterData,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let request = file_upload_router_data.request;
let checkout_file_request = CheckoutFileRequest {
purpose: "dispute_evidence",
file: request.file.clone(),
file_key: request.file_key.clone(),
file_type: request.file_type.to_string(),
};
let mut multipart = reqwest::multipart::Form::new();
multipart = multipart.text("purpose", "dispute_evidence");
let file_data = reqwest::multipart::Part::bytes(request.file)
.file_name(format!(
"{}.{}",
request.file_key,
request
.file_type
.as_ref()
.split('/')
.next_back()
.unwrap_or_default()
))
.mime_str(request.file_type.as_ref())
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failure in constructing file data")?;
multipart = multipart.part("file", file_data);
Ok(RequestContent::FormData((
multipart,
Box::new(checkout_file_request),
)))
}
#[derive(Debug, Deserialize, Serialize)]
pub struct FileUploadResponse {
#[serde(rename = "id")]
pub file_id: String,
}
#[derive(Default, Debug, Serialize)]
pub struct Evidence {
pub proof_of_delivery_or_service_file: Option<String>,
pub invoice_or_receipt_file: Option<String>,
pub invoice_showing_distinct_transactions_file: Option<String>,
pub customer_communication_file: Option<String>,
pub refund_or_cancellation_policy_file: Option<String>,
pub recurring_transaction_agreement_file: Option<String>,
pub additional_evidence_file: Option<String>,
}
impl TryFrom<&webhooks::IncomingWebhookRequestDetails<'_>> for PaymentsResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> Result<Self, Self::Error> {
let details: CheckoutWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let data = details.data;
let psync_struct = Self {
id: data.payment_id.unwrap_or(data.id),
amount: Some(data.amount),
status: CheckoutPaymentStatus::try_from(details.transaction_type)?,
links: details.links,
balances: data.balances,
reference: data.reference,
response_code: data.response_code,
response_summary: data.response_summary,
action_id: data.action_id,
currency: Some(data.currency),
processed_on: data.processed_on,
approved: data.approved,
source: Some(Source {
id: details.source.clone().and_then(|src| src.id),
avs_check: details.source.clone().and_then(|src| src.avs_check),
cvv_check: details.source.clone().and_then(|src| src.cvv_check),
}),
scheme_id: None,
processing: None,
};
Ok(psync_struct)
}
}
impl TryFrom<&webhooks::IncomingWebhookRequestDetails<'_>> for RefundResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> Result<Self, Self::Error> {
let details: CheckoutWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let data = details.data;
let refund_struct = Self {
action_id: data
.action_id
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?,
reference: data
.reference
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?,
};
Ok(refund_struct)
}
}
impl TryFrom<&SubmitEvidenceRouterData> for Evidence {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SubmitEvidenceRouterData) -> Result<Self, Self::Error> {
let submit_evidence_request_data = item.request.clone();
Ok(Self {
proof_of_delivery_or_service_file: submit_evidence_request_data
.shipping_documentation_provider_file_id,
invoice_or_receipt_file: submit_evidence_request_data.receipt_provider_file_id,
invoice_showing_distinct_transactions_file: submit_evidence_request_data
.invoice_showing_distinct_transactions_provider_file_id,
customer_communication_file: submit_evidence_request_data
.customer_communication_provider_file_id,
refund_or_cancellation_policy_file: submit_evidence_request_data
.refund_policy_provider_file_id,
recurring_transaction_agreement_file: submit_evidence_request_data
.recurring_transaction_agreement_provider_file_id,
additional_evidence_file: submit_evidence_request_data
.uncategorized_file_provider_file_id,
})
}
}
impl From<String> for utils::ErrorCodeAndMessage {
fn from(error: String) -> Self {
Self {
error_code: error.clone(),
error_message: error,
}
}
}
fn convert_to_additional_payment_method_connector_response(
source: Option<&Source>,
) -> Option<AdditionalPaymentMethodConnectorResponse> {
source.map(|code| {
let payment_checks = serde_json::json!({
"avs_result": code.avs_check,
"card_validation_result": code.cvv_check,
});
AdditionalPaymentMethodConnectorResponse::Card {
authentication_data: None,
payment_checks: Some(payment_checks),
card_network: None,
domestic_network: None,
}
})
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 15176
}
|
large_file_-2306161096919918784
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
</path>
<file>
use cards::CardNumber;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::{OptionExt, ValueExt},
pii::{self},
request::Method,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{
BankDebitData, BankRedirectData, BankTransferData, Card, CardRedirectData, GiftCardData,
PayLaterData, PaymentMethodData, VoucherData, WalletData,
},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{BrowserInformation, ResponseId},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
use hyperswitch_interfaces::{
api,
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use ring::digest;
use serde::{Deserialize, Serialize};
use strum::Display;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, BrowserInformationData, CardData, ForeignTryFrom, PaymentsAuthorizeRequestData,
RouterData as _,
},
};
#[derive(Debug, Serialize)]
pub struct ZenRouterData<T> {
pub amount: String,
pub router_data: T,
}
impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for ZenRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
Ok(Self {
amount,
router_data: item,
})
}
}
// Auth Struct
pub struct ZenAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for ZenAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::HeaderKey { api_key } = auth_type {
Ok(Self {
api_key: api_key.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiRequest {
merchant_transaction_id: String,
payment_channel: ZenPaymentChannels,
amount: String,
currency: enums::Currency,
payment_specific_data: ZenPaymentSpecificData,
customer: ZenCustomerDetails,
custom_ipn_url: String,
items: Vec<ZenItemObject>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum ZenPaymentsRequest {
ApiRequest(Box<ApiRequest>),
CheckoutRequest(Box<CheckoutRequest>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckoutRequest {
amount: String,
currency: enums::Currency,
custom_ipn_url: String,
items: Vec<ZenItemObject>,
merchant_transaction_id: String,
signature: Option<Secret<String>>,
specified_payment_channel: ZenPaymentChannels,
terminal_uuid: Secret<String>,
url_redirect: String,
}
#[derive(Clone, Debug, Display, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[allow(clippy::enum_variant_names)]
pub enum ZenPaymentChannels {
PclCard,
PclGooglepay,
PclApplepay,
PclBoacompraBoleto,
PclBoacompraEfecty,
PclBoacompraMultibanco,
PclBoacompraPagoefectivo,
PclBoacompraPix,
PclBoacompraPse,
PclBoacompraRedcompra,
PclBoacompraRedpagos,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ZenCustomerDetails {
email: pii::Email,
ip: Secret<String, pii::IpAddress>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum ZenPaymentSpecificData {
ZenOnetimePayment(Box<ZenPaymentData>),
ZenGeneralPayment(ZenGeneralPaymentData),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ZenPaymentData {
browser_details: ZenBrowserDetails,
#[serde(rename = "type")]
payment_type: ZenPaymentTypes,
#[serde(skip_serializing_if = "Option::is_none")]
token: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
card: Option<ZenCardDetails>,
descriptor: String,
return_verify_url: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ZenGeneralPaymentData {
#[serde(rename = "type")]
payment_type: ZenPaymentTypes,
return_url: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ZenBrowserDetails {
color_depth: String,
java_enabled: bool,
lang: String,
screen_height: String,
screen_width: String,
timezone: String,
accept_header: String,
window_size: String,
user_agent: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ZenPaymentTypes {
Onetime,
General,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ZenCardDetails {
number: CardNumber,
expiry_date: Secret<String>,
cvv: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ZenItemObject {
name: String,
price: String,
quantity: u16,
line_amount_total: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SessionObject {
pub apple_pay: Option<WalletSessionData>,
pub google_pay: Option<WalletSessionData>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct WalletSessionData {
pub terminal_uuid: Option<Secret<String>>,
pub pay_wall_secret: Option<Secret<String>>,
}
impl TryFrom<(&ZenRouterData<&types::PaymentsAuthorizeRouterData>, &Card)> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (&ZenRouterData<&types::PaymentsAuthorizeRouterData>, &Card),
) -> Result<Self, Self::Error> {
let (item, ccard) = value;
let browser_info = item.router_data.request.get_browser_info()?;
let ip = browser_info.get_ip_address()?;
let browser_details = get_browser_details(&browser_info)?;
let amount = item.amount.to_owned();
let payment_specific_data =
ZenPaymentSpecificData::ZenOnetimePayment(Box::new(ZenPaymentData {
browser_details,
//Connector Specific for cards
payment_type: ZenPaymentTypes::Onetime,
token: None,
card: Some(ZenCardDetails {
number: ccard.card_number.clone(),
expiry_date: ccard
.get_card_expiry_month_year_2_digit_with_delimiter("".to_owned())?,
cvv: ccard.card_cvc.clone(),
}),
descriptor: item
.router_data
.get_description()?
.chars()
.take(24)
.collect(),
return_verify_url: item.router_data.request.router_return_url.clone(),
}));
Ok(Self::ApiRequest(Box::new(ApiRequest {
merchant_transaction_id: item.router_data.connector_request_reference_id.clone(),
payment_channel: ZenPaymentChannels::PclCard,
currency: item.router_data.request.currency,
payment_specific_data,
customer: get_customer(item.router_data, ip)?,
custom_ipn_url: item.router_data.request.get_webhook_url()?,
items: get_item_object(item.router_data)?,
amount,
})))
}
}
impl
TryFrom<(
&ZenRouterData<&types::PaymentsAuthorizeRouterData>,
&VoucherData,
)> for ZenPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (
&ZenRouterData<&types::PaymentsAuthorizeRouterData>,
&VoucherData,
),
) -> Result<Self, Self::Error> {
let (item, voucher_data) = value;
let browser_info = item.router_data.request.get_browser_info()?;
let ip = browser_info.get_ip_address()?;
let amount = item.amount.to_owned();
let payment_specific_data =
ZenPaymentSpecificData::ZenGeneralPayment(ZenGeneralPaymentData {
//Connector Specific for Latam Methods
payment_type: ZenPaymentTypes::General,
return_url: item.router_data.request.get_router_return_url()?,
});
let payment_channel = match voucher_data {
VoucherData::Boleto { .. } => ZenPaymentChannels::PclBoacompraBoleto,
VoucherData::Efecty => ZenPaymentChannels::PclBoacompraEfecty,
VoucherData::PagoEfectivo => ZenPaymentChannels::PclBoacompraPagoefectivo,
VoucherData::RedCompra => ZenPaymentChannels::PclBoacompraRedcompra,
VoucherData::RedPagos => ZenPaymentChannels::PclBoacompraRedpagos,
VoucherData::Oxxo
| VoucherData::Alfamart { .. }
| VoucherData::Indomaret { .. }
| VoucherData::SevenEleven { .. }
| VoucherData::Lawson { .. }
| VoucherData::MiniStop { .. }
| VoucherData::FamilyMart { .. }
| VoucherData::Seicomart { .. }
| VoucherData::PayEasy { .. } => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
))?,
};
Ok(Self::ApiRequest(Box::new(ApiRequest {
merchant_transaction_id: item.router_data.connector_request_reference_id.clone(),
payment_channel,
currency: item.router_data.request.currency,
payment_specific_data,
customer: get_customer(item.router_data, ip)?,
custom_ipn_url: item.router_data.request.get_webhook_url()?,
items: get_item_object(item.router_data)?,
amount,
})))
}
}
impl
TryFrom<(
&ZenRouterData<&types::PaymentsAuthorizeRouterData>,
&Box<BankTransferData>,
)> for ZenPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (
&ZenRouterData<&types::PaymentsAuthorizeRouterData>,
&Box<BankTransferData>,
),
) -> Result<Self, Self::Error> {
let (item, bank_transfer_data) = value;
let browser_info = item.router_data.request.get_browser_info()?;
let ip = browser_info.get_ip_address()?;
let amount = item.amount.to_owned();
let payment_specific_data =
ZenPaymentSpecificData::ZenGeneralPayment(ZenGeneralPaymentData {
//Connector Specific for Latam Methods
payment_type: ZenPaymentTypes::General,
return_url: item.router_data.request.get_router_return_url()?,
});
let payment_channel = match **bank_transfer_data {
BankTransferData::MultibancoBankTransfer { .. } => {
ZenPaymentChannels::PclBoacompraMultibanco
}
BankTransferData::Pix { .. } => ZenPaymentChannels::PclBoacompraPix,
BankTransferData::Pse { .. } => ZenPaymentChannels::PclBoacompraPse,
BankTransferData::SepaBankTransfer { .. }
| BankTransferData::AchBankTransfer { .. }
| BankTransferData::BacsBankTransfer { .. }
| BankTransferData::PermataBankTransfer { .. }
| BankTransferData::BcaBankTransfer { .. }
| BankTransferData::BniVaBankTransfer { .. }
| BankTransferData::BriVaBankTransfer { .. }
| BankTransferData::CimbVaBankTransfer { .. }
| BankTransferData::DanamonVaBankTransfer { .. }
| BankTransferData::LocalBankTransfer { .. }
| BankTransferData::InstantBankTransfer {}
| BankTransferData::InstantBankTransferFinland { .. }
| BankTransferData::InstantBankTransferPoland { .. }
| BankTransferData::IndonesianBankTransfer { .. }
| BankTransferData::MandiriVaBankTransfer { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
))?
}
};
Ok(Self::ApiRequest(Box::new(ApiRequest {
merchant_transaction_id: item.router_data.connector_request_reference_id.clone(),
payment_channel,
currency: item.router_data.request.currency,
payment_specific_data,
customer: get_customer(item.router_data, ip)?,
custom_ipn_url: item.router_data.request.get_webhook_url()?,
items: get_item_object(item.router_data)?,
amount,
})))
}
}
/*
impl TryFrom<(&types::PaymentsAuthorizeRouterData, &GooglePayWalletData)> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, gpay_pay_redirect_data): (&types::PaymentsAuthorizeRouterData, &GooglePayWalletData),
) -> Result<Self, Self::Error> {
let amount = utils::to_currency_base_unit(item.request.amount, item.request.currency)?;
let browser_info = item.request.get_browser_info()?;
let browser_details = get_browser_details(&browser_info)?;
let ip = browser_info.get_ip_address()?;
let payment_specific_data = ZenPaymentData {
browser_details,
//Connector Specific for wallet
payment_type: ZenPaymentTypes::ExternalPaymentToken,
token: Some(Secret::new(
gpay_pay_redirect_data.tokenization_data.token.clone(),
)),
card: None,
descriptor: item.get_description()?.chars().take(24).collect(),
return_verify_url: item.request.router_return_url.clone(),
};
Ok(Self::ApiRequest(Box::new(ApiRequest {
merchant_transaction_id: item.attempt_id.clone(),
payment_channel: ZenPaymentChannels::PclGooglepay,
currency: item.request.currency,
payment_specific_data,
customer: get_customer(item, ip)?,
custom_ipn_url: item.request.get_webhook_url()?,
items: get_item_object(item, amount.clone())?,
amount,
})))
}
}
*/
/*
impl
TryFrom<(
&types::PaymentsAuthorizeRouterData,
&Box<ApplePayRedirectData>,
)> for ZenPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, _apple_pay_redirect_data): (
&types::PaymentsAuthorizeRouterData,
&Box<ApplePayRedirectData>,
),
) -> Result<Self, Self::Error> {
let amount = utils::to_currency_base_unit(item.request.amount, item.request.currency)?;
let connector_meta = item.get_connector_meta()?;
let session: SessionObject = connector_meta
.parse_value("SessionObject")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let applepay_session_data = session
.apple_pay
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
let terminal_uuid = applepay_session_data
.terminal_uuid
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
let mut checkout_request = CheckoutRequest {
merchant_transaction_id: item.attempt_id.clone(),
specified_payment_channel: ZenPaymentChannels::PclApplepay,
currency: item.request.currency,
custom_ipn_url: item.request.get_webhook_url()?,
items: get_item_object(item, amount.clone())?,
amount,
terminal_uuid: Secret::new(terminal_uuid),
signature: None,
url_redirect: item.request.get_return_url()?,
};
checkout_request.signature = Some(get_checkout_signature(
&checkout_request,
&applepay_session_data,
)?);
Ok(Self::CheckoutRequest(Box::new(checkout_request)))
}
}
*/
impl
TryFrom<(
&ZenRouterData<&types::PaymentsAuthorizeRouterData>,
&WalletData,
)> for ZenPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, wallet_data): (
&ZenRouterData<&types::PaymentsAuthorizeRouterData>,
&WalletData,
),
) -> Result<Self, Self::Error> {
let amount = item.amount.to_owned();
let connector_meta = item.router_data.get_connector_meta()?;
let session: SessionObject = connector_meta
.parse_value("SessionObject")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let (specified_payment_channel, session_data) = match wallet_data {
WalletData::ApplePayRedirect(_) => (
ZenPaymentChannels::PclApplepay,
session
.apple_pay
.ok_or(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?,
),
WalletData::GooglePayRedirect(_) => (
ZenPaymentChannels::PclGooglepay,
session
.google_pay
.ok_or(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Google Pay".to_string(),
})?,
),
WalletData::WeChatPayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::ApplePay(_)
| WalletData::GooglePay(_)
| WalletData::BluecodeRedirect {}
| WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::WeChatPayQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
))?,
};
let terminal_uuid = session_data
.terminal_uuid
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.expose();
let mut checkout_request = CheckoutRequest {
merchant_transaction_id: item.router_data.connector_request_reference_id.clone(),
specified_payment_channel,
currency: item.router_data.request.currency,
custom_ipn_url: item.router_data.request.get_webhook_url()?,
items: get_item_object(item.router_data)?,
amount,
terminal_uuid: Secret::new(terminal_uuid),
signature: None,
url_redirect: item.router_data.request.get_router_return_url()?,
};
checkout_request.signature =
Some(get_checkout_signature(&checkout_request, &session_data)?);
Ok(Self::CheckoutRequest(Box::new(checkout_request)))
}
}
fn get_checkout_signature(
checkout_request: &CheckoutRequest,
session: &WalletSessionData,
) -> Result<Secret<String>, error_stack::Report<errors::ConnectorError>> {
let pay_wall_secret = session
.pay_wall_secret
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
let mut signature_data = get_signature_data(checkout_request)?;
signature_data.push_str(&pay_wall_secret.expose());
let payload_digest = digest::digest(&digest::SHA256, signature_data.as_bytes());
let mut signature = hex::encode(payload_digest);
signature.push_str(";sha256");
Ok(Secret::new(signature))
}
/// Fields should be in alphabetical order
fn get_signature_data(
checkout_request: &CheckoutRequest,
) -> Result<String, errors::ConnectorError> {
let specified_payment_channel = match checkout_request.specified_payment_channel {
ZenPaymentChannels::PclCard => "pcl_card",
ZenPaymentChannels::PclGooglepay => "pcl_googlepay",
ZenPaymentChannels::PclApplepay => "pcl_applepay",
ZenPaymentChannels::PclBoacompraBoleto => "pcl_boacompra_boleto",
ZenPaymentChannels::PclBoacompraEfecty => "pcl_boacompra_efecty",
ZenPaymentChannels::PclBoacompraMultibanco => "pcl_boacompra_multibanco",
ZenPaymentChannels::PclBoacompraPagoefectivo => "pcl_boacompra_pagoefectivo",
ZenPaymentChannels::PclBoacompraPix => "pcl_boacompra_pix",
ZenPaymentChannels::PclBoacompraPse => "pcl_boacompra_pse",
ZenPaymentChannels::PclBoacompraRedcompra => "pcl_boacompra_redcompra",
ZenPaymentChannels::PclBoacompraRedpagos => "pcl_boacompra_redpagos",
};
let mut signature_data = vec![
format!("amount={}", checkout_request.amount),
format!("currency={}", checkout_request.currency),
format!("customipnurl={}", checkout_request.custom_ipn_url),
];
for index in 0..checkout_request.items.len() {
let prefix = format!("items[{index}].");
let checkout_request_items = checkout_request
.items
.get(index)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
signature_data.push(format!(
"{prefix}lineamounttotal={}",
checkout_request_items.line_amount_total
));
signature_data.push(format!("{prefix}name={}", checkout_request_items.name));
signature_data.push(format!("{prefix}price={}", checkout_request_items.price));
signature_data.push(format!(
"{prefix}quantity={}",
checkout_request_items.quantity
));
}
signature_data.push(format!(
"merchanttransactionid={}",
checkout_request.merchant_transaction_id
));
signature_data.push(format!(
"specifiedpaymentchannel={specified_payment_channel}"
));
signature_data.push(format!(
"terminaluuid={}",
checkout_request.terminal_uuid.peek()
));
signature_data.push(format!("urlredirect={}", checkout_request.url_redirect));
let signature = signature_data.join("&");
Ok(signature.to_lowercase())
}
fn get_customer(
item: &types::PaymentsAuthorizeRouterData,
ip: Secret<String, pii::IpAddress>,
) -> Result<ZenCustomerDetails, error_stack::Report<errors::ConnectorError>> {
Ok(ZenCustomerDetails {
email: item.request.get_email()?,
ip,
})
}
fn get_item_object(
item: &types::PaymentsAuthorizeRouterData,
) -> Result<Vec<ZenItemObject>, error_stack::Report<errors::ConnectorError>> {
let order_details = item.request.get_order_details()?;
order_details
.iter()
.map(|data| {
Ok(ZenItemObject {
name: data.product_name.clone(),
quantity: data.quantity,
price: utils::to_currency_base_unit_with_zero_decimal_check(
data.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future.
item.request.currency,
)?,
line_amount_total: (f64::from(data.quantity)
* utils::to_currency_base_unit_asf64(
data.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future.
item.request.currency,
)?)
.to_string(),
})
})
.collect::<Result<_, _>>()
}
fn get_browser_details(
browser_info: &BrowserInformation,
) -> CustomResult<ZenBrowserDetails, errors::ConnectorError> {
let screen_height = browser_info
.screen_height
.get_required_value("screen_height")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "screen_height",
})?;
let screen_width = browser_info
.screen_width
.get_required_value("screen_width")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "screen_width",
})?;
let window_size = match (screen_height, screen_width) {
(250, 400) => "01",
(390, 400) => "02",
(500, 600) => "03",
(600, 400) => "04",
_ => "05",
}
.to_string();
Ok(ZenBrowserDetails {
color_depth: browser_info.get_color_depth()?.to_string(),
java_enabled: browser_info.get_java_enabled()?,
lang: browser_info.get_language()?,
screen_height: screen_height.to_string(),
screen_width: screen_width.to_string(),
timezone: browser_info.get_time_zone()?.to_string(),
accept_header: browser_info.get_accept_header()?,
user_agent: browser_info.get_user_agent()?,
window_size,
})
}
impl TryFrom<&ZenRouterData<&types::PaymentsAuthorizeRouterData>> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ZenRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(card) => Self::try_from((item, card)),
PaymentMethodData::Wallet(wallet_data) => Self::try_from((item, wallet_data)),
PaymentMethodData::Voucher(voucher_data) => Self::try_from((item, voucher_data)),
PaymentMethodData::BankTransfer(bank_transfer_data) => {
Self::try_from((item, bank_transfer_data))
}
PaymentMethodData::BankRedirect(bank_redirect_data) => {
Self::try_from(bank_redirect_data)
}
PaymentMethodData::PayLater(paylater_data) => Self::try_from(paylater_data),
PaymentMethodData::BankDebit(bank_debit_data) => Self::try_from(bank_debit_data),
PaymentMethodData::CardRedirect(car_redirect_data) => Self::try_from(car_redirect_data),
PaymentMethodData::GiftCard(gift_card_data) => Self::try_from(gift_card_data.as_ref()),
PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
))?
}
}
}
}
impl TryFrom<&BankRedirectData> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &BankRedirectData) -> Result<Self, Self::Error> {
match value {
BankRedirectData::Ideal { .. }
| BankRedirectData::Sofort { .. }
| BankRedirectData::BancontactCard { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Eps { .. }
| BankRedirectData::Giropay { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::Bizum {}
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
)
.into())
}
}
}
}
impl TryFrom<&PayLaterData> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &PayLaterData) -> Result<Self, Self::Error> {
match value {
PayLaterData::KlarnaRedirect { .. }
| PayLaterData::KlarnaSdk { .. }
| PayLaterData::AffirmRedirect {}
| PayLaterData::AfterpayClearpayRedirect { .. }
| PayLaterData::PayBrightRedirect {}
| PayLaterData::WalleyRedirect {}
| PayLaterData::AlmaRedirect {}
| PayLaterData::FlexitiRedirect {}
| PayLaterData::AtomeRedirect {}
| PayLaterData::BreadpayRedirect {} => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
)
.into()),
}
}
}
impl TryFrom<&BankDebitData> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &BankDebitData) -> Result<Self, Self::Error> {
match value {
BankDebitData::AchBankDebit { .. }
| BankDebitData::SepaBankDebit { .. }
| BankDebitData::BecsBankDebit { .. }
| BankDebitData::BacsBankDebit { .. }
| BankDebitData::SepaGuarenteedBankDebit { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
)
.into())
}
}
}
}
impl TryFrom<&CardRedirectData> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &CardRedirectData) -> Result<Self, Self::Error> {
match value {
CardRedirectData::Knet {}
| CardRedirectData::Benefit {}
| CardRedirectData::MomoAtm {}
| CardRedirectData::CardRedirect {} => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
)
.into()),
}
}
}
impl TryFrom<&GiftCardData> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &GiftCardData) -> Result<Self, Self::Error> {
match value {
GiftCardData::PaySafeCard {}
| GiftCardData::Givex(_)
| GiftCardData::BhnCardNetwork(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
)
.into()),
}
}
}
// PaymentsResponse
#[derive(Debug, Default, Deserialize, Clone, strum::Display, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum ZenPaymentStatus {
Authorized,
Accepted,
#[default]
Pending,
Rejected,
Canceled,
}
impl ForeignTryFrom<(ZenPaymentStatus, Option<ZenActions>)> for enums::AttemptStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(item: (ZenPaymentStatus, Option<ZenActions>)) -> Result<Self, Self::Error> {
let (item_txn_status, item_action_status) = item;
Ok(match item_txn_status {
// Payment has been authorized at connector end, They will send webhook when it gets accepted
ZenPaymentStatus::Authorized => Self::Pending,
ZenPaymentStatus::Accepted => Self::Charged,
ZenPaymentStatus::Pending => {
item_action_status.map_or(Self::Pending, |action| match action {
ZenActions::Redirect => Self::AuthenticationPending,
})
}
ZenPaymentStatus::Rejected => Self::Failure,
ZenPaymentStatus::Canceled => Self::Voided,
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiResponse {
status: ZenPaymentStatus,
id: String,
// merchant_transaction_id: Option<String>,
merchant_action: Option<ZenMerchantAction>,
reject_code: Option<String>,
reject_reason: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ZenPaymentsResponse {
ApiResponse(ApiResponse),
CheckoutResponse(CheckoutResponse),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckoutResponse {
redirect_url: url::Url,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ZenMerchantAction {
action: ZenActions,
data: ZenMerchantActionData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum ZenActions {
Redirect,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ZenMerchantActionData {
redirect_url: url::Url,
}
impl<F, T> TryFrom<ResponseRouterData<F, ZenPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ZenPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
ZenPaymentsResponse::ApiResponse(response) => Self::try_from(ResponseRouterData {
response,
data: item.data,
http_code: item.http_code,
}),
ZenPaymentsResponse::CheckoutResponse(response) => Self::try_from(ResponseRouterData {
response,
data: item.data,
http_code: item.http_code,
}),
}
}
}
fn get_zen_response(
response: ApiResponse,
status_code: u16,
) -> CustomResult<
(
enums::AttemptStatus,
Option<ErrorResponse>,
PaymentsResponseData,
),
errors::ConnectorError,
> {
let redirection_data_action = response.merchant_action.map(|merchant_action| {
(
RedirectForm::from((merchant_action.data.redirect_url, Method::Get)),
merchant_action.action,
)
});
let (redirection_data, action) = match redirection_data_action {
Some((redirect_form, action)) => (Some(redirect_form), Some(action)),
None => (None, None),
};
let status = enums::AttemptStatus::foreign_try_from((response.status, action))?;
let error = if utils::is_payment_failure(status) {
Some(ErrorResponse {
code: response
.reject_code
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: response
.reject_reason
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: response.reject_reason,
status_code,
attempt_status: Some(status),
connector_transaction_id: Some(response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
let payment_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
};
Ok((status, error, payment_response_data))
}
impl<F, T> TryFrom<ResponseRouterData<F, ApiResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: ResponseRouterData<F, ApiResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, error, payment_response_data) =
get_zen_response(value.response.clone(), value.http_code)?;
Ok(Self {
status,
response: error.map_or_else(|| Ok(payment_response_data), Err),
..value.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, CheckoutResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: ResponseRouterData<F, CheckoutResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirection_data = Some(RedirectForm::from((
value.response.redirect_url,
Method::Get,
)));
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..value.data
})
}
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ZenRefundRequest {
amount: String,
transaction_id: String,
currency: enums::Currency,
merchant_transaction_id: String,
}
impl<F> TryFrom<&ZenRouterData<&types::RefundsRouterData<F>>> for ZenRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ZenRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
transaction_id: item.router_data.request.connector_transaction_id.clone(),
currency: item.router_data.request.currency,
merchant_transaction_id: item.router_data.request.refund_id.clone(),
})
}
}
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Authorized,
Accepted,
#[default]
Pending,
Rejected,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Accepted => Self::Success,
RefundStatus::Pending | RefundStatus::Authorized => Self::Pending,
RefundStatus::Rejected => Self::Failure,
}
}
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
id: String,
status: RefundStatus,
reject_code: Option<String>,
reject_reason: Option<String>,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let (error, refund_response_data) = get_zen_refund_response(item.response, item.http_code)?;
Ok(Self {
response: error.map_or_else(|| Ok(refund_response_data), Err),
..item.data
})
}
}
fn get_zen_refund_response(
response: RefundResponse,
status_code: u16,
) -> CustomResult<(Option<ErrorResponse>, RefundsResponseData), errors::ConnectorError> {
let refund_status = enums::RefundStatus::from(response.status);
let error = if utils::is_refund_failure(refund_status) {
Some(ErrorResponse {
code: response
.reject_code
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: response
.reject_reason
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: response.reject_reason,
status_code,
attempt_status: None,
connector_transaction_id: Some(response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
let refund_response_data = RefundsResponseData {
connector_refund_id: response.id,
refund_status,
};
Ok((error, refund_response_data))
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ZenWebhookBody {
#[serde(rename = "transactionId")]
pub id: String,
pub merchant_transaction_id: String,
pub amount: String,
pub currency: String,
pub status: ZenPaymentStatus,
}
#[derive(Debug, Clone, Deserialize)]
pub struct ZenWebhookSignature {
pub hash: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ZenWebhookObjectReference {
#[serde(rename = "type")]
pub transaction_type: ZenWebhookTxnType,
pub transaction_id: String,
pub merchant_transaction_id: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ZenWebhookEventType {
#[serde(rename = "type")]
pub transaction_type: ZenWebhookTxnType,
pub transaction_id: String,
pub status: ZenPaymentStatus,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ZenWebhookTxnType {
TrtPurchase,
TrtRefund,
#[serde(other)]
Unknown,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ZenErrorResponse {
pub error: Option<ZenErrorBody>,
pub message: Option<String>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct ZenErrorBody {
pub message: String,
pub code: String,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/zen/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 9555
}
|
large_file_-298703494261619822
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs
</path>
<file>
use common_enums::{enums, MerchantCategoryCode};
use common_types::payments::MerchantCountryCode;
use common_utils::{ext_traits::OptionExt as _, types::FloatMajorUnit};
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, RouterData},
router_request_types::{
authentication::{AuthNFlowType, ChallengeParams},
unified_authentication_service::{
AuthenticationInfo, DynamicData, PostAuthenticationDetails, PreAuthenticationDetails,
TokenDetails, UasAuthenticationResponseData,
},
},
types::{
UasAuthenticationConfirmationRouterData, UasAuthenticationRouterData,
UasPostAuthenticationRouterData, UasPreAuthenticationRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::types::ResponseRouterData;
//TODO: Fill the struct with respective fields
pub struct UnifiedAuthenticationServiceRouterData<T> {
pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for UnifiedAuthenticationServiceRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
}
}
}
use error_stack::ResultExt;
#[derive(Debug, Serialize)]
pub struct UnifiedAuthenticationServicePreAuthenticateRequest {
pub authenticate_by: String,
pub session_id: common_utils::id_type::AuthenticationId,
pub source_authentication_id: common_utils::id_type::AuthenticationId,
pub authentication_info: Option<AuthenticationInfo>,
pub service_details: Option<CtpServiceDetails>,
pub customer_details: Option<CustomerDetails>,
pub pmt_details: Option<PaymentDetails>,
pub auth_creds: UnifiedAuthenticationServiceAuthType,
pub transaction_details: Option<TransactionDetails>,
pub acquirer_details: Option<Acquirer>,
pub billing_address: Option<Address>,
}
#[derive(Debug, Serialize)]
pub struct UnifiedAuthenticationServiceAuthenticateConfirmationRequest {
pub authenticate_by: String,
pub source_authentication_id: common_utils::id_type::AuthenticationId,
pub auth_creds: UnifiedAuthenticationServiceAuthType,
pub x_src_flow_id: Option<String>,
pub transaction_amount: Option<FloatMajorUnit>,
pub transaction_currency: Option<enums::Currency>,
pub checkout_event_type: Option<String>,
pub checkout_event_status: Option<String>,
pub confirmation_status: Option<String>,
pub confirmation_reason: Option<String>,
pub confirmation_timestamp: Option<String>,
pub network_authorization_code: Option<String>,
pub network_transaction_identifier: Option<String>,
pub correlation_id: Option<String>,
pub merchant_transaction_id: Option<String>,
}
#[derive(Debug, Serialize, PartialEq, Deserialize)]
pub struct UnifiedAuthenticationServiceAuthenticateConfirmationResponse {
status: String,
}
impl<F, T>
TryFrom<
ResponseRouterData<
F,
UnifiedAuthenticationServiceAuthenticateConfirmationResponse,
T,
UasAuthenticationResponseData,
>,
> for RouterData<F, T, UasAuthenticationResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
UnifiedAuthenticationServiceAuthenticateConfirmationResponse,
T,
UasAuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(UasAuthenticationResponseData::Confirmation {}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct PaymentDetails {
pub pan: cards::CardNumber,
pub digital_card_id: Option<String>,
pub payment_data_type: Option<common_enums::PaymentMethodType>,
pub encrypted_src_card_details: Option<String>,
pub card_expiry_month: Secret<String>,
pub card_expiry_year: Secret<String>,
pub cardholder_name: Option<Secret<String>>,
pub card_token_number: Option<Secret<String>>,
pub account_type: Option<common_enums::PaymentMethodType>,
pub card_cvc: Option<Secret<String>>,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TransactionDetails {
pub amount: FloatMajorUnit,
pub currency: enums::Currency,
pub date: Option<PrimitiveDateTime>,
pub pan_source: Option<String>,
pub protection_type: Option<String>,
pub entry_mode: Option<String>,
pub transaction_type: Option<String>,
pub otp_value: Option<String>,
pub three_ds_data: Option<ThreeDSData>,
pub message_category: Option<MessageCategory>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MessageCategory {
Payment,
NonPayment,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreeDSData {
pub preferred_protocol_version: common_utils::types::SemanticVersion,
pub threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Acquirer {
pub acquirer_merchant_id: Option<String>,
pub acquirer_bin: Option<String>,
pub acquirer_country_code: Option<String>,
}
#[derive(Default, Debug, Serialize, PartialEq, Clone, Deserialize)]
pub struct BrowserInfo {
pub color_depth: Option<u8>,
pub java_enabled: Option<bool>,
pub java_script_enabled: Option<bool>,
pub language: Option<String>,
pub screen_height: Option<u32>,
pub screen_width: Option<u32>,
pub time_zone: Option<i32>,
pub ip_address: Option<std::net::IpAddr>,
pub accept_header: Option<String>,
pub user_agent: Option<String>,
pub os_type: Option<String>,
pub os_version: Option<String>,
pub device_model: Option<String>,
pub accept_language: Option<String>,
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct CtpServiceDetails {
pub service_session_ids: Option<ServiceSessionIds>,
pub merchant_details: Option<MerchantDetails>,
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct ServiceSessionIds {
pub client_id: Option<String>,
pub service_id: Option<String>,
pub correlation_id: Option<String>,
pub client_reference_id: Option<String>,
pub merchant_transaction_id: Option<String>,
pub x_src_flow_id: Option<String>,
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct MerchantDetails {
pub merchant_id: Option<String>,
pub merchant_name: Option<String>,
pub merchant_category_code: Option<MerchantCategoryCode>,
pub configuration_id: Option<String>,
pub endpoint_prefix: Option<String>,
pub three_ds_requestor_url: Option<String>,
pub three_ds_requestor_id: Option<String>,
pub three_ds_requestor_name: Option<String>,
pub merchant_country_code: Option<MerchantCountryCode>,
pub notification_url: Option<url::Url>,
}
#[derive(Default, Clone, Debug, Serialize, PartialEq, Deserialize)]
pub struct Address {
pub city: Option<String>,
pub country: Option<common_enums::CountryAlpha2>,
pub line1: Option<Secret<String>>,
pub line2: Option<Secret<String>>,
pub line3: Option<Secret<String>>,
pub post_code: Option<Secret<String>>,
pub state: Option<Secret<String>>,
}
#[derive(Default, Clone, Debug, Serialize, PartialEq, Deserialize)]
pub struct CustomerDetails {
pub name: Secret<String>,
pub email: Option<Secret<String>>,
pub phone_number: Option<Secret<String>>,
pub customer_id: String,
#[serde(rename = "type")]
pub customer_type: Option<String>,
pub billing_address: Address,
pub shipping_address: Address,
pub wallet_account_id: Secret<String>,
pub email_hash: Secret<String>,
pub country_code: String,
pub national_identifier: String,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct UnifiedAuthenticationServiceCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&UnifiedAuthenticationServiceRouterData<&UasPreAuthenticationRouterData>>
for UnifiedAuthenticationServicePreAuthenticateRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &UnifiedAuthenticationServiceRouterData<&UasPreAuthenticationRouterData>,
) -> Result<Self, Self::Error> {
let authentication_id = item.router_data.authentication_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "authentication_id",
},
)?;
let authentication_info = item.router_data.request.authentication_info.clone();
let auth_type =
UnifiedAuthenticationServiceAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
authenticate_by: item.router_data.connector.clone(),
session_id: authentication_id.clone(),
source_authentication_id: authentication_id,
authentication_info,
service_details: Some(CtpServiceDetails {
service_session_ids: item.router_data.request.service_details.clone().map(
|service_details| ServiceSessionIds {
client_id: None,
service_id: None,
correlation_id: service_details
.service_session_ids
.clone()
.and_then(|service_session_ids| service_session_ids.correlation_id),
client_reference_id: None,
merchant_transaction_id: service_details
.service_session_ids
.clone()
.and_then(|service_session_ids| {
service_session_ids.merchant_transaction_id
}),
x_src_flow_id: service_details
.service_session_ids
.clone()
.and_then(|service_session_ids| service_session_ids.x_src_flow_id),
},
),
merchant_details: None,
}),
customer_details: None,
pmt_details: None,
auth_creds: auth_type,
acquirer_details: None,
billing_address: None,
transaction_details: Some(TransactionDetails {
amount: item.amount,
currency: item
.router_data
.request
.transaction_details
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "transaction_details",
})?
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?,
date: None,
pan_source: None,
protection_type: None,
entry_mode: None,
transaction_type: None,
otp_value: None,
three_ds_data: None,
message_category: None,
}),
})
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum UnifiedAuthenticationServicePreAuthenticateStatus {
ACKSUCCESS,
ACKFAILURE,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UnifiedAuthenticationServicePreAuthenticateResponse {
status: UnifiedAuthenticationServicePreAuthenticateStatus,
pub eligibility: Option<Eligibility>,
}
impl<F, T>
TryFrom<
ResponseRouterData<
F,
UnifiedAuthenticationServicePreAuthenticateResponse,
T,
UasAuthenticationResponseData,
>,
> for RouterData<F, T, UasAuthenticationResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
UnifiedAuthenticationServicePreAuthenticateResponse,
T,
UasAuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
let three_ds_eligibility_response = if let Some(Eligibility::ThreeDsEligibilityResponse {
three_ds_eligibility_response,
}) = item.response.eligibility
{
Some(three_ds_eligibility_response)
} else {
None
};
let max_acs_protocol_version = three_ds_eligibility_response
.as_ref()
.and_then(|response| response.get_max_acs_protocol_version_if_available());
let maximum_supported_3ds_version = max_acs_protocol_version
.as_ref()
.map(|acs_protocol_version| acs_protocol_version.version.clone());
let three_ds_method_data =
three_ds_eligibility_response
.as_ref()
.and_then(|three_ds_eligibility_response| {
three_ds_eligibility_response
.three_ds_method_data_form
.as_ref()
.and_then(|form| form.three_ds_method_data.clone())
});
let three_ds_method_url = max_acs_protocol_version
.and_then(|acs_protocol_version| acs_protocol_version.three_ds_method_url);
Ok(Self {
response: Ok(UasAuthenticationResponseData::PreAuthentication {
authentication_details: PreAuthenticationDetails {
threeds_server_transaction_id: three_ds_eligibility_response
.as_ref()
.map(|response| response.three_ds_server_trans_id.clone()),
maximum_supported_3ds_version: maximum_supported_3ds_version.clone(),
connector_authentication_id: three_ds_eligibility_response
.as_ref()
.map(|response| response.three_ds_server_trans_id.clone()),
three_ds_method_data,
three_ds_method_url,
message_version: maximum_supported_3ds_version,
connector_metadata: None,
directory_server_id: three_ds_eligibility_response
.and_then(|response| response.directory_server_id),
},
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct UnifiedAuthenticationServicePostAuthenticateRequest {
pub authenticate_by: String,
pub source_authentication_id: common_utils::id_type::AuthenticationId,
pub auth_creds: ConnectorAuthType,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UnifiedAuthenticationServicePostAuthenticateResponse {
pub authentication_details: AuthenticationDetails,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AuthenticationDetails {
pub eci: Option<String>,
pub token_details: Option<UasTokenDetails>,
pub dynamic_data_details: Option<UasDynamicData>,
pub trans_status: Option<common_enums::TransactionStatus>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UasTokenDetails {
pub payment_token: cards::CardNumber,
pub payment_account_reference: String,
pub token_expiration_month: Secret<String>,
pub token_expiration_year: Secret<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UasDynamicData {
pub dynamic_data_value: Option<Secret<String>>,
pub dynamic_data_type: Option<String>,
pub ds_trans_id: Option<String>,
}
impl TryFrom<&UasPostAuthenticationRouterData>
for UnifiedAuthenticationServicePostAuthenticateRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &UasPostAuthenticationRouterData) -> Result<Self, Self::Error> {
Ok(Self {
authenticate_by: item.connector.clone(),
source_authentication_id: item.authentication_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "authentication_id",
},
)?,
auth_creds: item.connector_auth_type.clone(),
})
}
}
impl<F, T>
TryFrom<
ResponseRouterData<
F,
UnifiedAuthenticationServicePostAuthenticateResponse,
T,
UasAuthenticationResponseData,
>,
> for RouterData<F, T, UasAuthenticationResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
UnifiedAuthenticationServicePostAuthenticateResponse,
T,
UasAuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(UasAuthenticationResponseData::PostAuthentication {
authentication_details: PostAuthenticationDetails {
eci: item.response.authentication_details.eci,
token_details: item.response.authentication_details.token_details.map(
|token_details| TokenDetails {
payment_token: token_details.payment_token,
payment_account_reference: token_details.payment_account_reference,
token_expiration_month: token_details.token_expiration_month,
token_expiration_year: token_details.token_expiration_year,
},
),
dynamic_data_details: item
.response
.authentication_details
.dynamic_data_details
.map(|dynamic_data| DynamicData {
dynamic_data_value: dynamic_data.dynamic_data_value,
dynamic_data_type: dynamic_data.dynamic_data_type,
ds_trans_id: dynamic_data.ds_trans_id,
}),
trans_status: item.response.authentication_details.trans_status,
challenge_cancel: None,
challenge_code_reason: None,
},
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct UnifiedAuthenticationServiceErrorResponse {
pub error: String,
}
impl TryFrom<&UnifiedAuthenticationServiceRouterData<&UasAuthenticationConfirmationRouterData>>
for UnifiedAuthenticationServiceAuthenticateConfirmationRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &UnifiedAuthenticationServiceRouterData<&UasAuthenticationConfirmationRouterData>,
) -> Result<Self, Self::Error> {
let authentication_id = item.router_data.authentication_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "authentication_id",
},
)?;
let auth_type =
UnifiedAuthenticationServiceAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
authenticate_by: item.router_data.connector.clone(),
auth_creds: auth_type,
source_authentication_id: authentication_id,
x_src_flow_id: item.router_data.request.x_src_flow_id.clone(),
transaction_amount: Some(item.amount),
transaction_currency: Some(item.router_data.request.transaction_currency),
checkout_event_type: item.router_data.request.checkout_event_type.clone(),
checkout_event_status: item.router_data.request.checkout_event_status.clone(),
confirmation_status: item.router_data.request.confirmation_status.clone(),
confirmation_reason: item.router_data.request.confirmation_reason.clone(),
confirmation_timestamp: item.router_data.request.confirmation_timestamp.clone(),
network_authorization_code: item.router_data.request.network_authorization_code.clone(),
network_transaction_identifier: item
.router_data
.request
.network_transaction_identifier
.clone(),
correlation_id: item.router_data.request.correlation_id.clone(),
merchant_transaction_id: item.router_data.request.merchant_transaction_id.clone(),
})
}
}
// ThreeDs request
impl TryFrom<&UasPreAuthenticationRouterData>
for UnifiedAuthenticationServicePreAuthenticateRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &UasPreAuthenticationRouterData) -> Result<Self, Self::Error> {
let auth_type = UnifiedAuthenticationServiceAuthType::try_from(&item.connector_auth_type)?;
let authentication_id =
item.authentication_id
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "authentication_id",
})?;
let merchant_data = item.request.merchant_details.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "merchant_details",
},
)?;
let merchant_details = MerchantDetails {
merchant_id: merchant_data.merchant_id,
merchant_name: merchant_data.merchant_name,
merchant_category_code: merchant_data.merchant_category_code,
merchant_country_code: merchant_data.merchant_country_code.clone(),
endpoint_prefix: merchant_data.endpoint_prefix,
three_ds_requestor_url: merchant_data.three_ds_requestor_url,
three_ds_requestor_id: merchant_data.three_ds_requestor_id,
three_ds_requestor_name: merchant_data.three_ds_requestor_name,
configuration_id: None,
notification_url: merchant_data.notification_url,
};
let acquirer = Acquirer {
acquirer_bin: item.request.acquirer_bin.clone(),
acquirer_merchant_id: item.request.acquirer_merchant_id.clone(),
acquirer_country_code: merchant_data
.merchant_country_code
.map(|code| code.get_country_code()),
};
let service_details = Some(CtpServiceDetails {
service_session_ids: None,
merchant_details: Some(merchant_details),
});
let billing_address = item
.request
.billing_address
.clone()
.map(|address_wrap| Address {
city: address_wrap
.address
.clone()
.and_then(|address| address.city),
country: address_wrap
.address
.clone()
.and_then(|address| address.country),
line1: address_wrap
.address
.clone()
.and_then(|address| address.line1),
line2: address_wrap
.address
.clone()
.and_then(|address| address.line2),
line3: address_wrap
.address
.clone()
.and_then(|address| address.line3),
post_code: address_wrap.address.clone().and_then(|address| address.zip),
state: address_wrap.address.and_then(|address| address.state),
});
Ok(Self {
authenticate_by: item.connector.clone(),
session_id: authentication_id.clone(),
source_authentication_id: authentication_id,
authentication_info: None,
service_details,
customer_details: None,
pmt_details: item
.request
.payment_details
.clone()
.map(|details| PaymentDetails {
pan: details.pan,
digital_card_id: details.digital_card_id,
payment_data_type: details.payment_data_type,
encrypted_src_card_details: details.encrypted_src_card_details,
cardholder_name: details.cardholder_name,
card_token_number: details.card_token_number,
account_type: details.account_type,
card_expiry_month: details.card_expiry_month,
card_expiry_year: details.card_expiry_year,
card_cvc: details.card_cvc,
}),
auth_creds: auth_type,
transaction_details: None,
acquirer_details: Some(acquirer),
billing_address,
})
}
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(tag = "auth_type")]
pub enum UnifiedAuthenticationServiceAuthType {
HeaderKey {
api_key: Secret<String>,
},
CertificateAuth {
certificate: Secret<String>,
private_key: Secret<String>,
},
SignatureKey {
api_key: Secret<String>,
key1: Secret<String>,
api_secret: Secret<String>,
},
NoKey,
}
impl TryFrom<&ConnectorAuthType> for UnifiedAuthenticationServiceAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self::HeaderKey {
api_key: api_key.clone(),
}),
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self::SignatureKey {
api_key: api_key.clone(),
key1: key1.clone(),
api_secret: api_secret.clone(),
}),
ConnectorAuthType::CertificateAuth {
certificate,
private_key,
} => Ok(Self::CertificateAuth {
certificate: certificate.clone(),
private_key: private_key.clone(),
}),
ConnectorAuthType::NoKey => Ok(Self::NoKey),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "eligibility")]
pub enum Eligibility {
None,
TokenEligibilityResponse {
token_eligibility_response: Box<TokenEligibilityResponse>,
},
ThreeDsEligibilityResponse {
three_ds_eligibility_response: Box<ThreeDsEligibilityResponse>,
},
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TokenEligibilityResponse {
pub network_request_id: Option<String>,
pub network_client_id: Option<String>,
pub nonce: Option<String>,
pub payment_method_details: Option<PaymentMethodDetails>,
pub network_pan_enrollment_id: Option<String>,
pub ignore_00_field: Option<String>,
pub token_details: Option<TokenDetails>,
pub network_provisioned_token_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PaymentMethodDetails {
pub ignore_01_field: String,
pub cvv2_printed_ind: String,
pub last4: String,
pub exp_date_printed_ind: String,
pub payment_account_reference: String,
pub exp_year: String,
pub exp_month: String,
pub verification_results: VerificationResults,
pub enabled_services: EnabledServices,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct VerificationResults {
pub address_verification_code: String,
pub cvv2_verification_code: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EnabledServices {
pub merchant_presented_qr: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ThreeDsEligibilityResponse {
pub three_ds_server_trans_id: String,
pub scheme_id: Option<String>,
pub acs_protocol_versions: Option<Vec<AcsProtocolVersion>>,
pub ds_protocol_versions: Option<Vec<String>>,
pub three_ds_method_data_form: Option<ThreeDsMethodDataForm>,
pub three_ds_method_data: Option<ThreeDsMethodData>,
pub error_details: Option<String>,
pub is_card_found_in_2x_ranges: bool,
pub directory_server_id: Option<String>,
}
impl ThreeDsEligibilityResponse {
pub fn get_max_acs_protocol_version_if_available(&self) -> Option<AcsProtocolVersion> {
let max_acs_version =
self.acs_protocol_versions
.as_ref()
.and_then(|acs_protocol_versions| {
acs_protocol_versions
.iter()
.max_by_key(|acs_protocol_versions| acs_protocol_versions.version.clone())
});
max_acs_version.cloned()
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct AcsProtocolVersion {
pub version: common_utils::types::SemanticVersion,
pub acs_info_ind: Vec<String>,
pub three_ds_method_url: Option<String>,
pub supported_msg_ext: Option<Vec<SupportedMsgExt>>,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct SupportedMsgExt {
pub id: String,
pub version: String,
}
#[derive(Clone, Serialize, Deserialize, Debug, Default)]
pub struct ThreeDsMethodDataForm {
pub three_ds_method_data: Option<String>,
}
#[derive(Default, Clone, Serialize, Deserialize, Debug)]
pub struct ThreeDsMethodData {
pub three_ds_method_notification_url: String,
pub server_transaction_id: String,
}
#[derive(Serialize, Debug)]
pub struct UnifiedAuthenticationServiceAuthenticateRequest {
pub authenticate_by: String,
pub source_authentication_id: common_utils::id_type::AuthenticationId,
pub transaction_details: TransactionDetails,
pub device_details: DeviceDetails,
pub customer_details: Option<CustomerDetails>,
pub auth_creds: UnifiedAuthenticationServiceAuthType,
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct ServiceDetails {
pub service_session_ids: Option<ServiceSessionIds>,
pub merchant_details: Option<MerchantDetails>,
}
#[derive(Serialize, Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum UnifiedAuthenticationServiceAuthenticateResponse {
Success(Box<ThreeDsResponseData>),
Failure(UnifiedAuthenticationServiceErrorResponse),
}
#[derive(Serialize, Debug, Clone, Deserialize)]
pub struct ThreeDsResponseData {
pub three_ds_auth_response: ThreeDsAuthDetails,
}
#[derive(Serialize, Debug, Clone, Deserialize)]
pub struct ThreeDsAuthDetails {
pub three_ds_server_trans_id: String,
pub acs_trans_id: String,
pub acs_reference_number: String,
pub acs_operator_id: Option<String>,
pub ds_reference_number: Option<String>,
pub ds_trans_id: String,
pub sdk_trans_id: Option<String>,
pub trans_status: common_enums::TransactionStatus,
pub acs_challenge_mandated: Option<ACSChallengeMandatedEnum>,
pub message_type: Option<String>,
pub message_version: Option<String>,
pub acs_url: Option<url::Url>,
pub challenge_request: Option<String>,
pub challenge_request_key: Option<String>,
pub acs_signed_content: Option<String>,
pub authentication_value: Option<Secret<String>>,
pub eci: Option<String>,
pub challenge_code: Option<String>,
pub challenge_cancel: Option<String>,
pub challenge_code_reason: Option<String>,
pub message_extension: Option<common_utils::pii::SecretSerdeValue>,
}
#[derive(Debug, Serialize, Clone, Copy, Deserialize)]
pub enum ACSChallengeMandatedEnum {
/// Challenge is mandated
Y,
/// Challenge is not mandated
N,
}
#[derive(Clone, Serialize, Debug)]
pub struct DeviceDetails {
pub device_channel: api_models::payments::DeviceChannel,
pub browser_info: Option<BrowserInfo>,
pub sdk_info: Option<api_models::payments::SdkInformation>,
}
impl TryFrom<&UnifiedAuthenticationServiceRouterData<&UasAuthenticationRouterData>>
for UnifiedAuthenticationServiceAuthenticateRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &UnifiedAuthenticationServiceRouterData<&UasAuthenticationRouterData>,
) -> Result<Self, Self::Error> {
let authentication_id = item.router_data.authentication_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "authentication_id",
},
)?;
let browser_info =
if let Some(browser_details) = item.router_data.request.browser_details.clone() {
BrowserInfo {
color_depth: browser_details.color_depth,
java_enabled: browser_details.java_enabled,
java_script_enabled: browser_details.java_script_enabled,
language: browser_details.language,
screen_height: browser_details.screen_height,
screen_width: browser_details.screen_width,
time_zone: browser_details.time_zone,
ip_address: browser_details.ip_address,
accept_header: browser_details.accept_header,
user_agent: browser_details.user_agent,
os_type: browser_details.os_type,
os_version: browser_details.os_version,
device_model: browser_details.device_model,
accept_language: browser_details.accept_language,
}
} else {
BrowserInfo::default()
};
let three_ds_data = ThreeDSData {
preferred_protocol_version: item
.router_data
.request
.pre_authentication_data
.message_version
.clone(),
threeds_method_comp_ind: item.router_data.request.threeds_method_comp_ind.clone(),
};
let device_details = DeviceDetails {
device_channel: item
.router_data
.request
.transaction_details
.device_channel
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "device_channel",
})?,
browser_info: Some(browser_info),
sdk_info: item.router_data.request.sdk_information.clone(),
};
let message_category = item.router_data.request.transaction_details.message_category.clone().map(|category| match category {
hyperswitch_domain_models::router_request_types::authentication::MessageCategory::Payment => MessageCategory::Payment ,
hyperswitch_domain_models::router_request_types::authentication::MessageCategory::NonPayment => MessageCategory::NonPayment,
});
let transaction_details = TransactionDetails {
amount: item.amount,
currency: item
.router_data
.request
.transaction_details
.currency
.get_required_value("currency")
.change_context(errors::ConnectorError::InSufficientBalanceInPaymentMethod)?,
date: None,
pan_source: None,
protection_type: None,
entry_mode: None,
transaction_type: None,
otp_value: None,
three_ds_data: Some(three_ds_data),
message_category,
};
let auth_type =
UnifiedAuthenticationServiceAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
authenticate_by: item.router_data.connector.clone(),
source_authentication_id: authentication_id,
transaction_details,
auth_creds: auth_type,
device_details,
customer_details: None,
})
}
}
impl<F, T>
TryFrom<
ResponseRouterData<
F,
UnifiedAuthenticationServiceAuthenticateResponse,
T,
UasAuthenticationResponseData,
>,
> for RouterData<F, T, UasAuthenticationResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
UnifiedAuthenticationServiceAuthenticateResponse,
T,
UasAuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
let response = match item.response {
UnifiedAuthenticationServiceAuthenticateResponse::Success(auth_response) => {
let authn_flow_type = match auth_response.three_ds_auth_response.trans_status {
common_enums::TransactionStatus::ChallengeRequired => {
AuthNFlowType::Challenge(Box::new(ChallengeParams {
acs_url: auth_response.three_ds_auth_response.acs_url.clone(),
challenge_request: auth_response
.three_ds_auth_response
.challenge_request,
challenge_request_key: auth_response
.three_ds_auth_response
.challenge_request_key,
acs_reference_number: Some(
auth_response.three_ds_auth_response.acs_reference_number,
),
acs_trans_id: Some(auth_response.three_ds_auth_response.acs_trans_id),
three_dsserver_trans_id: Some(
auth_response
.three_ds_auth_response
.three_ds_server_trans_id,
),
acs_signed_content: auth_response
.three_ds_auth_response
.acs_signed_content,
}))
}
_ => AuthNFlowType::Frictionless,
};
Ok(UasAuthenticationResponseData::Authentication {
authentication_details: hyperswitch_domain_models::router_request_types::unified_authentication_service::AuthenticationDetails {
authn_flow_type,
authentication_value: auth_response.three_ds_auth_response.authentication_value,
trans_status: auth_response.three_ds_auth_response.trans_status,
connector_metadata: None,
ds_trans_id: Some(auth_response.three_ds_auth_response.ds_trans_id),
eci: auth_response.three_ds_auth_response.eci,
challenge_code: auth_response.three_ds_auth_response.challenge_code,
challenge_cancel: auth_response.three_ds_auth_response.challenge_cancel,
challenge_code_reason: auth_response.three_ds_auth_response.challenge_code_reason,
message_extension: auth_response.three_ds_auth_response.message_extension,
},
})
}
UnifiedAuthenticationServiceAuthenticateResponse::Failure(error_response) => {
Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: error_response.error.clone(),
reason: None,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
};
Ok(Self {
response,
..item.data
})
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 7599
}
|
large_file_-4421076715298231625
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs
</path>
<file>
use api_models::payments::QrCodeInformation;
use common_enums::{enums, PaymentMethod};
use common_utils::{
errors::CustomResult,
ext_traits::{BytesExt, Encode},
new_type::MaskedBankAccount,
pii,
types::StringMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankTransferData, PaymentMethodData},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
payments::Void,
refunds::{Execute, RSync},
},
router_request_types::{PaymentsCancelData, ResponseId},
router_response_types::{
ConnectorCustomerResponseData, PaymentsResponseData, RefundsResponseData,
},
types,
};
use hyperswitch_interfaces::{
consts, errors, events::connector_api_logs::ConnectorEvent, types::Response,
};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use url::Url;
use super::{
requests::{
DocumentType, FacilitapayAuthRequest, FacilitapayCredentials, FacilitapayCustomerRequest,
FacilitapayPaymentsRequest, FacilitapayPerson, FacilitapayRouterData,
FacilitapayTransactionRequest, PixTransactionRequest,
},
responses::{
FacilitapayAuthResponse, FacilitapayCustomerResponse, FacilitapayPaymentStatus,
FacilitapayPaymentsResponse, FacilitapayRefundResponse, FacilitapayVoidResponse,
},
};
use crate::{
types::{RefreshTokenRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{self, is_payment_failure, missing_field_err, QrImage, RouterData as OtherRouterData},
};
type Error = error_stack::Report<errors::ConnectorError>;
impl<T> From<(StringMajorUnit, T)> for FacilitapayRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
// Auth Struct
#[derive(Debug, Clone)]
pub struct FacilitapayAuthType {
pub(super) username: Secret<String>,
pub(super) password: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FacilitapayConnectorMetadataObject {
// pub destination_account_number: Secret<String>,
pub destination_account_number: MaskedBankAccount,
}
// Helper to build the request from Hyperswitch Auth Type
impl FacilitapayAuthRequest {
fn from_auth_type(auth: &FacilitapayAuthType) -> Self {
Self {
user: FacilitapayCredentials {
username: auth.username.clone(),
password: auth.password.clone(),
},
}
}
}
impl TryFrom<&ConnectorAuthType> for FacilitapayAuthType {
type Error = Error;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
username: key1.to_owned(),
password: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<&RefreshTokenRouterData> for FacilitapayAuthRequest {
type Error = Error;
fn try_from(item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
let auth_type = FacilitapayAuthType::try_from(&item.connector_auth_type)?;
Ok(Self::from_auth_type(&auth_type))
}
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for FacilitapayConnectorMetadataObject {
type Error = Error;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
Ok(metadata)
}
}
impl TryFrom<&FacilitapayRouterData<&types::PaymentsAuthorizeRouterData>>
for FacilitapayPaymentsRequest
{
type Error = Error;
fn try_from(
item: &FacilitapayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let metadata =
FacilitapayConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?;
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankTransfer(bank_transfer_data) => match *bank_transfer_data {
BankTransferData::Pix {
source_bank_account_id,
..
} => {
// Set expiry time to 15 minutes from now
let dynamic_pix_expires_at = {
let now = time::OffsetDateTime::now_utc();
let expires_at = now + time::Duration::minutes(15);
PrimitiveDateTime::new(expires_at.date(), expires_at.time())
};
let transaction_data =
FacilitapayTransactionRequest::Pix(PixTransactionRequest {
// subject id must be generated by pre-process step and link with customer id
// might require discussions to be done
subject_id: item.router_data.get_connector_customer_id()?.into(),
from_bank_account_id: source_bank_account_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "source bank account id",
},
)?,
to_bank_account_id: metadata.destination_account_number,
currency: item.router_data.request.currency,
exchange_currency: item.router_data.request.currency,
value: item.amount.clone(),
use_dynamic_pix: true,
// Format: YYYY-MM-DDThh:mm:ssZ
dynamic_pix_expires_at,
});
Ok(Self {
transaction: transaction_data,
})
}
BankTransferData::AchBankTransfer {}
| BankTransferData::SepaBankTransfer {}
| BankTransferData::BacsBankTransfer {}
| BankTransferData::MultibancoBankTransfer {}
| BankTransferData::PermataBankTransfer {}
| BankTransferData::BcaBankTransfer {}
| BankTransferData::BniVaBankTransfer {}
| BankTransferData::BriVaBankTransfer {}
| BankTransferData::CimbVaBankTransfer {}
| BankTransferData::DanamonVaBankTransfer {}
| BankTransferData::MandiriVaBankTransfer {}
| BankTransferData::Pse {}
| BankTransferData::InstantBankTransfer {}
| BankTransferData::InstantBankTransferFinland {}
| BankTransferData::InstantBankTransferPoland {}
| BankTransferData::IndonesianBankTransfer { .. }
| BankTransferData::LocalBankTransfer { .. } => {
Err(errors::ConnectorError::NotImplemented(
"Selected payment method through Facilitapay".to_string(),
)
.into())
}
},
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
"Selected payment method through Facilitapay".to_string(),
)
.into())
}
}
}
}
fn convert_to_document_type(document_type: &str) -> Result<DocumentType, errors::ConnectorError> {
match document_type.to_lowercase().as_str() {
"cc" => Ok(DocumentType::CedulaDeCiudadania),
"cnpj" => Ok(DocumentType::CadastroNacionaldaPessoaJurídica),
"cpf" => Ok(DocumentType::CadastrodePessoasFísicas),
"curp" => Ok(DocumentType::ClaveÚnicadeRegistrodePoblación),
"nit" => Ok(DocumentType::NúmerodeIdentificaciónTributaria),
"passport" => Ok(DocumentType::Passport),
"rfc" => Ok(DocumentType::RegistroFederaldeContribuyentes),
"rut" => Ok(DocumentType::RolUnicoTributario),
"tax_id" | "taxid" => Ok(DocumentType::TaxId),
_ => Err(errors::ConnectorError::NotSupported {
message: format!("Document type '{document_type}'"),
connector: "Facilitapay",
}),
}
}
pub fn parse_facilitapay_error_response(
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let status_code = res.status_code;
let response_body_bytes = res.response.clone();
let (message, raw_error) =
match response_body_bytes.parse_struct::<serde_json::Value>("FacilitapayErrorResponse") {
Ok(json_value) => {
event_builder.map(|i| i.set_response_body(&json_value));
let message = extract_message_from_json(&json_value);
(
message,
serde_json::to_string(&json_value).unwrap_or_default(),
)
}
Err(_) => match String::from_utf8(response_body_bytes.to_vec()) {
Ok(text) => {
event_builder.map(|i| i.set_response_body(&text));
(text.clone(), text)
}
Err(_) => (
"Invalid response format received".to_string(),
format!(
"Unable to parse response as JSON or UTF-8 string. Status code: {status_code}",
),
),
},
};
Ok(ErrorResponse {
status_code,
code: consts::NO_ERROR_CODE.to_string(),
message,
reason: Some(raw_error),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
// Helper function to extract a readable message from JSON error
fn extract_message_from_json(json: &serde_json::Value) -> String {
if let Some(obj) = json.as_object() {
if let Some(error) = obj.get("error").and_then(|e| e.as_str()) {
return error.to_string();
}
if obj.contains_key("errors") {
return "Validation error occurred".to_string();
}
if !obj.is_empty() {
return obj
.iter()
.next()
.map(|(k, v)| format!("{k}: {v}"))
.unwrap_or_else(|| "Unknown error".to_string());
}
} else if let Some(s) = json.as_str() {
return s.to_string();
}
"Unknown error format".to_string()
}
impl TryFrom<&types::ConnectorCustomerRouterData> for FacilitapayCustomerRequest {
type Error = Error;
fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> {
let email = item.request.email.clone();
let social_name = item.get_billing_full_name()?;
let (document_type, document_number) = match item.request.payment_method_data.clone() {
Some(PaymentMethodData::BankTransfer(bank_transfer_data)) => {
match *bank_transfer_data {
BankTransferData::Pix { cpf, .. } => {
// Extract only digits from the CPF string
let document_number =
cpf.ok_or_else(missing_field_err("cpf"))?.map(|cpf_number| {
cpf_number
.chars()
.filter(|chars| chars.is_ascii_digit())
.collect::<String>()
});
let document_type = convert_to_document_type("cpf")?;
(document_type, document_number)
}
_ => {
return Err(errors::ConnectorError::NotImplemented(
"Selected payment method through Facilitapay".to_string(),
)
.into())
}
}
}
_ => {
return Err(errors::ConnectorError::NotImplemented(
"Selected payment method through Facilitapay".to_string(),
)
.into())
}
};
let fiscal_country = item.get_billing_country()?;
let person = FacilitapayPerson {
document_number,
document_type,
social_name,
fiscal_country,
email,
birth_date: None,
phone_country_code: None,
phone_area_code: None,
phone_number: None,
address_city: None,
address_state: None,
address_complement: None,
address_country: None,
address_number: None,
address_postal_code: None,
address_street: None,
net_monthly_average_income: None,
};
Ok(Self { person })
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FacilitapayCustomerResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, FacilitapayCustomerResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(
item.response.data.customer_id.expose(),
),
)),
..item.data
})
}
}
impl From<FacilitapayPaymentStatus> for common_enums::AttemptStatus {
fn from(item: FacilitapayPaymentStatus) -> Self {
match item {
FacilitapayPaymentStatus::Pending => Self::Pending,
FacilitapayPaymentStatus::Identified
| FacilitapayPaymentStatus::Exchanged
| FacilitapayPaymentStatus::Wired => Self::Charged,
FacilitapayPaymentStatus::Cancelled => Self::Failure,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FacilitapayAuthResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, FacilitapayAuthResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.jwt,
expires: 86400, // Facilitapay docs say 24 hours validity. 24 * 60 * 60 = 86400 seconds.
}),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FacilitapayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, FacilitapayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = if item.data.payment_method == PaymentMethod::BankTransfer
&& item.response.data.status == FacilitapayPaymentStatus::Identified
{
if item.response.data.currency != item.response.data.exchange_currency {
// Cross-currency: Identified is not terminal
common_enums::AttemptStatus::Pending
} else {
// Local currency: Identified is terminal
common_enums::AttemptStatus::Charged
}
} else {
common_enums::AttemptStatus::from(item.response.data.status.clone())
};
Ok(Self {
status,
response: if is_payment_failure(status) {
Err(ErrorResponse {
code: item.response.data.status.clone().to_string(),
message: item.response.data.status.clone().to_string(),
reason: item.response.data.cancelled_reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.data.transaction_id),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.data.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: get_qr_code_data(&item.response)?,
network_txn_id: None,
connector_response_reference_id: Some(item.response.data.transaction_id),
incremental_authorization_allowed: None,
charges: None,
})
},
..item.data
})
}
}
fn get_qr_code_data(
response: &FacilitapayPaymentsResponse,
) -> CustomResult<Option<serde_json::Value>, errors::ConnectorError> {
let expiration_time: i64 = if let Some(meta) = &response.data.meta {
if let Some(due_date_str) = meta
.get("dynamic_pix_due_date")
.and_then(|due_date_value| due_date_value.as_str())
{
let datetime = time::OffsetDateTime::parse(
due_date_str,
&time::format_description::well_known::Rfc3339,
)
.map_err(|_| errors::ConnectorError::ResponseHandlingFailed)?;
datetime.unix_timestamp() * 1000
} else {
// If dynamic_pix_due_date isn't present, use current time + 15 minutes
let now = time::OffsetDateTime::now_utc();
let expires_at = now + time::Duration::minutes(15);
expires_at.unix_timestamp() * 1000
}
} else {
// If meta is null, use current time + 15 minutes
let now = time::OffsetDateTime::now_utc();
let expires_at = now + time::Duration::minutes(15);
expires_at.unix_timestamp() * 1000
};
let dynamic_pix_code = response.data.dynamic_pix_code.as_ref().ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "dynamic_pix_code",
}
})?;
let image_data = QrImage::new_from_data(dynamic_pix_code.clone())
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let image_data_url = Url::parse(image_data.data.clone().as_str())
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let qr_code_info = QrCodeInformation::QrDataUrl {
image_data_url,
display_to_timestamp: Some(expiration_time),
};
Some(qr_code_info.encode_to_value())
.transpose()
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
impl From<FacilitapayPaymentStatus> for enums::RefundStatus {
fn from(item: FacilitapayPaymentStatus) -> Self {
match item {
FacilitapayPaymentStatus::Identified
| FacilitapayPaymentStatus::Exchanged
| FacilitapayPaymentStatus::Wired => Self::Success,
FacilitapayPaymentStatus::Cancelled => Self::Failure,
FacilitapayPaymentStatus::Pending => Self::Pending,
}
}
}
// Void (cancel unprocessed payment) transformer
impl
TryFrom<
ResponseRouterData<Void, FacilitapayVoidResponse, PaymentsCancelData, PaymentsResponseData>,
> for RouterData<Void, PaymentsCancelData, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<
Void,
FacilitapayVoidResponse,
PaymentsCancelData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = common_enums::AttemptStatus::from(item.response.data.status.clone());
Ok(Self {
status,
response: if is_payment_failure(status) {
Err(ErrorResponse {
code: item.response.data.status.clone().to_string(),
message: item.response.data.status.clone().to_string(),
reason: item.response.data.reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.data.void_id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.data.void_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.data.void_id),
incremental_authorization_allowed: None,
charges: None,
})
},
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<Execute, FacilitapayRefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<Execute, FacilitapayRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.data.transaction_id.clone(),
refund_status: enums::RefundStatus::from(item.response.data.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, FacilitapayRefundResponse>>
for types::RefundsRouterData<RSync>
{
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<RSync, FacilitapayRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.data.transaction_id.clone(),
refund_status: enums::RefundStatus::from(item.response.data.status),
}),
..item.data
})
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4832
}
|
large_file_3217522958592989618
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs
</path>
<file>
use common_utils::{pii, types::StringMajorUnit};
use masking::Secret;
use serde::{Deserialize, Serialize};
use super::requests::DocumentType;
// Response body for POST /sign_in
#[derive(Debug, Deserialize, Serialize)]
pub struct FacilitapayAuthResponse {
username: Secret<String>,
name: Secret<String>,
pub jwt: Secret<String>,
}
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SubjectKycStatus {
// Customer is able to send/receive money through the platform. No action is needed on your side.
Approved,
// Customer is required to upload documents or uploaded documents have been rejected by KYC.
Reproved,
// Customer has uploaded KYC documents but awaiting analysis from the backoffice. No action is needed on your side.
WaitingApproval,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct FacilitapaySubject {
pub social_name: Secret<String>,
pub document_type: DocumentType,
pub document_number: Secret<String>,
// In documentation, both CountryAlpha2 and String are used. We cannot rely on CountryAlpha2.
pub fiscal_country: String,
pub updated_at: Option<String>,
pub status: SubjectKycStatus,
#[serde(rename = "id")]
pub customer_id: Secret<String>,
pub birth_date: Option<time::Date>,
pub email: Option<pii::Email>,
pub phone_country_code: Option<Secret<String>>,
pub phone_area_code: Option<Secret<String>>,
pub phone_number: Option<Secret<String>>,
pub address_street: Option<Secret<String>>,
pub address_number: Option<Secret<String>>,
pub address_complement: Option<Secret<String>>,
pub address_city: Option<String>,
pub address_state: Option<String>,
pub address_postal_code: Option<Secret<String>>,
pub address_country: Option<String>,
pub address_neighborhood: Option<Secret<String>>,
pub net_monthly_average_income: Option<StringMajorUnit>,
pub clearance_level: Option<i32>,
pub required_clearance_level: Option<i32>,
pub inserted_at: Option<String>,
pub references: Option<Vec<serde_json::Value>>,
pub rfc_pf: Option<Secret<String>>, // 13-digit RFC, specific to Mexico users
pub documents: Option<Vec<serde_json::Value>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct FacilitapayCustomerResponse {
pub data: FacilitapaySubject,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PixInfo {
#[serde(rename = "type")]
pub key_type: String,
pub key: Secret<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CreditCardResponseInfo {
pub id: String,
pub status: Option<String>,
pub document_type: String,
pub document_number: Secret<String>,
pub birthdate: Option<String>,
pub phone_country_code: Option<String>,
pub phone_area_code: Option<String>,
pub phone_number: Option<Secret<String>>,
pub inserted_at: Option<String>,
}
// PaymentsResponse
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[derive(strum::Display)]
pub enum FacilitapayPaymentStatus {
/// Transaction has been created but it is waiting for an incoming TED/Wire.
/// This is the first recorded status in production mode.
#[default]
Pending,
/// Incoming TED/Wire has been identified into Facilita´s bank account.
/// When it is a deposit into an internal bank account and there is no
/// conversion involved (BRL to BRL for instance), that is the final state.
Identified,
/// The conversion rate has been closed and therefore the exchanged value
/// is defined - when it is a deposit into an internal bank account, that is the final state.
Exchanged,
/// The exchanged value has been wired to its destination (a real bank account) - that is also a final state.
Wired,
/// When for any reason the transaction cannot be concluded or need to be reversed, it is canceled.
#[serde(rename = "canceled")]
Cancelled,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FacilitapayPaymentsResponse {
pub data: TransactionData,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OwnerCompany {
pub social_name: Option<Secret<String>>,
#[serde(rename = "id")]
pub company_id: Option<String>,
pub document_type: DocumentType,
pub document_number: Secret<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct BankInfo {
pub swift: Option<Secret<String>>,
pub name: Option<String>,
#[serde(rename = "id")]
pub bank_id: Secret<String>,
pub code: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct BankAccountDetail {
pub routing_number: Option<Secret<String>>,
pub pix_info: Option<PixInfo>,
pub owner_name: Option<Secret<String>>,
pub owner_document_type: Option<String>,
pub owner_document_number: Option<Secret<String>>,
pub owner_company: Option<OwnerCompany>,
pub internal: Option<bool>,
pub intermediary_bank_account: Option<Secret<String>>,
pub intermediary_bank_account_id: Option<Secret<String>>,
#[serde(rename = "id")]
pub bank_account_id: Secret<String>,
pub iban: Option<Secret<String>>,
pub flow_type: Option<String>,
pub currency: api_models::enums::Currency,
pub branch_number: Option<Secret<String>>,
pub branch_country: Option<String>,
pub bank: Option<BankInfo>,
pub account_type: Option<String>,
pub account_number: Option<Secret<String>>,
pub aba: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TransactionData {
#[serde(rename = "id")]
pub transaction_id: String,
pub value: StringMajorUnit,
pub status: FacilitapayPaymentStatus,
pub currency: api_models::enums::Currency,
pub exchange_currency: api_models::enums::Currency,
// Details about the destination account (Required)
pub to_bank_account: BankAccountDetail,
// Details about the source - mutually exclusive
pub from_credit_card: Option<CreditCardResponseInfo>,
pub from_bank_account: Option<BankAccountDetail>, // Populated for PIX
// Subject information (customer)
pub subject_id: String,
pub subject: Option<FacilitapaySubject>,
pub subject_is_receiver: Option<bool>,
// Source identification (potentially redundant with subject or card/bank info)
pub source_name: Option<Secret<String>>,
pub source_document_type: DocumentType,
pub source_document_number: Secret<String>,
// Timestamps and flags
pub inserted_at: Option<String>,
pub for_exchange: Option<bool>,
pub exchange_under_request: Option<bool>,
pub estimated_value_until_exchange: Option<bool>,
pub cleared: Option<bool>,
// PIX specific field
pub dynamic_pix_code: Option<String>, // QR code string for PIX
// Exchange details
pub exchanged_value: Option<StringMajorUnit>,
// Cancelation details
#[serde(rename = "canceled_reason")]
pub cancelled_reason: Option<String>,
#[serde(rename = "canceled_at")]
pub cancelled_at: Option<String>,
// Other fields
pub bank_transaction: Option<Secret<serde_json::Value>>,
pub meta: Option<serde_json::Value>,
}
// Void response structures (for /refund endpoint)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VoidBankTransaction {
#[serde(rename = "id")]
pub transaction_id: String,
pub value: StringMajorUnit,
pub currency: api_models::enums::Currency,
pub iof_value: Option<StringMajorUnit>,
pub fx_value: Option<StringMajorUnit>,
pub exchange_rate: Option<StringMajorUnit>,
pub exchange_currency: api_models::enums::Currency,
pub exchanged_value: StringMajorUnit,
pub exchange_approved: bool,
pub wire_id: Option<String>,
pub exchange_id: Option<String>,
pub movement_date: String,
pub source_name: Secret<String>,
pub source_document_number: Secret<String>,
pub source_document_type: String,
pub source_id: String,
pub source_type: String,
pub source_description: String,
pub source_bank: Option<String>,
pub source_branch: Option<String>,
pub source_account: Option<String>,
pub source_bank_ispb: Option<String>,
pub company_id: String,
pub company_name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VoidData {
#[serde(rename = "id")]
pub void_id: String,
pub reason: Option<String>,
pub inserted_at: String,
pub status: FacilitapayPaymentStatus,
pub transaction_kind: String,
pub bank_transaction: VoidBankTransaction,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FacilitapayVoidResponse {
pub data: VoidData,
}
// Refund response uses the same TransactionData structure as payments
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FacilitapayRefundResponse {
pub data: TransactionData,
}
// Webhook structures
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FacilitapayWebhookNotification {
pub notification: FacilitapayWebhookBody,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct FacilitapayWebhookBody {
#[serde(rename = "type")]
pub event_type: FacilitapayWebhookEventType,
pub secret: Secret<String>,
#[serde(flatten)]
pub data: FacilitapayWebhookData,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum FacilitapayWebhookEventType {
ExchangeCreated,
Identified,
PaymentApproved,
PaymentExpired,
PaymentFailed,
PaymentRefunded,
WireCreated,
WireWaitingCorrection,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum FacilitapayWebhookErrorCode {
/// Creditor account number invalid or missing (branch_number or account_number incorrect)
Ac03,
/// Creditor account type missing or invalid (account_type incorrect)
Ac14,
/// Value in Creditor Identifier is incorrect (owner_document_number incorrect)
Ch11,
/// Transaction type not supported/authorized on this account (account rejected the payment)
Ag03,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FacilitapayWebhookData {
CardPayment {
transaction_id: String,
checkout_id: Option<String>,
},
Exchange {
exchange_id: String,
transaction_ids: Vec<String>,
},
Transaction {
transaction_id: String,
},
Wire {
wire_id: String,
transaction_ids: Vec<String>,
},
WireError {
error_code: FacilitapayWebhookErrorCode,
error_description: String,
bank_account_owner_id: String,
bank_account_id: String,
transaction_ids: Vec<String>,
wire_id: String,
},
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2490
}
|
large_file_-5343947221960150487
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs
</path>
<file>
use common_enums::enums;
use common_utils::types::FloatMajorUnit;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{MobilePaymentData, PaymentMethodData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, PaymentsCompleteAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData},
};
pub struct DigitalvirgoRouterData<T> {
pub amount: FloatMajorUnit,
pub surcharge_amount: Option<FloatMajorUnit>,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, Option<FloatMajorUnit>, T)> for DigitalvirgoRouterData<T> {
fn from((amount, surcharge_amount, item): (FloatMajorUnit, Option<FloatMajorUnit>, T)) -> Self {
Self {
amount,
surcharge_amount,
router_data: item,
}
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DigitalvirgoPaymentsRequest {
amount: FloatMajorUnit,
amount_surcharge: Option<FloatMajorUnit>,
client_uid: Option<String>,
msisdn: String,
product_name: String,
description: Option<String>,
partner_transaction_id: String,
}
impl TryFrom<&DigitalvirgoRouterData<&PaymentsAuthorizeRouterData>>
for DigitalvirgoPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DigitalvirgoRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::MobilePayment(mobile_payment_data) => match mobile_payment_data {
MobilePaymentData::DirectCarrierBilling { msisdn, client_uid } => {
let order_details = item.router_data.request.get_order_details()?;
let product_name = order_details
.first()
.map(|order| order.product_name.to_owned())
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "product_name",
})?;
Ok(Self {
amount: item.amount.to_owned(),
amount_surcharge: item.surcharge_amount.to_owned(),
client_uid,
msisdn,
product_name,
description: item.router_data.description.to_owned(),
partner_transaction_id: item
.router_data
.connector_request_reference_id
.to_owned(),
})
}
},
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
pub struct DigitalvirgoAuthType {
pub(super) username: Secret<String>,
pub(super) password: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for DigitalvirgoAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
username: key1.to_owned(),
password: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DigitalvirgoPaymentStatus {
Ok,
ConfirmPayment,
}
impl From<DigitalvirgoPaymentStatus> for common_enums::AttemptStatus {
fn from(item: DigitalvirgoPaymentStatus) -> Self {
match item {
DigitalvirgoPaymentStatus::Ok => Self::Charged,
DigitalvirgoPaymentStatus::ConfirmPayment => Self::AuthenticationPending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DigitalvirgoPaymentsResponse {
state: DigitalvirgoPaymentStatus,
transaction_id: String,
consent: Option<DigitalvirgoConsentStatus>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DigitalvirgoConsentStatus {
required: Option<bool>,
}
impl<F, T> TryFrom<ResponseRouterData<F, DigitalvirgoPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DigitalvirgoPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
// show if consent is required in next action
let connector_metadata = item
.response
.consent
.and_then(|consent_status| {
consent_status.required.map(|consent_required| {
if consent_required {
serde_json::json!({
"consent_data_required": "consent_required",
})
} else {
serde_json::json!({
"consent_data_required": "consent_not_required",
})
}
})
})
.or(Some(serde_json::json!({
"consent_data_required": "consent_not_required",
})));
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.transaction_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DigitalvirgoPaymentSyncStatus {
Accepted,
Payed,
Pending,
Cancelled,
Rejected,
Locked,
}
impl From<DigitalvirgoPaymentSyncStatus> for common_enums::AttemptStatus {
fn from(item: DigitalvirgoPaymentSyncStatus) -> Self {
match item {
DigitalvirgoPaymentSyncStatus::Accepted => Self::AuthenticationPending,
DigitalvirgoPaymentSyncStatus::Payed => Self::Charged,
DigitalvirgoPaymentSyncStatus::Pending | DigitalvirgoPaymentSyncStatus::Locked => {
Self::Pending
}
DigitalvirgoPaymentSyncStatus::Cancelled => Self::Voided,
DigitalvirgoPaymentSyncStatus::Rejected => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DigitalvirgoPaymentSyncResponse {
payment_status: DigitalvirgoPaymentSyncStatus,
transaction_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, DigitalvirgoPaymentSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DigitalvirgoPaymentSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.payment_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.transaction_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DigitalvirgoConfirmRequest {
transaction_id: String,
token: Secret<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DigitalvirgoRedirectResponseData {
otp: Secret<String>,
}
impl TryFrom<&PaymentsCompleteAuthorizeRouterData> for DigitalvirgoConfirmRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> {
let payload_data = item.request.get_redirect_response_payload()?.expose();
let otp_data: DigitalvirgoRedirectResponseData = serde_json::from_value(payload_data)
.change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "otp for transaction",
})?;
Ok(Self {
transaction_id: item
.request
.connector_transaction_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorTransactionID)?,
token: otp_data.otp,
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct DigitalvirgoRefundRequest {
pub amount: FloatMajorUnit,
}
impl<F> TryFrom<&DigitalvirgoRouterData<&RefundsRouterData<F>>> for DigitalvirgoRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &DigitalvirgoRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DigitalvirgoErrorResponse {
pub cause: Option<String>,
pub operation_error: Option<String>,
pub description: Option<String>,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2502
}
|
large_file_5756509263765013174
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/breadpay/transformers.rs
</path>
<file>
use common_enums::enums;
use common_utils::{request::Method, types::StringMinorUnit};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, PaymentsAuthorizeRequestData},
};
pub struct BreadpayRouterData<T> {
pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for BreadpayRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BreadpayCartRequest {
custom_total: StringMinorUnit,
options: Option<BreadpayCartOptions>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BreadpayCartOptions {
order_ref: Option<String>,
complete_url: String,
callback_url: String,
// billing_contact: Option<BillingContact>,
}
// #[derive(Debug, Serialize)]
// #[serde(rename_all = "camelCase")]
// pub struct BillingContact {
// first_name: Secret<String>,
// last_name: Secret<String>,
// email: Option<Email>,
// address: Secret<String>,
// city: Secret<String>,
// state: Secret<String>,
// }
impl TryFrom<&BreadpayRouterData<&PaymentsAuthorizeRouterData>> for BreadpayCartRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BreadpayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let request = match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::PayLater(pay_later_data) => match pay_later_data{
hyperswitch_domain_models::payment_method_data::PayLaterData::BreadpayRedirect { } => {
// let billing_contact = BillingContact {
// first_name: item.router_data.get_billing_first_name()?,
// last_name: item.router_data.get_billing_last_name()?,
// email: item.router_data.get_optional_billing_email(),
// address: item.router_data.get_billing_line1()?,
// city: item.router_data.get_billing_city()?.into(),
// state: item.router_data.get_billing_state()?,
// };
let options = Some({
BreadpayCartOptions {
order_ref: item.router_data.request.merchant_order_reference_id.clone(),
complete_url: item.router_data.request.get_complete_authorize_url()?,
callback_url: item.router_data.request.get_router_return_url()?
// billing_contact: Some(billing_contact)
}
});
Self{
custom_total: item.amount.clone(),
options,
}
},
hyperswitch_domain_models::payment_method_data::PayLaterData::KlarnaRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::WalleyRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::KlarnaSdk { .. } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AffirmRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::FlexitiRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AfterpayClearpayRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::PayBrightRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AlmaRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AtomeRedirect { } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("breadpay"),
))
}?,
},
PaymentMethodData::Card(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(
_,
)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::MobilePayment(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("breadpay"),
))
}?
};
Ok(request)
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BreadpayTransactionRequest {
#[serde(rename = "type")]
pub transaction_type: BreadpayTransactionType,
}
#[derive(Debug, Serialize)]
pub enum BreadpayTransactionType {
Authorize,
Settle,
Cancel,
Refund,
}
// Auth Struct
pub struct BreadpayAuthType {
pub(super) api_key: Secret<String>,
pub(super) api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BreadpayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
api_secret: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BreadpayTransactionResponse {
status: TransactionStatus,
bread_transactin_id: String,
merchant_order_id: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionStatus {
Pending,
Canceled,
Refunded,
Expired,
Authorized,
Settled,
}
impl<F, T> TryFrom<ResponseRouterData<F, BreadpayTransactionResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BreadpayTransactionResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.bread_transactin_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl From<TransactionStatus> for enums::AttemptStatus {
fn from(item: TransactionStatus) -> Self {
match item {
TransactionStatus::Pending => Self::Pending,
TransactionStatus::Authorized => Self::Authorized,
TransactionStatus::Canceled => Self::Voided,
TransactionStatus::Refunded => Self::AutoRefunded,
TransactionStatus::Expired => Self::Failure,
TransactionStatus::Settled => Self::Charged,
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BreadpayPaymentsResponse {
url: url::Url,
}
impl<F, T> TryFrom<ResponseRouterData<F, BreadpayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BreadpayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
// As per documentation, the first call is cart creation where we don't get any status only get the customer redirection url.
status: common_enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::from((
item.response.url,
Method::Get,
)))),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CallBackResponse {
pub transaction_id: String,
pub order_ref: String,
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
pub struct BreadpayRefundRequest {
pub amount: StringMinorUnit,
#[serde(rename = "type")]
pub transaction_type: BreadpayTransactionType,
}
impl<F> TryFrom<&BreadpayRouterData<&RefundsRouterData<F>>> for BreadpayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &BreadpayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
transaction_type: BreadpayTransactionType::Refund,
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BreadpayErrorResponse {
/// Human-readable error description
pub description: String,
/// Error type classification
#[serde(rename = "type")]
pub error_type: String,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/breadpay/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2681
}
|
large_file_-7183931592753893526
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/dummyconnector/transformers.rs
</path>
<file>
use common_enums::{AttemptStatus, Currency, RefundStatus};
use common_utils::{pii, request::Method, types::MinorUnit};
use hyperswitch_domain_models::{
payment_method_data::{
Card, PayLaterData, PaymentMethodData, UpiCollectData, UpiData, WalletData,
},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::Secret;
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::RouterData as _,
};
#[derive(Debug, Serialize)]
pub struct DummyConnectorRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for DummyConnectorRouterData<T> {
fn from((amount, router_data): (MinorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Serialize, strum::Display, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum DummyConnectors {
#[serde(rename = "phonypay")]
#[strum(serialize = "phonypay")]
PhonyPay,
#[serde(rename = "fauxpay")]
#[strum(serialize = "fauxpay")]
FauxPay,
#[serde(rename = "pretendpay")]
#[strum(serialize = "pretendpay")]
PretendPay,
StripeTest,
AdyenTest,
CheckoutTest,
PaypalTest,
}
impl DummyConnectors {
pub fn get_dummy_connector_id(self) -> &'static str {
match self {
Self::PhonyPay => "phonypay",
Self::FauxPay => "fauxpay",
Self::PretendPay => "pretendpay",
Self::StripeTest => "stripe_test",
Self::AdyenTest => "adyen_test",
Self::CheckoutTest => "checkout_test",
Self::PaypalTest => "paypal_test",
}
}
}
impl From<u8> for DummyConnectors {
fn from(value: u8) -> Self {
match value {
1 => Self::PhonyPay,
2 => Self::FauxPay,
3 => Self::PretendPay,
4 => Self::StripeTest,
5 => Self::AdyenTest,
6 => Self::CheckoutTest,
7 => Self::PaypalTest,
_ => Self::PhonyPay,
}
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct DummyConnectorPaymentsRequest<const T: u8> {
amount: MinorUnit,
currency: Currency,
payment_method_data: DummyPaymentMethodData,
return_url: Option<String>,
connector: DummyConnectors,
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum DummyPaymentMethodData {
Card(DummyConnectorCard),
Wallet(DummyConnectorWallet),
PayLater(DummyConnectorPayLater),
Upi(DummyConnectorUpi),
}
#[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DummyConnectorUpi {
UpiCollect(DummyConnectorUpiCollect),
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct DummyConnectorUpiCollect {
vpa_id: Secret<String, pii::UpiVpaMaskingStrategy>,
}
impl TryFrom<UpiCollectData> for DummyConnectorUpi {
type Error = error_stack::Report<ConnectorError>;
fn try_from(value: UpiCollectData) -> Result<Self, Self::Error> {
Ok(Self::UpiCollect(DummyConnectorUpiCollect {
vpa_id: value.vpa_id.ok_or(ConnectorError::MissingRequiredField {
field_name: "vpa_id",
})?,
}))
}
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct DummyConnectorCard {
name: Secret<String>,
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
}
impl TryFrom<(Card, Option<Secret<String>>)> for DummyConnectorCard {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
(value, card_holder_name): (Card, Option<Secret<String>>),
) -> Result<Self, Self::Error> {
Ok(Self {
name: card_holder_name.unwrap_or(Secret::new("".to_string())),
number: value.card_number,
expiry_month: value.card_exp_month,
expiry_year: value.card_exp_year,
cvc: value.card_cvc,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum DummyConnectorWallet {
GooglePay,
Paypal,
WeChatPay,
MbWay,
AliPay,
AliPayHK,
}
impl TryFrom<WalletData> for DummyConnectorWallet {
type Error = error_stack::Report<ConnectorError>;
fn try_from(value: WalletData) -> Result<Self, Self::Error> {
match value {
WalletData::GooglePayRedirect(_) => Ok(Self::GooglePay),
WalletData::PaypalRedirect(_) => Ok(Self::Paypal),
WalletData::WeChatPayRedirect(_) => Ok(Self::WeChatPay),
WalletData::MbWayRedirect(_) => Ok(Self::MbWay),
WalletData::AliPayRedirect(_) => Ok(Self::AliPay),
WalletData::AliPayHkRedirect(_) => Ok(Self::AliPayHK),
_ => Err(ConnectorError::NotImplemented("Dummy wallet".to_string()).into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum DummyConnectorPayLater {
Klarna,
Affirm,
AfterPayClearPay,
}
impl TryFrom<PayLaterData> for DummyConnectorPayLater {
type Error = error_stack::Report<ConnectorError>;
fn try_from(value: PayLaterData) -> Result<Self, Self::Error> {
match value {
PayLaterData::KlarnaRedirect { .. } => Ok(Self::Klarna),
PayLaterData::AffirmRedirect {} => Ok(Self::Affirm),
PayLaterData::AfterpayClearpayRedirect { .. } => Ok(Self::AfterPayClearPay),
_ => Err(ConnectorError::NotImplemented("Dummy pay later".to_string()).into()),
}
}
}
impl<const T: u8> TryFrom<&DummyConnectorRouterData<&PaymentsAuthorizeRouterData>>
for DummyConnectorPaymentsRequest<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &DummyConnectorRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payment_method_data: Result<DummyPaymentMethodData, Self::Error> =
match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref req_card) => {
let card_holder_name = item.router_data.get_optional_billing_full_name();
Ok(DummyPaymentMethodData::Card(DummyConnectorCard::try_from(
(req_card.clone(), card_holder_name),
)?))
}
PaymentMethodData::Upi(ref req_upi_data) => match req_upi_data {
UpiData::UpiCollect(data) => Ok(DummyPaymentMethodData::Upi(
DummyConnectorUpi::try_from(data.clone())?,
)),
UpiData::UpiIntent(_) | UpiData::UpiQr(_) => {
Err(ConnectorError::NotImplemented("UPI flow".to_string()).into())
}
},
PaymentMethodData::Wallet(ref wallet_data) => Ok(DummyPaymentMethodData::Wallet(
wallet_data.clone().try_into()?,
)),
PaymentMethodData::PayLater(ref pay_later_data) => Ok(
DummyPaymentMethodData::PayLater(pay_later_data.clone().try_into()?),
),
_ => Err(ConnectorError::NotImplemented("Payment methods".to_string()).into()),
};
Ok(Self {
amount: item.router_data.request.minor_amount,
currency: item.router_data.request.currency,
payment_method_data: payment_method_data?,
return_url: item.router_data.request.router_return_url.clone(),
connector: Into::<DummyConnectors>::into(T),
})
}
}
// Auth Struct
pub struct DummyConnectorAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for DummyConnectorAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
//TODO: Append the remaining status flags
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum DummyConnectorPaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<DummyConnectorPaymentStatus> for AttemptStatus {
fn from(item: DummyConnectorPaymentStatus) -> Self {
match item {
DummyConnectorPaymentStatus::Succeeded => Self::Charged,
DummyConnectorPaymentStatus::Failed => Self::Failure,
DummyConnectorPaymentStatus::Processing => Self::AuthenticationPending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PaymentsResponse {
status: DummyConnectorPaymentStatus,
id: String,
amount: MinorUnit,
currency: Currency,
created: String,
payment_method_type: PaymentMethodType,
next_action: Option<DummyConnectorNextAction>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum PaymentMethodType {
Card,
Upi(DummyConnectorUpiType),
Wallet(DummyConnectorWallet),
PayLater(DummyConnectorPayLater),
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum DummyConnectorUpiType {
UpiCollect,
}
impl<F, T> TryFrom<ResponseRouterData<F, PaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.next_action
.and_then(|redirection_data| redirection_data.get_url())
.map(|redirection_url| RedirectForm::from((redirection_url, Method::Get)));
Ok(Self {
status: AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum DummyConnectorNextAction {
RedirectToUrl(Url),
}
impl DummyConnectorNextAction {
fn get_url(&self) -> Option<Url> {
match self {
Self::RedirectToUrl(redirect_to_url) => Some(redirect_to_url.to_owned()),
}
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct DummyConnectorRefundRequest {
pub amount: MinorUnit,
}
impl<F> TryFrom<&DummyConnectorRouterData<&RefundsRouterData<F>>> for DummyConnectorRefundRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &DummyConnectorRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.router_data.request.minor_refund_amount,
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
#[serde(rename_all = "lowercase")]
pub enum DummyRefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<DummyRefundStatus> for RefundStatus {
fn from(item: DummyRefundStatus) -> Self {
match item {
DummyRefundStatus::Succeeded => Self::Success,
DummyRefundStatus::Failed => Self::Failure,
DummyRefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: DummyRefundStatus,
currency: Currency,
created: String,
payment_amount: MinorUnit,
refund_amount: MinorUnit,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DummyConnectorErrorResponse {
pub error: ErrorData,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct ErrorData {
pub code: String,
pub message: String,
pub reason: Option<String>,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/dummyconnector/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3232
}
|
large_file_3583427740440250533
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs
</path>
<file>
#[cfg(feature = "payouts")]
use common_enums::enums::PayoutEntityType;
use common_enums::{enums, Currency, PayoutStatus};
use common_utils::{pii::Email, types::FloatMajorUnit};
use hyperswitch_domain_models::router_data::ConnectorAuthType;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_response_types::PayoutsResponseData, types::PayoutsRouterData,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
#[cfg(feature = "payouts")]
use crate::utils::PayoutFulfillRequestData;
#[cfg(feature = "payouts")]
use crate::{types::PayoutsResponseRouterData, utils::RouterData as UtilsRouterData};
pub const PURPOSE_OF_PAYMENT_IS_OTHER: &str = "OTHER";
pub struct NomupayRouterData<T> {
pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for NomupayRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
}
}
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Address {
pub country: enums::CountryAlpha2,
pub state_province: Secret<String>,
pub street: Secret<String>,
pub city: String,
pub postal_code: Secret<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum ProfileType {
#[default]
Individual,
Businness,
}
#[cfg(feature = "payouts")]
impl From<PayoutEntityType> for ProfileType {
fn from(entity: PayoutEntityType) -> Self {
match entity {
PayoutEntityType::Personal
| PayoutEntityType::NaturalPerson
| PayoutEntityType::Individual => Self::Individual,
_ => Self::Businness,
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub enum NomupayGender {
Male,
Female,
#[default]
Other,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Profile {
pub profile_type: ProfileType,
pub first_name: Secret<String>,
pub last_name: Secret<String>,
pub date_of_birth: Secret<String>,
pub gender: NomupayGender,
pub email_address: Email,
pub phone_number_country_code: Option<String>,
pub phone_number: Option<Secret<String>>,
pub address: Address,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct OnboardSubAccountRequest {
pub account_id: Secret<String>,
pub client_sub_account_id: Secret<String>,
pub profile: Profile,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct BankAccount {
pub bank_id: Option<Secret<String>>,
pub account_id: Secret<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct VirtualAccountsType {
pub country_code: String,
pub currency_code: String,
pub bank_id: Secret<String>,
pub bank_account_id: Secret<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransferMethodType {
#[default]
BankAccount,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct OnboardTransferMethodRequest {
pub country_code: enums::CountryAlpha2,
pub currency_code: Currency,
#[serde(rename = "type")]
pub transfer_method_type: TransferMethodType,
pub display_name: Secret<String>,
pub bank_account: BankAccount,
pub profile: Profile,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct NomupayPaymentRequest {
pub source_id: Secret<String>,
pub destination_id: Secret<String>,
pub payment_reference: String,
pub amount: FloatMajorUnit,
pub currency_code: Currency,
pub purpose: String,
pub description: Option<String>,
pub internal_memo: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct QuoteRequest {
pub source_id: Secret<String>,
pub source_currency_code: Currency,
pub destination_currency_code: Currency,
pub amount: FloatMajorUnit,
pub include_fee: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct CommitRequest {
pub source_id: Secret<String>,
pub id: String,
pub destination_id: Secret<String>,
pub payment_reference: String,
pub amount: FloatMajorUnit,
pub currency_code: Currency,
pub purpose: String,
pub description: String,
pub internal_memo: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct OnboardSubAccountResponse {
pub account_id: Secret<String>,
pub id: String,
pub client_sub_account_id: Secret<String>,
pub profile: Profile,
pub virtual_accounts: Vec<VirtualAccountsType>,
pub status: String,
pub created_on: String,
pub last_updated: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct OnboardTransferMethodResponse {
pub parent_id: Secret<String>,
pub account_id: Secret<String>,
pub sub_account_id: Secret<String>,
pub id: String,
pub status: String,
pub created_on: String,
pub last_updated: String,
pub country_code: String,
pub currency_code: Currency,
pub display_name: String,
#[serde(rename = "type")]
pub transfer_method_type: String,
pub profile: Profile,
pub bank_account: BankAccount,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct NomupayPaymentResponse {
pub id: String,
pub status: NomupayPaymentStatus,
pub created_on: String,
pub last_updated: String,
pub source_id: Secret<String>,
pub destination_id: Secret<String>,
pub payment_reference: String,
pub amount: FloatMajorUnit,
pub currency_code: String,
pub purpose: String,
pub description: String,
pub internal_memo: String,
pub release_on: String,
pub expire_on: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct FeesType {
#[serde(rename = "type")]
pub fees_type: String,
pub fees: FloatMajorUnit,
pub currency_code: Currency,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PayoutQuoteResponse {
pub source_id: Secret<String>,
pub destination_currency_code: Currency,
pub amount: FloatMajorUnit,
pub source_currency_code: Currency,
pub include_fee: bool,
pub fees: Vec<FeesType>,
pub payment_reference: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct CommitResponse {
pub id: String,
pub status: String,
pub created_on: String,
pub last_updated: String,
pub source_id: Secret<String>,
pub destination_id: Secret<String>,
pub payment_reference: String,
pub amount: FloatMajorUnit,
pub currency_code: Currency,
pub purpose: String,
pub description: String,
pub internal_memo: String,
pub release_on: String,
pub expire_on: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct NomupayMetadata {
pub private_key: Secret<String>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ValidationError {
pub field: String,
pub message: String,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DetailsType {
pub loc: Vec<String>,
#[serde(rename = "type")]
pub error_type: String,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct NomupayInnerError {
pub error_code: String,
pub error_description: Option<String>,
pub validation_errors: Option<Vec<ValidationError>>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct NomupayErrorResponse {
pub status: Option<String>,
pub code: Option<u64>,
pub error: Option<NomupayInnerError>,
pub status_code: Option<u16>,
pub detail: Option<Vec<DetailsType>>,
}
pub struct NomupayAuthType {
pub(super) kid: Secret<String>,
#[cfg(feature = "payouts")]
pub(super) eid: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for NomupayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
#[cfg(feature = "payouts")]
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
kid: api_key.to_owned(),
eid: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum NomupayPaymentStatus {
Pending,
Processed,
Failed,
#[default]
Processing,
Scheduled,
PendingAccountActivation,
PendingTransferMethodCreation,
PendingAccountKyc,
}
impl From<NomupayPaymentStatus> for PayoutStatus {
fn from(item: NomupayPaymentStatus) -> Self {
match item {
NomupayPaymentStatus::Processed => Self::Success,
NomupayPaymentStatus::Failed => Self::Failed,
NomupayPaymentStatus::Processing
| NomupayPaymentStatus::Pending
| NomupayPaymentStatus::Scheduled
| NomupayPaymentStatus::PendingAccountActivation
| NomupayPaymentStatus::PendingTransferMethodCreation
| NomupayPaymentStatus::PendingAccountKyc => Self::Pending,
}
}
}
#[cfg(feature = "payouts")]
fn get_profile<F>(
item: &PayoutsRouterData<F>,
entity_type: PayoutEntityType,
) -> Result<Profile, error_stack::Report<errors::ConnectorError>> {
let my_address = Address {
country: item.get_billing_country()?,
state_province: item.get_billing_state()?,
street: item.get_billing_line1()?,
city: item.get_billing_city()?,
postal_code: item.get_billing_zip()?,
};
Ok(Profile {
profile_type: ProfileType::from(entity_type),
first_name: item.get_billing_first_name()?,
last_name: item.get_billing_last_name()?,
date_of_birth: Secret::new("1991-01-01".to_string()), // Query raised with Nomupay regarding why this field is required
gender: NomupayGender::Other, // Query raised with Nomupay regarding why this field is required
email_address: item.get_billing_email()?,
phone_number_country_code: item
.get_billing_phone()
.map(|phone| phone.country_code.clone())?,
phone_number: Some(item.get_billing_phone_number()?),
address: my_address,
})
}
// PoRecipient Request
#[cfg(feature = "payouts")]
impl<F> TryFrom<&PayoutsRouterData<F>> for OnboardSubAccountRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
let payout_type = request.payout_type;
let profile = get_profile(item, request.entity_type)?;
let nomupay_auth_type = NomupayAuthType::try_from(&item.connector_auth_type)?;
match payout_type {
Some(common_enums::PayoutType::Bank) => Ok(Self {
account_id: nomupay_auth_type.eid,
client_sub_account_id: Secret::new(item.connector_request_reference_id.clone()),
profile,
}),
_ => Err(errors::ConnectorError::NotImplemented(
"This payment method is not implemented for Nomupay".to_string(),
)
.into()),
}
}
}
// PoRecipient Response
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, OnboardSubAccountResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, OnboardSubAccountResponse>,
) -> Result<Self, Self::Error> {
let response: OnboardSubAccountResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::RequiresVendorAccountCreation),
connector_payout_id: Some(response.id.to_string()),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
// PoRecipientAccount Request
#[cfg(feature = "payouts")]
impl<F> TryFrom<&PayoutsRouterData<F>> for OnboardTransferMethodRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let payout_method_data = item.get_payout_method_data()?;
match payout_method_data {
api_models::payouts::PayoutMethodData::Bank(bank) => match bank {
api_models::payouts::Bank::Sepa(bank_details) => {
let bank_account = BankAccount {
bank_id: bank_details.bic,
account_id: bank_details.iban,
};
let country_iso2_code = item
.get_billing_country()
.unwrap_or(enums::CountryAlpha2::CA);
let profile = get_profile(item, item.request.entity_type)?;
Ok(Self {
country_code: country_iso2_code,
currency_code: item.request.destination_currency,
transfer_method_type: TransferMethodType::BankAccount,
display_name: item.get_billing_full_name()?,
bank_account,
profile,
})
}
other_bank => Err(errors::ConnectorError::NotSupported {
message: format!("{other_bank:?} is not supported"),
connector: "nomupay",
}
.into()),
},
_ => Err(errors::ConnectorError::NotImplemented(
"This payment method is not implemented for Nomupay".to_string(),
)
.into()),
}
}
}
// PoRecipientAccount response
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, OnboardTransferMethodResponse>>
for PayoutsRouterData<F>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, OnboardTransferMethodResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::RequiresCreation),
connector_payout_id: Some(item.response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
// PoFulfill Request
#[cfg(feature = "payouts")]
impl<F> TryFrom<(&PayoutsRouterData<F>, FloatMajorUnit)> for NomupayPaymentRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, amount): (&PayoutsRouterData<F>, FloatMajorUnit),
) -> Result<Self, Self::Error> {
let nomupay_auth_type = NomupayAuthType::try_from(&item.connector_auth_type)?;
let destination = item.request.clone().get_connector_transfer_method_id()?;
Ok(Self {
source_id: nomupay_auth_type.eid,
destination_id: Secret::new(destination),
payment_reference: item.connector_request_reference_id.clone(),
amount,
currency_code: item.request.destination_currency,
purpose: PURPOSE_OF_PAYMENT_IS_OTHER.to_string(),
description: item.description.clone(),
internal_memo: item.description.clone(),
})
}
}
// PoFulfill response
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, NomupayPaymentResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, NomupayPaymentResponse>,
) -> Result<Self, Self::Error> {
let response: NomupayPaymentResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::from(response.status)),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3917
}
|
large_file_-3889580990835560568
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs
</path>
<file>
use std::collections::HashMap;
use common_enums::{enums, CardNetwork};
use common_utils::{
pii::{self},
request::Method,
types::StringMajorUnit,
};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ErrorResponse, PaymentMethodToken, RouterData,
},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{BrowserInformation, PaymentsAuthorizeData, ResponseId},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundsRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
},
unimplemented_payment_method,
utils::{self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, RouterData as _},
};
pub struct HipayRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for HipayRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Operation {
Authorization,
Sale,
Capture,
Refund,
Cancel,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct HipayBrowserInfo {
java_enabled: Option<bool>,
javascript_enabled: Option<bool>,
ipaddr: Option<std::net::IpAddr>,
http_accept: String,
http_user_agent: Option<String>,
language: Option<String>,
color_depth: Option<u8>,
screen_height: Option<u32>,
screen_width: Option<u32>,
timezone: Option<i32>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct HipayPaymentsRequest {
operation: Operation,
authentication_indicator: u8,
cardtoken: Secret<String>,
orderid: String,
currency: enums::Currency,
payment_product: String,
amount: StringMajorUnit,
description: String,
decline_url: Option<String>,
pending_url: Option<String>,
cancel_url: Option<String>,
accept_url: Option<String>,
notify_url: Option<String>,
#[serde(flatten)]
#[serde(skip_serializing_if = "Option::is_none")]
three_ds_data: Option<ThreeDSPaymentData>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ThreeDSPaymentData {
#[serde(skip_serializing_if = "Option::is_none")]
pub firstname: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub lastname: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<pii::Email>,
#[serde(skip_serializing_if = "Option::is_none")]
pub streetaddress: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub city: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub zipcode: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub country: Option<enums::CountryAlpha2>,
#[serde(skip_serializing_if = "Option::is_none")]
pub browser_info: Option<HipayBrowserInfo>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct HipayMaintenanceRequest {
operation: Operation,
currency: Option<enums::Currency>,
amount: Option<StringMajorUnit>,
}
impl From<BrowserInformation> for HipayBrowserInfo {
fn from(browser_info: BrowserInformation) -> Self {
Self {
java_enabled: browser_info.java_enabled,
javascript_enabled: browser_info.java_script_enabled,
ipaddr: browser_info.ip_address,
http_accept: "*/*".to_string(),
http_user_agent: browser_info.user_agent,
language: browser_info.language,
color_depth: browser_info.color_depth,
screen_height: browser_info.screen_height,
screen_width: browser_info.screen_width,
timezone: browser_info.time_zone,
}
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct HiPayTokenRequest {
pub card_number: cards::CardNumber,
pub card_expiry_month: Secret<String>,
pub card_expiry_year: Secret<String>,
pub card_holder: Secret<String>,
pub cvc: Secret<String>,
}
impl TryFrom<&HipayRouterData<&PaymentsAuthorizeRouterData>> for HipayPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &HipayRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
let (domestic_card_network, domestic_network) = item
.router_data
.connector_response
.clone()
.and_then(|response| match response.additional_payment_method_data {
Some(AdditionalPaymentMethodConnectorResponse::Card {
card_network,
domestic_network,
..
}) => Some((card_network, domestic_network)),
_ => None,
})
.unwrap_or_default();
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => Ok(Self {
operation: if item.router_data.request.is_auto_capture()? {
Operation::Sale
} else {
Operation::Authorization
},
authentication_indicator: if item.router_data.is_three_ds() { 2 } else { 0 },
cardtoken: match item.router_data.get_payment_method_token()? {
PaymentMethodToken::Token(token) => token,
PaymentMethodToken::ApplePayDecrypt(_) => {
return Err(unimplemented_payment_method!("Apple Pay", "Hipay").into());
}
PaymentMethodToken::PazeDecrypt(_) => {
return Err(unimplemented_payment_method!("Paze", "Hipay").into());
}
PaymentMethodToken::GooglePayDecrypt(_) => {
return Err(unimplemented_payment_method!("Google Pay", "Hipay").into());
}
},
orderid: item.router_data.connector_request_reference_id.clone(),
currency: item.router_data.request.currency,
payment_product: match (domestic_network, domestic_card_network.as_deref()) {
(Some(domestic), _) => domestic,
(None, Some("VISA")) => "visa".to_string(),
(None, Some("MASTERCARD")) => "mastercard".to_string(),
(None, Some("MAESTRO")) => "maestro".to_string(),
(None, Some("AMERICAN EXPRESS")) => "american-express".to_string(),
(None, Some("CB")) => "cb".to_string(),
(None, Some("BCMC")) => "bcmc".to_string(),
(None, _) => match req_card.card_network {
Some(CardNetwork::Visa) => "visa".to_string(),
Some(CardNetwork::Mastercard) => "mastercard".to_string(),
Some(CardNetwork::AmericanExpress) => "american-express".to_string(),
Some(CardNetwork::JCB) => "jcb".to_string(),
Some(CardNetwork::DinersClub) => "diners".to_string(),
Some(CardNetwork::Discover) => "discover".to_string(),
Some(CardNetwork::CartesBancaires) => "cb".to_string(),
Some(CardNetwork::UnionPay) => "unionpay".to_string(),
Some(CardNetwork::Interac) => "interac".to_string(),
Some(CardNetwork::RuPay) => "rupay".to_string(),
Some(CardNetwork::Maestro) => "maestro".to_string(),
Some(CardNetwork::Star)
| Some(CardNetwork::Accel)
| Some(CardNetwork::Pulse)
| Some(CardNetwork::Nyce)
| None => "".to_string(),
},
},
amount: item.amount.clone(),
description: item
.router_data
.get_description()
.map(|s| s.to_string())
.unwrap_or("Short Description".to_string()),
decline_url: item.router_data.request.router_return_url.clone(),
pending_url: item.router_data.request.router_return_url.clone(),
cancel_url: item.router_data.request.router_return_url.clone(),
accept_url: item.router_data.request.router_return_url.clone(),
notify_url: item.router_data.request.router_return_url.clone(),
three_ds_data: if item.router_data.is_three_ds() {
let billing_address = item.router_data.get_billing_address()?;
Some(ThreeDSPaymentData {
firstname: billing_address.get_optional_first_name(),
lastname: billing_address.get_optional_last_name(),
email: Some(
item.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?,
),
city: billing_address.get_optional_city(),
streetaddress: billing_address.get_optional_line1(),
zipcode: billing_address.get_optional_zip(),
state: billing_address.get_optional_state(),
country: billing_address.get_optional_country(),
browser_info: Some(HipayBrowserInfo::from(
item.router_data.request.get_browser_info()?,
)),
})
} else {
None
},
}),
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
impl TryFrom<&TokenizationRouterData> for HiPayTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(card_data) => Ok(Self {
card_number: card_data.card_number.clone(),
card_expiry_month: card_data.card_exp_month.clone(),
card_expiry_year: card_data.get_expiry_year_4_digit(),
card_holder: item.get_billing_full_name()?,
cvc: card_data.card_cvc,
}),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Hipay"),
)
.into()),
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct HipayTokenResponse {
token: Secret<String>,
brand: String,
domestic_network: Option<String>,
}
impl From<&HipayTokenResponse> for AdditionalPaymentMethodConnectorResponse {
fn from(hipay_token_response: &HipayTokenResponse) -> Self {
Self::Card {
authentication_data: None,
payment_checks: None,
card_network: Some(hipay_token_response.brand.clone()),
domestic_network: hipay_token_response.domestic_network.clone(),
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct HipayErrorResponse {
pub code: u8,
pub message: String,
pub description: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, HipayTokenResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, HipayTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.token.clone().expose(),
}),
connector_response: Some(ConnectorResponseData::with_additional_payment_method_data(
AdditionalPaymentMethodConnectorResponse::from(&item.response),
)),
..item.data
})
}
}
pub struct HipayAuthType {
pub(super) api_key: Secret<String>,
pub(super) key1: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for HipayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.clone(),
key1: key1.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HipayPaymentsResponse {
status: HipayPaymentStatus,
message: String,
order: PaymentOrder,
forward_url: String,
transaction_reference: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentOrder {
id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HipayMaintenanceResponse<S> {
status: S,
message: String,
transaction_reference: String,
}
impl<F>
TryFrom<
ResponseRouterData<F, HipayPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
HipayPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = common_enums::AttemptStatus::from(item.response.status);
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: item.response.message.clone(),
reason: Some(item.response.message.clone()),
attempt_status: None,
connector_transaction_id: Some(item.response.transaction_reference),
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_reference,
),
redirection_data: match item.data.is_three_ds() {
true => Box::new(Some(RedirectForm::Form {
endpoint: item.response.forward_url,
method: Method::Get,
form_fields: HashMap::new(),
})),
false => Box::new(None),
},
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl<F> TryFrom<&HipayRouterData<&RefundsRouterData<F>>> for HipayMaintenanceRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &HipayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: Some(item.amount.to_owned()),
operation: Operation::Refund,
currency: Some(item.router_data.request.currency),
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for HipayMaintenanceRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Ok(Self {
operation: Operation::Cancel,
currency: item.request.currency,
amount: None,
})
}
}
impl TryFrom<&HipayRouterData<&PaymentsCaptureRouterData>> for HipayMaintenanceRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &HipayRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
Ok(Self {
amount: Some(item.amount.to_owned()),
operation: Operation::Capture,
currency: Some(item.router_data.request.currency),
})
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum RefundStatus {
#[serde(rename = "124")]
RefundRequested,
#[serde(rename = "125")]
Refunded,
#[serde(rename = "126")]
PartiallyRefunded,
#[serde(rename = "165")]
RefundRefused,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::RefundRequested => Self::Pending,
RefundStatus::Refunded | RefundStatus::PartiallyRefunded => Self::Success,
RefundStatus::RefundRefused => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum HipayPaymentStatus {
#[serde(rename = "109")]
AuthenticationFailed,
#[serde(rename = "110")]
Blocked,
#[serde(rename = "111")]
Denied,
#[serde(rename = "112")]
AuthorizedAndPending,
#[serde(rename = "113")]
Refused,
#[serde(rename = "114")]
Expired,
#[serde(rename = "115")]
Cancelled,
#[serde(rename = "116")]
Authorized,
#[serde(rename = "117")]
CaptureRequested,
#[serde(rename = "118")]
Captured,
#[serde(rename = "119")]
PartiallyCaptured,
#[serde(rename = "129")]
ChargedBack,
#[serde(rename = "173")]
CaptureRefused,
#[serde(rename = "174")]
AwaitingTerminal,
#[serde(rename = "175")]
AuthorizationCancellationRequested,
#[serde(rename = "177")]
ChallengeRequested,
#[serde(rename = "178")]
SoftDeclined,
#[serde(rename = "200")]
PendingPayment,
#[serde(rename = "101")]
Created,
#[serde(rename = "105")]
UnableToAuthenticate,
#[serde(rename = "106")]
CardholderAuthenticated,
#[serde(rename = "107")]
AuthenticationAttempted,
#[serde(rename = "108")]
CouldNotAuthenticate,
#[serde(rename = "120")]
Collected,
#[serde(rename = "121")]
PartiallyCollected,
#[serde(rename = "122")]
Settled,
#[serde(rename = "123")]
PartiallySettled,
#[serde(rename = "140")]
AuthenticationRequested,
#[serde(rename = "141")]
Authenticated,
#[serde(rename = "151")]
AcquirerNotFound,
#[serde(rename = "161")]
RiskAccepted,
#[serde(rename = "163")]
AuthorizationRefused,
}
impl From<HipayPaymentStatus> for common_enums::AttemptStatus {
fn from(status: HipayPaymentStatus) -> Self {
match status {
HipayPaymentStatus::AuthenticationFailed => Self::AuthenticationFailed,
HipayPaymentStatus::Blocked
| HipayPaymentStatus::Refused
| HipayPaymentStatus::Expired
| HipayPaymentStatus::Denied => Self::Failure,
HipayPaymentStatus::AuthorizedAndPending => Self::Pending,
HipayPaymentStatus::Cancelled => Self::Voided,
HipayPaymentStatus::Authorized => Self::Authorized,
HipayPaymentStatus::CaptureRequested => Self::CaptureInitiated,
HipayPaymentStatus::Captured => Self::Charged,
HipayPaymentStatus::PartiallyCaptured => Self::PartialCharged,
HipayPaymentStatus::CaptureRefused => Self::CaptureFailed,
HipayPaymentStatus::AwaitingTerminal => Self::Pending,
HipayPaymentStatus::AuthorizationCancellationRequested => Self::VoidInitiated,
HipayPaymentStatus::ChallengeRequested => Self::AuthenticationPending,
HipayPaymentStatus::SoftDeclined => Self::Failure,
HipayPaymentStatus::PendingPayment => Self::Pending,
HipayPaymentStatus::ChargedBack => Self::Failure,
HipayPaymentStatus::Created => Self::Started,
HipayPaymentStatus::UnableToAuthenticate | HipayPaymentStatus::CouldNotAuthenticate => {
Self::AuthenticationFailed
}
HipayPaymentStatus::CardholderAuthenticated => Self::Pending,
HipayPaymentStatus::AuthenticationAttempted => Self::AuthenticationPending,
HipayPaymentStatus::Collected
| HipayPaymentStatus::PartiallySettled
| HipayPaymentStatus::PartiallyCollected
| HipayPaymentStatus::Settled => Self::Charged,
HipayPaymentStatus::AuthenticationRequested => Self::AuthenticationPending,
HipayPaymentStatus::Authenticated => Self::AuthenticationSuccessful,
HipayPaymentStatus::AcquirerNotFound => Self::Failure,
HipayPaymentStatus::RiskAccepted => Self::Pending,
HipayPaymentStatus::AuthorizationRefused => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: u64,
status: u16,
}
impl TryFrom<RefundsResponseRouterData<Execute, HipayMaintenanceResponse<RefundStatus>>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, HipayMaintenanceResponse<RefundStatus>>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_reference,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: match item.response.status {
25 | 26 => enums::RefundStatus::Success,
65 => enums::RefundStatus::Failure,
24 => enums::RefundStatus::Pending,
_ => enums::RefundStatus::Pending,
},
}),
..item.data
})
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<HipayMaintenanceResponse<HipayPaymentStatus>>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<HipayMaintenanceResponse<HipayPaymentStatus>>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_reference.clone().to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<PaymentsCancelResponseRouterData<HipayMaintenanceResponse<HipayPaymentStatus>>>
for PaymentsCancelRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<HipayMaintenanceResponse<HipayPaymentStatus>>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_reference.clone().to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Reason {
reason: Option<String>,
code: Option<u64>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum HipaySyncResponse {
Response { status: i32, reason: Reason },
Error { message: String, code: u32 },
}
fn get_sync_status(state: i32) -> enums::AttemptStatus {
match state {
9 => enums::AttemptStatus::AuthenticationFailed,
10 => enums::AttemptStatus::Failure,
11 => enums::AttemptStatus::Failure,
12 => enums::AttemptStatus::Pending,
13 => enums::AttemptStatus::Failure,
14 => enums::AttemptStatus::Failure,
15 => enums::AttemptStatus::Voided,
16 => enums::AttemptStatus::Authorized,
17 => enums::AttemptStatus::CaptureInitiated,
18 => enums::AttemptStatus::Charged,
19 => enums::AttemptStatus::PartialCharged,
29 => enums::AttemptStatus::Failure,
73 => enums::AttemptStatus::CaptureFailed,
74 => enums::AttemptStatus::Pending,
75 => enums::AttemptStatus::VoidInitiated,
77 => enums::AttemptStatus::AuthenticationPending,
78 => enums::AttemptStatus::Failure,
200 => enums::AttemptStatus::Pending,
1 => enums::AttemptStatus::Started,
5 => enums::AttemptStatus::AuthenticationFailed,
6 => enums::AttemptStatus::Pending,
7 => enums::AttemptStatus::AuthenticationPending,
8 => enums::AttemptStatus::AuthenticationFailed,
20 => enums::AttemptStatus::Charged,
21 => enums::AttemptStatus::Charged,
22 => enums::AttemptStatus::Charged,
23 => enums::AttemptStatus::Charged,
40 => enums::AttemptStatus::AuthenticationPending,
41 => enums::AttemptStatus::AuthenticationSuccessful,
51 => enums::AttemptStatus::Failure,
61 => enums::AttemptStatus::Pending,
63 => enums::AttemptStatus::Failure,
_ => enums::AttemptStatus::Failure,
}
}
impl TryFrom<PaymentsSyncResponseRouterData<HipaySyncResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<HipaySyncResponse>,
) -> Result<Self, Self::Error> {
match item.response {
HipaySyncResponse::Error { message, code } => {
let response = Err(ErrorResponse {
code: code.to_string(),
message: message.clone(),
reason: Some(message.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
status: enums::AttemptStatus::Failure,
response,
..item.data
})
}
HipaySyncResponse::Response { status, reason } => {
let status = get_sync_status(status);
let response = if status == enums::AttemptStatus::Failure {
let error_code = reason
.code
.map_or(NO_ERROR_CODE.to_string(), |c| c.to_string());
let error_message = reason
.reason
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_owned());
Err(ErrorResponse {
code: error_code,
message: error_message.clone(),
reason: Some(error_message),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6304
}
|
large_file_-4978016086815277277
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
</path>
<file>
use std::collections::HashMap;
use common_enums::enums;
pub use common_utils::request::Method;
use common_utils::{
errors::CustomResult, ext_traits::ValueExt, id_type, pii::Email, types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::{PaymentsAuthorizeData, ResponseId},
router_response_types::{PaymentsResponseData, RedirectForm},
types::PaymentsAuthorizeRouterData,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::ResponseRouterData,
utils::{self, PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodePaymentsRequest {
amount: FloatMajorUnit,
transaction_id: String,
user_id: Secret<id_type::CustomerId>,
currency: enums::Currency,
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
user_alias: Secret<id_type::CustomerId>,
requested_url: String,
cancel_url: String,
email: Option<Email>,
mid: Secret<String>,
}
fn get_mid(
connector_auth_type: &ConnectorAuthType,
payment_method_type: Option<enums::PaymentMethodType>,
currency: enums::Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
match CashtocodeAuth::try_from((connector_auth_type, ¤cy)) {
Ok(cashtocode_auth) => match payment_method_type {
Some(enums::PaymentMethodType::ClassicReward) => Ok(cashtocode_auth
.merchant_id_classic
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?),
Some(enums::PaymentMethodType::Evoucher) => Ok(cashtocode_auth
.merchant_id_evoucher
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?),
_ => Err(errors::ConnectorError::FailedToObtainAuthType),
},
Err(_) => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
impl TryFrom<(&PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, amount): (&PaymentsAuthorizeRouterData, FloatMajorUnit),
) -> Result<Self, Self::Error> {
let customer_id = item.get_customer_id()?;
let url = item.request.get_router_return_url()?;
let mid = get_mid(
&item.connector_auth_type,
item.request.payment_method_type,
item.request.currency,
)?;
match item.payment_method {
enums::PaymentMethod::Reward => Ok(Self {
amount,
transaction_id: item.attempt_id.clone(),
currency: item.request.currency,
user_id: Secret::new(customer_id.to_owned()),
first_name: None,
last_name: None,
user_alias: Secret::new(customer_id),
requested_url: url.to_owned(),
cancel_url: url,
email: item.request.email.clone(),
mid,
}),
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
#[derive(Default, Debug, Deserialize)]
pub struct CashtocodeAuthType {
pub auths: HashMap<enums::Currency, CashtocodeAuth>,
}
#[derive(Default, Debug, Deserialize)]
pub struct CashtocodeAuth {
pub password_classic: Option<Secret<String>>,
pub password_evoucher: Option<Secret<String>>,
pub username_classic: Option<Secret<String>>,
pub username_evoucher: Option<Secret<String>>,
pub merchant_id_classic: Option<Secret<String>>,
pub merchant_id_evoucher: Option<Secret<String>>,
}
impl TryFrom<&ConnectorAuthType> for CashtocodeAuthType {
type Error = error_stack::Report<errors::ConnectorError>; // Assuming ErrorStack is the appropriate error type
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
let transformed_auths = auth_key_map
.iter()
.map(|(currency, identity_auth_key)| {
let cashtocode_auth = identity_auth_key
.to_owned()
.parse_value::<CashtocodeAuth>("CashtocodeAuth")
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "auth_key_map",
})?;
Ok((currency.to_owned(), cashtocode_auth))
})
.collect::<Result<_, Self::Error>>()?;
Ok(Self {
auths: transformed_auths,
})
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<(&ConnectorAuthType, &enums::Currency)> for CashtocodeAuth {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: (&ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> {
let (auth_type, currency) = value;
if let ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type {
if let Some(identity_auth_key) = auth_key_map.get(currency) {
let cashtocode_auth: Self = identity_auth_key
.to_owned()
.parse_value("CashtocodeAuth")
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(cashtocode_auth)
} else {
Err(errors::ConnectorError::CurrencyNotSupported {
message: currency.to_string(),
connector: "CashToCode",
}
.into())
}
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CashtocodePaymentStatus {
Succeeded,
#[default]
Processing,
}
impl From<CashtocodePaymentStatus> for enums::AttemptStatus {
fn from(item: CashtocodePaymentStatus) -> Self {
match item {
CashtocodePaymentStatus::Succeeded => Self::Charged,
CashtocodePaymentStatus::Processing => Self::AuthenticationPending,
}
}
}
#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct CashtocodeErrors {
pub message: String,
pub path: String,
#[serde(rename = "type")]
pub event_type: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CashtocodePaymentsResponse {
CashtoCodeError(CashtocodeErrorResponse),
CashtoCodeData(CashtocodePaymentsResponseData),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodePaymentsResponseData {
pub pay_url: url::Url,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodePaymentsSyncResponse {
pub transaction_id: String,
pub amount: FloatMajorUnit,
}
fn get_redirect_form_data(
payment_method_type: enums::PaymentMethodType,
response_data: CashtocodePaymentsResponseData,
) -> CustomResult<RedirectForm, errors::ConnectorError> {
match payment_method_type {
enums::PaymentMethodType::ClassicReward => Ok(RedirectForm::Form {
//redirect form is manually constructed because the connector for this pm type expects query params in the url
endpoint: response_data.pay_url.to_string(),
method: Method::Post,
form_fields: Default::default(),
}),
enums::PaymentMethodType::Evoucher => Ok(RedirectForm::from((
//here the pay url gets parsed, and query params are sent as formfields as the connector expects
response_data.pay_url,
Method::Get,
))),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("CashToCode"),
))?,
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
CashtocodePaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
CashtocodePaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let (status, response) = match item.response {
CashtocodePaymentsResponse::CashtoCodeError(error_data) => (
enums::AttemptStatus::Failure,
Err(ErrorResponse {
code: error_data.error.to_string(),
status_code: item.http_code,
message: error_data.error_description.clone(),
reason: Some(error_data.error_description),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
),
CashtocodePaymentsResponse::CashtoCodeData(response_data) => {
let payment_method_type = item
.data
.request
.payment_method_type
.ok_or(errors::ConnectorError::MissingPaymentMethodType)?;
let redirection_data = get_redirect_form_data(payment_method_type, response_data)?;
(
enums::AttemptStatus::AuthenticationPending,
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.data.attempt_id.clone(),
),
redirection_data: Box::new(Some(redirection_data)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
)
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::Charged, // Charged status is hardcoded because cashtocode do not support Psync, and we only receive webhooks when payment is succeeded, this tryFrom is used for CallConnectorAction.
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.data.attempt_id.clone(), //in response they only send PayUrl, so we use attempt_id as connector_transaction_id
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CashtocodeErrorResponse {
pub error: serde_json::Value,
pub error_description: String,
pub errors: Option<Vec<CashtocodeErrors>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodeIncomingWebhook {
pub amount: FloatMajorUnit,
pub currency: String,
pub foreign_transaction_id: String,
#[serde(rename = "type")]
pub event_type: String,
pub transaction_id: String,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2563
}
|
large_file_-4603720426666225406
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
</path>
<file>
use common_enums::enums;
use common_utils::{
pii,
types::{MinorUnit, StringMajorUnit},
};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm},
types,
};
use hyperswitch_interfaces::{consts, errors};
use masking::Secret;
use reqwest::Url;
use serde::{Deserialize, Serialize};
use crate::{
types::ResponseRouterData,
utils::{self, CryptoData, ForeignTryFrom, PaymentsAuthorizeRequestData},
};
#[derive(Debug, Serialize)]
pub struct CryptopayRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for CryptopayRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct CryptopayPaymentsRequest {
price_amount: StringMajorUnit,
price_currency: enums::Currency,
pay_currency: String,
#[serde(skip_serializing_if = "Option::is_none")]
network: Option<String>,
success_redirect_url: Option<String>,
unsuccess_redirect_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
metadata: Option<pii::SecretSerdeValue>,
custom_id: String,
}
impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>>
for CryptopayPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CryptopayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let cryptopay_request = match item.router_data.request.payment_method_data {
PaymentMethodData::Crypto(ref cryptodata) => {
let pay_currency = cryptodata.get_pay_currency()?;
Ok(Self {
price_amount: item.amount.clone(),
price_currency: item.router_data.request.currency,
pay_currency,
network: cryptodata.network.to_owned(),
success_redirect_url: item.router_data.request.router_return_url.clone(),
unsuccess_redirect_url: item.router_data.request.router_return_url.clone(),
//Cryptopay only accepts metadata as Object. If any other type, payment will fail with error.
metadata: item.router_data.request.get_metadata_as_object(),
custom_id: item.router_data.connector_request_reference_id.clone(),
})
}
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("CryptoPay"),
))
}
}?;
Ok(cryptopay_request)
}
}
// Auth Struct
pub struct CryptopayAuthType {
pub(super) api_key: Secret<String>,
pub(super) api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for CryptopayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
api_key: api_key.to_owned(),
api_secret: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CryptopayPaymentStatus {
New,
Completed,
Unresolved,
Refunded,
Cancelled,
}
impl From<CryptopayPaymentStatus> for enums::AttemptStatus {
fn from(item: CryptopayPaymentStatus) -> Self {
match item {
CryptopayPaymentStatus::New => Self::AuthenticationPending,
CryptopayPaymentStatus::Completed => Self::Charged,
CryptopayPaymentStatus::Cancelled => Self::Failure,
CryptopayPaymentStatus::Unresolved | CryptopayPaymentStatus::Refunded => {
Self::Unresolved
} //mapped refunded to Unresolved because refund api is not available, also merchant has done the action on the connector dashboard.
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CryptopayPaymentsResponse {
pub data: CryptopayPaymentResponseData,
}
impl<F, T>
ForeignTryFrom<(
ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>,
Option<MinorUnit>,
)> for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, amount_captured_in_minor_units): (
ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>,
Option<MinorUnit>,
),
) -> Result<Self, Self::Error> {
let status = enums::AttemptStatus::from(item.response.data.status.clone());
let response = if utils::is_payment_failure(status) {
let payment_response = &item.response.data;
Err(ErrorResponse {
code: payment_response
.name
.clone()
.unwrap_or(consts::NO_ERROR_CODE.to_string()),
message: payment_response
.status_context
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: payment_response.status_context.clone(),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(payment_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
let redirection_data = item
.response
.data
.hosted_page_url
.map(|x| RedirectForm::from((x, common_utils::request::Method::Get)));
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.data.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
.response
.data
.custom_id
.or(Some(item.response.data.id)),
incremental_authorization_allowed: None,
charges: None,
})
};
match (amount_captured_in_minor_units, status) {
(Some(minor_amount), enums::AttemptStatus::Charged) => {
let amount_captured = Some(minor_amount.get_amount_as_i64());
Ok(Self {
status,
response,
amount_captured,
minor_amount_captured: amount_captured_in_minor_units,
..item.data
})
}
_ => Ok(Self {
status,
response,
..item.data
}),
}
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct CryptopayErrorData {
pub code: String,
pub message: String,
pub reason: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct CryptopayErrorResponse {
pub error: CryptopayErrorData,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CryptopayPaymentResponseData {
pub id: String,
pub custom_id: Option<String>,
pub customer_id: Option<String>,
pub status: CryptopayPaymentStatus,
pub status_context: Option<String>,
pub address: Option<Secret<String>>,
pub network: Option<String>,
pub uri: Option<String>,
pub price_amount: Option<StringMajorUnit>,
pub price_currency: Option<String>,
pub pay_amount: Option<StringMajorUnit>,
pub pay_currency: Option<String>,
pub fee: Option<String>,
pub fee_currency: Option<String>,
pub paid_amount: Option<String>,
pub name: Option<String>,
pub description: Option<String>,
pub success_redirect_url: Option<String>,
pub unsuccess_redirect_url: Option<String>,
pub hosted_page_url: Option<Url>,
pub created_at: Option<String>,
pub expires_at: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CryptopayWebhookDetails {
#[serde(rename = "type")]
pub service_type: String,
pub event: WebhookEvent,
pub data: CryptopayPaymentResponseData,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WebhookEvent {
TransactionCreated,
TransactionConfirmed,
StatusChanged,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2039
}
|
large_file_-3120654605494489814
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs
</path>
<file>
use common_enums::{enums, Currency};
use common_utils::{pii::Email, request::Method, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankRedirectData, PaymentMethodData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::PaymentsAuthorizeRequestData,
};
pub struct PaystackRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for PaystackRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
}
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct PaystackEftProvider {
provider: String,
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct PaystackPaymentsRequest {
amount: MinorUnit,
currency: Currency,
email: Email,
eft: PaystackEftProvider,
}
impl TryFrom<&PaystackRouterData<&PaymentsAuthorizeRouterData>> for PaystackPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaystackRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankRedirect(BankRedirectData::Eft { provider }) => {
let email = item.router_data.request.get_email()?;
let eft = PaystackEftProvider { provider };
Ok(Self {
amount: item.amount,
currency: item.router_data.request.currency,
email,
eft,
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
pub struct PaystackAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PaystackAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PaystackEftRedirect {
reference: String,
status: String,
url: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PaystackPaymentsResponseData {
status: bool,
message: String,
data: PaystackEftRedirect,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum PaystackPaymentsResponse {
PaystackPaymentsData(PaystackPaymentsResponseData),
PaystackPaymentsError(PaystackErrorResponse),
}
impl<F, T> TryFrom<ResponseRouterData<F, PaystackPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaystackPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, response) = match item.response {
PaystackPaymentsResponse::PaystackPaymentsData(resp) => {
let redirection_url = Url::parse(resp.data.url.as_str())
.change_context(errors::ConnectorError::ParsingFailed)?;
let redirection_data = RedirectForm::from((redirection_url, Method::Get));
(
common_enums::AttemptStatus::AuthenticationPending,
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
resp.data.reference.clone(),
),
redirection_data: Box::new(Some(redirection_data)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
)
}
PaystackPaymentsResponse::PaystackPaymentsError(err) => {
let err_msg = get_error_message(err.clone());
(
common_enums::AttemptStatus::Failure,
Err(ErrorResponse {
code: err.code,
message: err_msg.clone(),
reason: Some(err_msg.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
)
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum PaystackPSyncStatus {
Abandoned,
Failed,
Ongoing,
Pending,
Processing,
Queued,
Reversed,
Success,
}
impl From<PaystackPSyncStatus> for common_enums::AttemptStatus {
fn from(item: PaystackPSyncStatus) -> Self {
match item {
PaystackPSyncStatus::Success => Self::Charged,
PaystackPSyncStatus::Abandoned => Self::AuthenticationPending,
PaystackPSyncStatus::Ongoing
| PaystackPSyncStatus::Pending
| PaystackPSyncStatus::Processing
| PaystackPSyncStatus::Queued => Self::Pending,
PaystackPSyncStatus::Failed => Self::Failure,
PaystackPSyncStatus::Reversed => Self::Voided,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PaystackPSyncData {
status: PaystackPSyncStatus,
reference: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PaystackPSyncResponseData {
status: bool,
message: String,
data: PaystackPSyncData,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum PaystackPSyncResponse {
PaystackPSyncData(PaystackPSyncResponseData),
PaystackPSyncWebhook(PaystackPaymentWebhookData),
PaystackPSyncError(PaystackErrorResponse),
}
impl<F, T> TryFrom<ResponseRouterData<F, PaystackPSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaystackPSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
PaystackPSyncResponse::PaystackPSyncData(resp) => Ok(Self {
status: common_enums::AttemptStatus::from(resp.data.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(resp.data.reference.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
PaystackPSyncResponse::PaystackPSyncWebhook(resp) => Ok(Self {
status: common_enums::AttemptStatus::from(resp.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(resp.reference.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
PaystackPSyncResponse::PaystackPSyncError(err) => {
let err_msg = get_error_message(err.clone());
Ok(Self {
response: Err(ErrorResponse {
code: err.code,
message: err_msg.clone(),
reason: Some(err_msg.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct PaystackRefundRequest {
pub transaction: String,
pub amount: MinorUnit,
}
impl<F> TryFrom<&PaystackRouterData<&RefundsRouterData<F>>> for PaystackRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaystackRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
transaction: item.router_data.request.connector_transaction_id.clone(),
amount: item.amount.to_owned(),
})
}
}
#[derive(Debug, Serialize, Default, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum PaystackRefundStatus {
Processed,
Failed,
#[default]
Processing,
Pending,
}
impl From<PaystackRefundStatus> for enums::RefundStatus {
fn from(item: PaystackRefundStatus) -> Self {
match item {
PaystackRefundStatus::Processed => Self::Success,
PaystackRefundStatus::Failed => Self::Failure,
PaystackRefundStatus::Processing | PaystackRefundStatus::Pending => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PaystackRefundsData {
status: PaystackRefundStatus,
id: i64,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PaystackRefundsResponseData {
status: bool,
message: String,
data: PaystackRefundsData,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum PaystackRefundsResponse {
PaystackRefundsData(PaystackRefundsResponseData),
PaystackRSyncWebhook(PaystackRefundWebhookData),
PaystackRefundsError(PaystackErrorResponse),
}
impl TryFrom<RefundsResponseRouterData<Execute, PaystackRefundsResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, PaystackRefundsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
PaystackRefundsResponse::PaystackRefundsData(resp) => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: resp.data.id.to_string(),
refund_status: enums::RefundStatus::from(resp.data.status),
}),
..item.data
}),
PaystackRefundsResponse::PaystackRSyncWebhook(resp) => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: resp.id,
refund_status: enums::RefundStatus::from(resp.status),
}),
..item.data
}),
PaystackRefundsResponse::PaystackRefundsError(err) => {
let err_msg = get_error_message(err.clone());
Ok(Self {
response: Err(ErrorResponse {
code: err.code,
message: err_msg.clone(),
reason: Some(err_msg.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
}
impl TryFrom<RefundsResponseRouterData<RSync, PaystackRefundsResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, PaystackRefundsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
PaystackRefundsResponse::PaystackRefundsData(resp) => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: resp.data.id.to_string(),
refund_status: enums::RefundStatus::from(resp.data.status),
}),
..item.data
}),
PaystackRefundsResponse::PaystackRSyncWebhook(resp) => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: resp.id,
refund_status: enums::RefundStatus::from(resp.status),
}),
..item.data
}),
PaystackRefundsResponse::PaystackRefundsError(err) => {
let err_msg = get_error_message(err.clone());
Ok(Self {
response: Err(ErrorResponse {
code: err.code,
message: err_msg.clone(),
reason: Some(err_msg.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct PaystackErrorResponse {
pub status: bool,
pub message: String,
pub data: Option<serde_json::Value>,
pub meta: serde_json::Value,
pub code: String,
}
pub fn get_error_message(response: PaystackErrorResponse) -> String {
if let Some(serde_json::Value::Object(err_map)) = response.data {
err_map.get("message").map(|msg| msg.clone().to_string())
} else {
None
}
.unwrap_or(response.message)
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct PaystackPaymentWebhookData {
pub status: PaystackPSyncStatus,
pub reference: String,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct PaystackRefundWebhookData {
pub status: PaystackRefundStatus,
pub id: String,
pub transaction_reference: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(untagged)]
pub enum PaystackWebhookEventData {
Payment(PaystackPaymentWebhookData),
Refund(PaystackRefundWebhookData),
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct PaystackWebhookData {
pub event: String,
pub data: PaystackWebhookEventData,
}
impl From<PaystackWebhookEventData> for api_models::webhooks::IncomingWebhookEvent {
fn from(item: PaystackWebhookEventData) -> Self {
match item {
PaystackWebhookEventData::Payment(payment_data) => match payment_data.status {
PaystackPSyncStatus::Success => Self::PaymentIntentSuccess,
PaystackPSyncStatus::Failed => Self::PaymentIntentFailure,
PaystackPSyncStatus::Abandoned
| PaystackPSyncStatus::Ongoing
| PaystackPSyncStatus::Pending
| PaystackPSyncStatus::Processing
| PaystackPSyncStatus::Queued => Self::PaymentIntentProcessing,
PaystackPSyncStatus::Reversed => Self::EventNotSupported,
},
PaystackWebhookEventData::Refund(refund_data) => match refund_data.status {
PaystackRefundStatus::Processed => Self::RefundSuccess,
PaystackRefundStatus::Failed => Self::RefundFailure,
PaystackRefundStatus::Processing | PaystackRefundStatus::Pending => {
Self::EventNotSupported
}
},
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3576
}
|
large_file_1186552953431055061
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/calida/transformers.rs
</path>
<file>
use std::collections::HashMap;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::ByteSliceExt,
pii::{Email, IpAddress},
request::Method,
types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self as connector_utils, PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
pub struct CalidaRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for CalidaRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct CalidaMetadataObject {
pub shop_name: String,
}
impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for CalidaMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
meta_data: &Option<common_utils::pii::SecretSerdeValue>,
) -> Result<Self, Self::Error> {
let metadata = connector_utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CalidaPaymentsRequest {
pub amount: FloatMajorUnit,
pub currency: enums::Currency,
pub payment_provider: String,
pub shop_name: String,
pub reference: String,
pub ip_address: Option<Secret<String, IpAddress>>,
pub first_name: Secret<String>,
pub last_name: Secret<String>,
pub billing_address_country_code_iso: enums::CountryAlpha2,
pub billing_address_city: String,
pub billing_address_line1: Secret<String>,
pub billing_address_postal_code: Secret<String>,
pub webhook_url: String,
pub success_url: String,
pub failure_url: String,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct CalidaCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&CalidaRouterData<&PaymentsAuthorizeRouterData>> for CalidaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CalidaRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual)
| Some(enums::CaptureMethod::ManualMultiple)
| Some(enums::CaptureMethod::Scheduled)
| Some(enums::CaptureMethod::SequentialAutomatic) => {
Err(errors::ConnectorError::FlowNotSupported {
flow: format!("{:?}", item.router_data.request.capture_method),
connector: "Calida".to_string(),
}
.into())
}
Some(enums::CaptureMethod::Automatic) | None => {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Wallet(WalletData::BluecodeRedirect {}) => {
let calida_mca_metadata =
CalidaMetadataObject::try_from(&item.router_data.connector_meta_data)?;
Self::try_from((item, &calida_mca_metadata))
}
_ => Err(
errors::ConnectorError::NotImplemented("Payment method".to_string()).into(),
),
}
}
}
}
}
impl
TryFrom<(
&CalidaRouterData<&PaymentsAuthorizeRouterData>,
&CalidaMetadataObject,
)> for CalidaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (
&CalidaRouterData<&PaymentsAuthorizeRouterData>,
&CalidaMetadataObject,
),
) -> Result<Self, Self::Error> {
let item = value.0;
Ok(Self {
amount: item.amount,
currency: item.router_data.request.currency,
payment_provider: "bluecode_payment".to_string(),
shop_name: value.1.shop_name.clone(),
reference: item.router_data.payment_id.clone(),
ip_address: item.router_data.request.get_ip_address_as_optional(),
first_name: item.router_data.get_billing_first_name()?,
last_name: item.router_data.get_billing_last_name()?,
billing_address_country_code_iso: item.router_data.get_billing_country()?,
billing_address_city: item.router_data.get_billing_city()?,
billing_address_line1: item.router_data.get_billing_line1()?,
billing_address_postal_code: item.router_data.get_billing_zip()?,
webhook_url: item.router_data.request.get_webhook_url()?,
success_url: item.router_data.request.get_router_return_url()?,
failure_url: item.router_data.request.get_router_return_url()?,
})
}
}
pub struct CalidaAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for CalidaAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl From<CalidaPaymentStatus> for common_enums::AttemptStatus {
fn from(item: CalidaPaymentStatus) -> Self {
match item {
CalidaPaymentStatus::ManualProcessing => Self::Pending,
CalidaPaymentStatus::Pending | CalidaPaymentStatus::PaymentInitiated => {
Self::AuthenticationPending
}
CalidaPaymentStatus::Failed => Self::Failure,
CalidaPaymentStatus::Completed => Self::Charged,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CalidaPaymentsResponse {
pub id: i64,
pub order_id: String,
pub amount: FloatMajorUnit,
pub currency: enums::Currency,
pub charged_amount: FloatMajorUnit,
pub charged_currency: enums::Currency,
pub status: CalidaPaymentStatus,
pub payment_link: url::Url,
pub etoken: Secret<String>,
pub payment_request_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CalidaSyncResponse {
pub id: Option<i64>,
pub order_id: String,
pub user_id: Option<i64>,
pub customer_id: Option<String>,
pub customer_email: Option<Email>,
pub customer_phone: Option<String>,
pub status: CalidaPaymentStatus,
pub payment_provider: Option<String>,
pub payment_connector: Option<String>,
pub payment_method: Option<String>,
pub payment_method_type: Option<String>,
pub shop_name: Option<String>,
pub sender_name: Option<String>,
pub sender_email: Option<String>,
pub description: Option<String>,
pub amount: FloatMajorUnit,
pub currency: enums::Currency,
pub charged_amount: Option<FloatMajorUnit>,
pub charged_amount_currency: Option<String>,
pub charged_fx_amount: Option<FloatMajorUnit>,
pub charged_fx_amount_currency: Option<enums::Currency>,
pub is_underpaid: Option<bool>,
pub billing_amount: Option<FloatMajorUnit>,
pub billing_currency: Option<String>,
pub language: Option<String>,
pub ip_address: Option<Secret<String, IpAddress>>,
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub billing_address_line1: Option<Secret<String>>,
pub billing_address_city: Option<Secret<String>>,
pub billing_address_postal_code: Option<Secret<String>>,
pub billing_address_country: Option<String>,
pub billing_address_country_code_iso: Option<enums::CountryAlpha2>,
pub shipping_address_country_code_iso: Option<enums::CountryAlpha2>,
pub success_url: Option<String>,
pub failure_url: Option<String>,
pub source: Option<String>,
pub bonus_code: Option<String>,
pub dob: Option<String>,
pub fees_amount: Option<f64>,
pub fx_margin_amount: Option<f64>,
pub fx_margin_percent: Option<f64>,
pub fees_percent: Option<f64>,
pub reseller_id: Option<String>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CalidaPaymentStatus {
Pending,
PaymentInitiated,
ManualProcessing,
Failed,
Completed,
}
impl<F, T> TryFrom<ResponseRouterData<F, CalidaPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CalidaPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let url = item.response.payment_link.clone();
let redirection_data = Some(RedirectForm::from((url, Method::Get)));
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.payment_request_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, CalidaSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CalidaSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: item.data.response,
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct CalidaRefundRequest {
pub amount: FloatMajorUnit,
}
impl<F> TryFrom<&CalidaRouterData<&RefundsRouterData<F>>> for CalidaRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &CalidaRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct CalidaErrorResponse {
pub message: String,
pub context_data: HashMap<String, Value>,
}
pub(crate) fn get_calida_webhook_event(
status: CalidaPaymentStatus,
) -> api_models::webhooks::IncomingWebhookEvent {
match status {
CalidaPaymentStatus::Completed => {
api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess
}
CalidaPaymentStatus::PaymentInitiated
| CalidaPaymentStatus::ManualProcessing
| CalidaPaymentStatus::Pending => {
api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing
}
CalidaPaymentStatus::Failed => {
api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure
}
}
}
pub(crate) fn get_webhook_object_from_body(
body: &[u8],
) -> CustomResult<CalidaSyncResponse, common_utils::errors::ParsingError> {
let webhook: CalidaSyncResponse = body.parse_struct("CalidaIncomingWebhook")?;
Ok(webhook)
}
pub fn sort_and_minify_json(value: &Value) -> Result<String, errors::ConnectorError> {
fn sort_value(val: &Value) -> Value {
match val {
Value::Object(map) => {
let mut entries: Vec<_> = map.iter().collect();
entries.sort_by_key(|(k, _)| k.to_owned());
let sorted_map: Map<String, Value> = entries
.into_iter()
.map(|(k, v)| (k.clone(), sort_value(v)))
.collect();
Value::Object(sorted_map)
}
Value::Array(arr) => Value::Array(arr.iter().map(sort_value).collect()),
_ => val.clone(),
}
}
let sorted_value = sort_value(value);
serde_json::to_string(&sorted_value)
.map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed)
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/calida/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3317
}
|
large_file_-7133240845391684219
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs
</path>
<file>
use std::collections::HashMap;
use api_models::admin::{AdditionalMerchantData, MerchantAccountData, MerchantRecipientData};
use common_enums::enums;
use common_utils::{id_type::MerchantId, request::Method, types::StringMajorUnit};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self},
};
//TODO: Fill the struct with respective fields
pub struct TokenioRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for TokenioRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenioPaymentsRequest {
pub initiation: PaymentInitiation,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInitiation {
pub ref_id: String,
pub remittance_information_primary: MerchantId,
pub amount: Amount,
pub local_instrument: LocalInstrument,
pub creditor: Creditor,
pub callback_url: Option<String>,
pub flow_type: FlowType,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
pub value: StringMajorUnit,
pub currency: enums::Currency,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LocalInstrument {
Sepa,
SepaInstant,
FasterPayments,
Elixir,
Bankgiro,
Plusgiro,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum Creditor {
FasterPayments {
#[serde(rename = "sortCode")]
sort_code: Secret<String>,
#[serde(rename = "accountNumber")]
account_number: Secret<String>,
name: Secret<String>,
},
Sepa {
iban: Secret<String>,
name: Secret<String>,
},
SepaInstant {
iban: Secret<String>,
name: Secret<String>,
},
ElixirIban {
iban: Secret<String>,
name: Secret<String>,
},
ElixirAccount {
#[serde(rename = "accountNumber")]
account_number: Secret<String>,
name: Secret<String>,
},
Bankgiro {
#[serde(rename = "bankgiroNumber")]
bankgiro_number: Secret<String>,
name: Secret<String>,
},
Plusgiro {
#[serde(rename = "plusgiroNumber")]
plusgiro_number: Secret<String>,
name: Secret<String>,
},
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FlowType {
ApiOnly,
FullHostedPages,
EmbeddedHostedPages,
}
impl TryFrom<&TokenioRouterData<&PaymentsAuthorizeRouterData>> for TokenioPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &TokenioRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::OpenBanking(_) => {
let (local_instrument, creditor) = match item
.router_data
.additional_merchant_data
.as_ref()
.and_then(|data| match data {
AdditionalMerchantData::OpenBankingRecipientData(recipient_data) => {
match recipient_data {
MerchantRecipientData::AccountData(account_data) => {
Some(account_data)
}
_ => None,
}
}
}) {
Some(MerchantAccountData::FasterPayments {
account_number,
sort_code,
name,
..
}) => (
LocalInstrument::FasterPayments,
Creditor::FasterPayments {
sort_code: sort_code.clone(),
account_number: account_number.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::SepaInstant { iban, name, .. }) => (
LocalInstrument::SepaInstant,
Creditor::SepaInstant {
iban: iban.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::Sepa { iban, name, .. }) => (
LocalInstrument::Sepa,
Creditor::Sepa {
iban: iban.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::Iban { iban, name, .. }) => (
LocalInstrument::Sepa, // Assuming IBAN defaults to SEPA
Creditor::Sepa {
iban: iban.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::Elixir {
account_number,
iban,
name,
..
}) => {
if !iban.peek().is_empty() {
(
LocalInstrument::Elixir,
Creditor::ElixirIban {
iban: iban.clone(),
name: name.clone().into(),
},
)
} else {
(
LocalInstrument::Elixir,
Creditor::ElixirAccount {
account_number: account_number.clone(),
name: name.clone().into(),
},
)
}
}
Some(MerchantAccountData::Bacs {
account_number,
sort_code,
name,
..
}) => (
LocalInstrument::FasterPayments,
Creditor::FasterPayments {
sort_code: sort_code.clone(),
account_number: account_number.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::Bankgiro { number, name, .. }) => (
LocalInstrument::Bankgiro,
Creditor::Bankgiro {
bankgiro_number: number.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::Plusgiro { number, name, .. }) => (
LocalInstrument::Plusgiro,
Creditor::Plusgiro {
plusgiro_number: number.clone(),
name: name.clone().into(),
},
),
None => {
return Err(errors::ConnectorError::InvalidConnectorConfig {
config: "No valid payment method found in additional merchant data",
}
.into())
}
};
Ok(Self {
initiation: PaymentInitiation {
ref_id: utils::generate_12_digit_number().to_string(),
remittance_information_primary: item.router_data.merchant_id.clone(),
amount: Amount {
value: item.amount.clone(),
currency: item.router_data.request.currency,
},
local_instrument,
creditor,
callback_url: item.router_data.request.router_return_url.clone(),
flow_type: FlowType::FullHostedPages,
},
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
pub struct TokenioAuthType {
pub(super) merchant_id: Secret<String>,
pub(super) private_key: Secret<String>,
pub(super) key_id: Secret<String>,
pub(super) key_algorithm: CryptoAlgorithm,
}
#[derive(Debug, Deserialize, PartialEq)]
pub enum CryptoAlgorithm {
RS256,
ES256,
#[serde(rename = "EdDSA")]
EDDSA,
}
impl TryFrom<&str> for CryptoAlgorithm {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(s: &str) -> Result<Self, Self::Error> {
match s.to_uppercase().as_str() {
"RS256" | "rs256" => Ok(Self::RS256),
"ES256" | "es256" => Ok(Self::ES256),
"EDDSA" | "eddsa" | "EdDSA" => Ok(Self::EDDSA),
_ => Err(errors::ConnectorError::InvalidConnectorConfig {
config: "Unsupported key algorithm. Select from RS256, ES256, EdDSA",
}
.into()),
}
}
}
impl TryFrom<&ConnectorAuthType> for TokenioAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Ok(Self {
merchant_id: key1.to_owned(),
private_key: api_secret.to_owned(),
key_id: api_key.to_owned(),
key_algorithm: CryptoAlgorithm::try_from(key2.clone().expose().as_str())?,
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenioApiWrapper {
pub payment: PaymentResponse,
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(untagged)]
pub enum TokenioPaymentsResponse {
Success(TokenioApiWrapper),
Error(TokenioErrorResponse),
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentResponse {
pub id: String,
pub status: PaymentStatus,
pub status_reason_information: Option<String>,
pub authentication: Option<Authentication>,
pub error_info: Option<ErrorInfo>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentStatus {
InitiationPending,
InitiationPendingRedirectAuth,
InitiationPendingRedirectAuthVerification,
InitiationPendingRedirectHp,
InitiationPendingRedemption,
InitiationPendingRedemptionVerification,
InitiationProcessing,
InitiationCompleted,
InitiationRejected,
InitiationRejectedInsufficientFunds,
InitiationFailed,
InitiationDeclined,
InitiationExpired,
InitiationNoFinalStatusAvailable,
SettlementInProgress,
SettlementCompleted,
SettlementIncomplete,
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(untagged)]
pub enum Authentication {
RedirectUrl {
#[serde(rename = "redirectUrl")]
redirect_url: String,
},
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorInfo {
pub http_error_code: i32,
pub message: Option<String>,
pub token_external_error: Option<bool>,
pub token_trace_id: Option<String>,
}
impl From<TokenioPaymentsResponse> for common_enums::AttemptStatus {
fn from(response: TokenioPaymentsResponse) -> Self {
match response {
TokenioPaymentsResponse::Success(wrapper) => match wrapper.payment.status {
// Pending statuses - payment is still in progress
PaymentStatus::InitiationPending
| PaymentStatus::InitiationPendingRedirectAuth
| PaymentStatus::InitiationPendingRedirectAuthVerification
| PaymentStatus::InitiationPendingRedirectHp
| PaymentStatus::InitiationPendingRedemption
| PaymentStatus::InitiationPendingRedemptionVerification => {
Self::AuthenticationPending
}
// Success statuses
PaymentStatus::SettlementCompleted => Self::Charged,
// Settlement in progress - could map to different status based on business logic
PaymentStatus::SettlementInProgress => Self::Pending,
// Failure statuses
PaymentStatus::InitiationRejected
| PaymentStatus::InitiationFailed
| PaymentStatus::InitiationExpired
| PaymentStatus::InitiationRejectedInsufficientFunds
| PaymentStatus::InitiationDeclined => Self::Failure,
// Uncertain status
PaymentStatus::InitiationCompleted
| PaymentStatus::InitiationProcessing
| PaymentStatus::InitiationNoFinalStatusAvailable
| PaymentStatus::SettlementIncomplete => Self::Pending,
},
TokenioPaymentsResponse::Error(_) => Self::Failure,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, TokenioPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, TokenioPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = common_enums::AttemptStatus::from(item.response.clone());
let response = match item.response {
TokenioPaymentsResponse::Success(wrapper) => {
let payment = wrapper.payment;
if let common_enums::AttemptStatus::Failure = status {
Err(ErrorResponse {
code: payment
.error_info
.as_ref()
.map(|ei| ei.http_error_code.to_string())
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: payment
.error_info
.as_ref()
.and_then(|ei| ei.message.clone())
.or_else(|| payment.status_reason_information.clone())
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: Some(
payment
.error_info
.as_ref()
.and_then(|ei| ei.message.clone())
.or_else(|| payment.status_reason_information.clone())
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(payment.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(payment.id.clone()),
redirection_data: Box::new(payment.authentication.as_ref().map(|auth| {
match auth {
Authentication::RedirectUrl { redirect_url } => {
RedirectForm::Form {
endpoint: redirect_url.to_string(),
method: Method::Get,
form_fields: HashMap::new(),
}
}
}
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
}
}
TokenioPaymentsResponse::Error(error_response) => Err(ErrorResponse {
code: error_response.get_error_code(),
message: error_response.get_message(),
reason: Some(error_response.get_message()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct TokenioRefundRequest {
pub amount: StringMajorUnit,
}
impl<F> TryFrom<&TokenioRouterData<&RefundsRouterData<F>>> for TokenioRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &TokenioRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(untagged)]
pub enum TokenioErrorResponse {
Json {
#[serde(rename = "errorCode")]
error_code: Option<String>,
message: Option<String>,
},
Text(String),
}
impl TokenioErrorResponse {
pub fn from_bytes(bytes: &[u8]) -> Self {
// First try to parse as JSON
if let Ok(json_response) = serde_json::from_slice::<Self>(bytes) {
json_response
} else {
// If JSON parsing fails, treat as plain text
let text = String::from_utf8_lossy(bytes).to_string();
Self::Text(text)
}
}
pub fn get_message(&self) -> String {
match self {
Self::Json {
message,
error_code,
} => message
.as_deref()
.or(error_code.as_deref())
.unwrap_or(NO_ERROR_MESSAGE)
.to_string(),
Self::Text(text) => text.clone(),
}
}
pub fn get_error_code(&self) -> String {
match self {
Self::Json { error_code, .. } => {
error_code.as_deref().unwrap_or(NO_ERROR_CODE).to_string()
}
Self::Text(_) => NO_ERROR_CODE.to_string(),
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TokenioWebhookEventType {
PaymentStatusChanged,
#[serde(other)]
Unknown,
}
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TokenioWebhookPaymentStatus {
InitiationCompleted,
PaymentCompleted,
PaymentFailed,
PaymentCancelled,
InitiationRejected,
InitiationProcessing,
#[serde(other)]
Unknown,
}
// Base webhook payload structure
#[derive(Debug, Deserialize, Serialize)]
pub struct TokenioWebhookPayload {
#[serde(rename = "eventType", skip_serializing_if = "Option::is_none")]
pub event_type: Option<String>,
pub id: String,
#[serde(flatten)]
pub event_data: TokenioWebhookEventData,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum TokenioWebhookEventData {
PaymentV2 { payment: TokenioPaymentObjectV2 },
}
// Payment v2 structures
#[derive(Debug, Deserialize, Serialize)]
pub struct TokenioPaymentObjectV2 {
pub id: String,
pub status: TokenioPaymentStatus,
}
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TokenioPaymentStatus {
InitiationCompleted,
PaymentCompleted,
PaymentFailed,
PaymentCancelled,
InitiationRejected,
InitiationProcessing,
InitiationPendingRedirectHp,
#[serde(other)]
Other,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4488
}
|
large_file_7336154928232156901
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs
</path>
<file>
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
use std::str::FromStr;
use common_enums::enums;
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
use common_utils::types::{ConnectorTransactionId, FloatMajorUnitForConnector};
use common_utils::{
errors::CustomResult,
ext_traits::ByteSliceExt,
id_type,
types::{FloatMajorUnit, StringMinorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::router_data::ConnectorAuthType;
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
use hyperswitch_domain_models::{
router_data_v2::flow_common_types as recovery_flow_common_types,
router_flow_types::revenue_recovery as recovery_router_flows,
router_request_types::revenue_recovery as recovery_request_types,
router_response_types::revenue_recovery as recovery_response_types,
types as recovery_router_data_types,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
use crate::{types::ResponseRouterDataV2, utils};
pub struct RecurlyRouterData<T> {
pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for RecurlyRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
}
}
}
// Auth Struct
pub struct RecurlyAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for RecurlyAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct RecurlyErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct RecurlyWebhookBody {
// Transaction uuid
pub uuid: String,
pub event_type: RecurlyPaymentEventType,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub enum RecurlyPaymentEventType {
#[serde(rename = "succeeded")]
PaymentSucceeded,
#[serde(rename = "failed")]
PaymentFailed,
}
impl RecurlyWebhookBody {
pub fn get_webhook_object_from_body(body: &[u8]) -> CustomResult<Self, errors::ConnectorError> {
let webhook_body = body
.parse_struct::<Self>("RecurlyWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(webhook_body)
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub enum RecurlyChargeStatus {
#[serde(rename = "success")]
Succeeded,
#[serde(rename = "declined")]
Failed,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum RecurlyFundingTypes {
Credit,
Debit,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum RecurlyPaymentObject {
CreditCard,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RecurlyRecoveryDetailsData {
pub amount: FloatMajorUnit,
pub currency: common_enums::Currency,
pub id: String,
pub status_code: Option<String>,
pub status_message: Option<String>,
pub account: Account,
pub invoice: Invoice,
pub payment_method: PaymentMethod,
pub payment_gateway: PaymentGateway,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
pub status: RecurlyChargeStatus,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentMethod {
pub gateway_token: String,
pub funding_source: RecurlyFundingTypes,
pub object: RecurlyPaymentObject,
pub card_type: common_enums::CardNetwork,
pub first_six: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Invoice {
pub id: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Account {
pub id: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentGateway {
pub id: String,
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl
TryFrom<
ResponseRouterDataV2<
recovery_router_flows::BillingConnectorPaymentsSync,
RecurlyRecoveryDetailsData,
recovery_flow_common_types::BillingConnectorPaymentsSyncFlowData,
recovery_request_types::BillingConnectorPaymentsSyncRequest,
recovery_response_types::BillingConnectorPaymentsSyncResponse,
>,
> for recovery_router_data_types::BillingConnectorPaymentsSyncRouterDataV2
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterDataV2<
recovery_router_flows::BillingConnectorPaymentsSync,
RecurlyRecoveryDetailsData,
recovery_flow_common_types::BillingConnectorPaymentsSyncFlowData,
recovery_request_types::BillingConnectorPaymentsSyncRequest,
recovery_response_types::BillingConnectorPaymentsSyncResponse,
>,
) -> Result<Self, Self::Error> {
let merchant_reference_id =
id_type::PaymentReferenceId::from_str(&item.response.invoice.id)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let connector_transaction_id = Some(ConnectorTransactionId::from(item.response.id));
Ok(Self {
response: Ok(
recovery_response_types::BillingConnectorPaymentsSyncResponse {
status: item.response.status.into(),
amount: utils::convert_back_amount_to_minor_units(
&FloatMajorUnitForConnector,
item.response.amount,
item.response.currency,
)?,
currency: item.response.currency,
merchant_reference_id,
connector_account_reference_id: item.response.payment_gateway.id,
connector_transaction_id,
error_code: item.response.status_code,
error_message: item.response.status_message,
processor_payment_method_token: item.response.payment_method.gateway_token,
connector_customer_id: item.response.account.id,
transaction_created_at: Some(item.response.created_at),
payment_method_sub_type: common_enums::PaymentMethodType::from(
item.response.payment_method.funding_source,
),
payment_method_type: common_enums::PaymentMethod::from(
item.response.payment_method.object,
),
// This none because this field is specific to stripebilling.
charge_id: None,
// Need to populate these card info field
card_info: api_models::payments::AdditionalCardInfo {
card_network: Some(item.response.payment_method.card_type),
card_isin: Some(item.response.payment_method.first_six),
card_issuer: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
last4: None,
card_extended_bin: None,
card_exp_month: None,
card_exp_year: None,
card_holder_name: None,
payment_checks: None,
authentication_data: None,
is_regulated: None,
signature_network: None,
},
},
),
..item.data
})
}
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl From<RecurlyChargeStatus> for enums::AttemptStatus {
fn from(status: RecurlyChargeStatus) -> Self {
match status {
RecurlyChargeStatus::Succeeded => Self::Charged,
RecurlyChargeStatus::Failed => Self::Failure,
}
}
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl From<RecurlyFundingTypes> for common_enums::PaymentMethodType {
fn from(funding: RecurlyFundingTypes) -> Self {
match funding {
RecurlyFundingTypes::Credit => Self::Credit,
RecurlyFundingTypes::Debit => Self::Debit,
}
}
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl From<RecurlyPaymentObject> for common_enums::PaymentMethod {
fn from(funding: RecurlyPaymentObject) -> Self {
match funding {
RecurlyPaymentObject::CreditCard => Self::Card,
}
}
}
#[derive(Debug, Serialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum RecurlyRecordStatus {
Success,
Failure,
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl TryFrom<enums::AttemptStatus> for RecurlyRecordStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(status: enums::AttemptStatus) -> Result<Self, Self::Error> {
match status {
enums::AttemptStatus::Charged
| enums::AttemptStatus::PartialCharged
| enums::AttemptStatus::PartialChargedAndChargeable => Ok(Self::Success),
enums::AttemptStatus::Failure
| enums::AttemptStatus::CaptureFailed
| enums::AttemptStatus::RouterDeclined => Ok(Self::Failure),
enums::AttemptStatus::AuthenticationFailed
| enums::AttemptStatus::Started
| enums::AttemptStatus::AuthenticationPending
| enums::AttemptStatus::AuthenticationSuccessful
| enums::AttemptStatus::Authorized
| enums::AttemptStatus::PartiallyAuthorized
| enums::AttemptStatus::AuthorizationFailed
| enums::AttemptStatus::Authorizing
| enums::AttemptStatus::CodInitiated
| enums::AttemptStatus::Voided
| enums::AttemptStatus::VoidedPostCharge
| enums::AttemptStatus::VoidInitiated
| enums::AttemptStatus::CaptureInitiated
| enums::AttemptStatus::VoidFailed
| enums::AttemptStatus::AutoRefunded
| enums::AttemptStatus::Unresolved
| enums::AttemptStatus::Pending
| enums::AttemptStatus::PaymentMethodAwaited
| enums::AttemptStatus::ConfirmationAwaited
| enums::AttemptStatus::DeviceDataCollectionPending
| enums::AttemptStatus::IntegrityFailure
| enums::AttemptStatus::Expired => Err(errors::ConnectorError::NotSupported {
message: "Record back flow is only supported for terminal status".to_string(),
connector: "recurly",
}
.into()),
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct RecurlyRecordBackResponse {
// Invoice id
pub id: id_type::PaymentReferenceId,
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl
TryFrom<
ResponseRouterDataV2<
recovery_router_flows::InvoiceRecordBack,
RecurlyRecordBackResponse,
recovery_flow_common_types::InvoiceRecordBackData,
recovery_request_types::InvoiceRecordBackRequest,
recovery_response_types::InvoiceRecordBackResponse,
>,
> for recovery_router_data_types::InvoiceRecordBackRouterDataV2
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterDataV2<
recovery_router_flows::InvoiceRecordBack,
RecurlyRecordBackResponse,
recovery_flow_common_types::InvoiceRecordBackData,
recovery_request_types::InvoiceRecordBackRequest,
recovery_response_types::InvoiceRecordBackResponse,
>,
) -> Result<Self, Self::Error> {
let merchant_reference_id = item.response.id;
Ok(Self {
response: Ok(recovery_response_types::InvoiceRecordBackResponse {
merchant_reference_id,
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct RecurlyInvoiceSyncResponse {
pub id: String,
pub total: FloatMajorUnit,
pub currency: common_enums::Currency,
pub address: Option<RecurlyInvoiceBillingAddress>,
pub line_items: Vec<RecurlyLineItems>,
pub transactions: Vec<RecurlyInvoiceTransactionsStatus>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct RecurlyInvoiceBillingAddress {
pub street1: Option<Secret<String>>,
pub street2: Option<Secret<String>>,
pub region: Option<Secret<String>>,
pub country: Option<enums::CountryAlpha2>,
pub postal_code: Option<Secret<String>>,
pub city: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct RecurlyLineItems {
#[serde(rename = "type")]
pub invoice_type: RecurlyInvoiceLineItemType,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub start_date: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub end_date: PrimitiveDateTime,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum RecurlyInvoiceLineItemType {
Credit,
Charge,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub struct RecurlyInvoiceTransactionsStatus {
pub status: String,
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl
TryFrom<
ResponseRouterDataV2<
recovery_router_flows::BillingConnectorInvoiceSync,
RecurlyInvoiceSyncResponse,
recovery_flow_common_types::BillingConnectorInvoiceSyncFlowData,
recovery_request_types::BillingConnectorInvoiceSyncRequest,
recovery_response_types::BillingConnectorInvoiceSyncResponse,
>,
> for recovery_router_data_types::BillingConnectorInvoiceSyncRouterDataV2
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterDataV2<
recovery_router_flows::BillingConnectorInvoiceSync,
RecurlyInvoiceSyncResponse,
recovery_flow_common_types::BillingConnectorInvoiceSyncFlowData,
recovery_request_types::BillingConnectorInvoiceSyncRequest,
recovery_response_types::BillingConnectorInvoiceSyncResponse,
>,
) -> Result<Self, Self::Error> {
#[allow(clippy::as_conversions)]
// No of retries never exceeds u16 in recurly. So its better to suppress the clippy warning
let retry_count = item.response.transactions.len() as u16;
let merchant_reference_id = id_type::PaymentReferenceId::from_str(&item.response.id)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Self {
response: Ok(
recovery_response_types::BillingConnectorInvoiceSyncResponse {
amount: utils::convert_back_amount_to_minor_units(
&FloatMajorUnitForConnector,
item.response.total,
item.response.currency,
)?,
currency: item.response.currency,
merchant_reference_id,
retry_count: Some(retry_count),
billing_address: Some(api_models::payments::Address {
address: Some(api_models::payments::AddressDetails {
city: item
.response
.address
.clone()
.and_then(|address| address.city),
state: item
.response
.address
.clone()
.and_then(|address| address.region),
country: item
.response
.address
.clone()
.and_then(|address| address.country),
line1: item
.response
.address
.clone()
.and_then(|address| address.street1),
line2: item
.response
.address
.clone()
.and_then(|address| address.street2),
line3: None,
zip: item
.response
.address
.clone()
.and_then(|address| address.postal_code),
first_name: None,
last_name: None,
origin_zip: None,
}),
phone: None,
email: None,
}),
created_at: item.response.line_items.first().map(|line| line.start_date),
ends_at: item.response.line_items.first().map(|line| line.end_date),
},
),
..item.data
})
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3663
}
|
large_file_2202581916572862031
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs
</path>
<file>
use std::collections::HashMap;
use common_enums::enums;
use common_utils::{
consts::{PROPHETPAY_REDIRECT_URL, PROPHETPAY_TOKEN},
errors::CustomResult,
request::Method,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{CardRedirectData, PaymentMethodData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::Execute,
router_request_types::{
CompleteAuthorizeData, CompleteAuthorizeRedirectResponse, PaymentsAuthorizeData, ResponseId,
},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
use hyperswitch_interfaces::{api, consts::NO_ERROR_CODE, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, to_connector_meta},
};
pub struct ProphetpayRouterData<T> {
pub amount: f64,
pub router_data: T,
}
impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for ProphetpayRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?;
Ok(Self {
amount,
router_data: item,
})
}
}
pub struct ProphetpayAuthType {
pub(super) user_name: Secret<String>,
pub(super) password: Secret<String>,
pub(super) profile_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for ProphetpayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
user_name: api_key.to_owned(),
password: key1.to_owned(),
profile_id: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct ProphetpayTokenRequest {
ref_info: String,
profile: Secret<String>,
entry_method: i8,
token_type: i8,
card_entry_context: i8,
}
#[derive(Debug, Clone)]
pub enum ProphetpayEntryMethod {
ManualEntry,
CardSwipe,
}
impl ProphetpayEntryMethod {
fn get_entry_method(&self) -> i8 {
match self {
Self::ManualEntry => 1,
Self::CardSwipe => 2,
}
}
}
#[derive(Debug, Clone)]
#[repr(i8)]
pub enum ProphetpayTokenType {
Normal,
SaleTab,
TemporarySave,
}
impl ProphetpayTokenType {
fn get_token_type(&self) -> i8 {
match self {
Self::Normal => 0,
Self::SaleTab => 1,
Self::TemporarySave => 2,
}
}
}
#[derive(Debug, Clone)]
#[repr(i8)]
pub enum ProphetpayCardContext {
NotApplicable,
WebConsumerInitiated,
}
impl ProphetpayCardContext {
fn get_card_context(&self) -> i8 {
match self {
Self::NotApplicable => 0,
Self::WebConsumerInitiated => 5,
}
}
}
impl TryFrom<&ProphetpayRouterData<&types::PaymentsAuthorizeRouterData>>
for ProphetpayTokenRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ProphetpayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if item.router_data.request.currency == api_models::enums::Currency::USD {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::CardRedirect(CardRedirectData::CardRedirect {}) => {
let auth_data =
ProphetpayAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
ref_info: item.router_data.connector_request_reference_id.to_owned(),
profile: auth_data.profile_id,
entry_method: ProphetpayEntryMethod::get_entry_method(
&ProphetpayEntryMethod::ManualEntry,
),
token_type: ProphetpayTokenType::get_token_type(
&ProphetpayTokenType::SaleTab,
),
card_entry_context: ProphetpayCardContext::get_card_context(
&ProphetpayCardContext::WebConsumerInitiated,
),
})
}
_ => Err(
errors::ConnectorError::NotImplemented("Payment methods".to_string()).into(),
),
}
} else {
Err(errors::ConnectorError::CurrencyNotSupported {
message: item.router_data.request.currency.to_string(),
connector: "Prophetpay",
}
.into())
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayTokenResponse {
hosted_tokenize_id: Secret<String>,
}
impl<F>
TryFrom<
ResponseRouterData<F, ProphetpayTokenResponse, PaymentsAuthorizeData, PaymentsResponseData>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
ProphetpayTokenResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let url_data = format!(
"{}{}",
PROPHETPAY_REDIRECT_URL,
item.response.hosted_tokenize_id.expose()
);
let redirect_url = Url::parse(url_data.as_str())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let redirection_data = get_redirect_url_form(
redirect_url,
item.data.request.complete_authorize_url.clone(),
)
.ok();
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
fn get_redirect_url_form(
mut redirect_url: Url,
complete_auth_url: Option<String>,
) -> CustomResult<RedirectForm, errors::ConnectorError> {
let mut form_fields = HashMap::<String, String>::new();
form_fields.insert(
String::from("redirectUrl"),
complete_auth_url.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "complete_auth_url",
})?,
);
// Do not include query params in the endpoint
redirect_url.set_query(None);
Ok(RedirectForm::Form {
endpoint: redirect_url.to_string(),
method: Method::Get,
form_fields,
})
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayCompleteRequest {
amount: f64,
ref_info: String,
inquiry_reference: String,
profile: Secret<String>,
action_type: i8,
card_token: Secret<String>,
}
impl TryFrom<&ProphetpayRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
for ProphetpayCompleteRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ProphetpayRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let auth_data = ProphetpayAuthType::try_from(&item.router_data.connector_auth_type)?;
let card_token = Secret::new(get_card_token(
item.router_data.request.redirect_response.clone(),
)?);
Ok(Self {
amount: item.amount.to_owned(),
ref_info: item.router_data.connector_request_reference_id.to_owned(),
inquiry_reference: item.router_data.connector_request_reference_id.clone(),
profile: auth_data.profile_id,
action_type: ProphetpayActionType::get_action_type(&ProphetpayActionType::Charge),
card_token,
})
}
}
fn get_card_token(
response: Option<CompleteAuthorizeRedirectResponse>,
) -> CustomResult<String, errors::ConnectorError> {
let res = response.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
})?;
let queries_params = res
.params
.map(|param| {
let mut queries = HashMap::<String, String>::new();
let values = param.peek().split('&').collect::<Vec<&str>>();
for value in values {
let pair = value.split('=').collect::<Vec<&str>>();
queries.insert(
pair.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?
.to_string(),
pair.get(1)
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?
.to_string(),
);
}
Ok::<_, errors::ConnectorError>(queries)
})
.transpose()?
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
for (key, val) in queries_params {
if key.as_str() == PROPHETPAY_TOKEN {
return Ok(val);
}
}
Err(errors::ConnectorError::MissingRequiredField {
field_name: "card_token",
}
.into())
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpaySyncRequest {
transaction_id: String,
ref_info: String,
inquiry_reference: String,
profile: Secret<String>,
action_type: i8,
}
#[derive(Debug, Clone)]
pub enum ProphetpayActionType {
Charge,
Refund,
Inquiry,
}
impl ProphetpayActionType {
fn get_action_type(&self) -> i8 {
match self {
Self::Charge => 1,
Self::Refund => 3,
Self::Inquiry => 7,
}
}
}
impl TryFrom<&types::PaymentsSyncRouterData> for ProphetpaySyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let auth_data = ProphetpayAuthType::try_from(&item.connector_auth_type)?;
let transaction_id = item
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(Self {
transaction_id,
ref_info: item.connector_request_reference_id.to_owned(),
inquiry_reference: item.connector_request_reference_id.clone(),
profile: auth_data.profile_id,
action_type: ProphetpayActionType::get_action_type(&ProphetpayActionType::Inquiry),
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayCompleteAuthResponse {
pub success: bool,
pub response_text: String,
#[serde(rename = "transactionID")]
pub transaction_id: String,
pub response_code: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProphetpayCardTokenData {
card_token: Secret<String>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
ProphetpayCompleteAuthResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
ProphetpayCompleteAuthResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
if item.response.success {
let card_token = get_card_token(item.data.request.redirect_response.clone())?;
let card_token_data = ProphetpayCardTokenData {
card_token: Secret::from(card_token),
};
let connector_metadata = serde_json::to_value(card_token_data).ok();
Ok(Self {
status: enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.transaction_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: item.response.response_code,
message: item.response.response_text.clone(),
reason: Some(item.response.response_text),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpaySyncResponse {
success: bool,
pub response_text: String,
#[serde(rename = "transactionID")]
pub transaction_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, ProphetpaySyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ProphetpaySyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
if item.response.success {
Ok(Self {
status: enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.transaction_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: item.response.response_text.clone(),
reason: Some(item.response.response_text),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayVoidResponse {
pub success: bool,
pub response_text: String,
#[serde(rename = "transactionID")]
pub transaction_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, ProphetpayVoidResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ProphetpayVoidResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
if item.response.success {
Ok(Self {
status: enums::AttemptStatus::Voided,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.transaction_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: enums::AttemptStatus::VoidFailed,
response: Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: item.response.response_text.clone(),
reason: Some(item.response.response_text),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayVoidRequest {
pub transaction_id: String,
pub profile: Secret<String>,
pub ref_info: String,
pub inquiry_reference: String,
pub action_type: i8,
}
impl TryFrom<&types::PaymentsCancelRouterData> for ProphetpayVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let auth_data = ProphetpayAuthType::try_from(&item.connector_auth_type)?;
let transaction_id = item.request.connector_transaction_id.to_owned();
Ok(Self {
transaction_id,
ref_info: item.connector_request_reference_id.to_owned(),
inquiry_reference: item.connector_request_reference_id.clone(),
profile: auth_data.profile_id,
action_type: ProphetpayActionType::get_action_type(&ProphetpayActionType::Inquiry),
})
}
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayRefundRequest {
pub amount: f64,
pub card_token: Secret<String>,
pub transaction_id: String,
pub profile: Secret<String>,
pub ref_info: String,
pub inquiry_reference: String,
pub action_type: i8,
}
impl<F> TryFrom<&ProphetpayRouterData<&types::RefundsRouterData<F>>> for ProphetpayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ProphetpayRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
if item.router_data.request.payment_amount == item.router_data.request.refund_amount {
let auth_data = ProphetpayAuthType::try_from(&item.router_data.connector_auth_type)?;
let transaction_id = item.router_data.request.connector_transaction_id.to_owned();
let card_token_data: ProphetpayCardTokenData =
to_connector_meta(item.router_data.request.connector_metadata.clone())?;
Ok(Self {
transaction_id,
amount: item.amount.to_owned(),
card_token: card_token_data.card_token,
profile: auth_data.profile_id,
ref_info: item.router_data.request.refund_id.to_owned(),
inquiry_reference: item.router_data.request.refund_id.clone(),
action_type: ProphetpayActionType::get_action_type(&ProphetpayActionType::Refund),
})
} else {
Err(errors::ConnectorError::NotImplemented("Partial Refund".to_string()).into())
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayRefundResponse {
pub success: bool,
pub response_text: String,
pub tran_seq_number: Option<String>,
}
impl TryFrom<RefundsResponseRouterData<Execute, ProphetpayRefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, ProphetpayRefundResponse>,
) -> Result<Self, Self::Error> {
if item.response.success {
Ok(Self {
response: Ok(RefundsResponseData {
// no refund id is generated, tranSeqNumber is kept for future usage
connector_refund_id: item.response.tran_seq_number.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "tran_seq_number",
},
)?,
refund_status: enums::RefundStatus::Success,
}),
..item.data
})
} else {
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: item.response.response_text.clone(),
reason: Some(item.response.response_text),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayRefundSyncResponse {
pub success: bool,
pub response_text: String,
}
impl<T> TryFrom<RefundsResponseRouterData<T, ProphetpayRefundSyncResponse>>
for types::RefundsRouterData<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<T, ProphetpayRefundSyncResponse>,
) -> Result<Self, Self::Error> {
if item.response.success {
Ok(Self {
response: Ok(RefundsResponseData {
// no refund id is generated, rather transaction id is used for referring to status in refund also
connector_refund_id: item.data.request.connector_transaction_id.clone(),
refund_status: enums::RefundStatus::Success,
}),
..item.data
})
} else {
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: item.response.response_text.clone(),
reason: Some(item.response.response_text),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayRefundSyncRequest {
transaction_id: String,
inquiry_reference: String,
ref_info: String,
profile: Secret<String>,
action_type: i8,
}
impl TryFrom<&types::RefundSyncRouterData> for ProphetpayRefundSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
let auth_data = ProphetpayAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
transaction_id: item.request.connector_transaction_id.clone(),
ref_info: item.connector_request_reference_id.to_owned(),
inquiry_reference: item.connector_request_reference_id.clone(),
profile: auth_data.profile_id,
action_type: ProphetpayActionType::get_action_type(&ProphetpayActionType::Inquiry),
})
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5056
}
|
large_file_5829148315447254113
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs
</path>
<file>
use api_models::webhooks::IncomingWebhookEvent;
use base64::Engine;
use cards::CardNumber;
use common_enums::{enums, AttemptStatus, CaptureMethod, CountryAlpha2};
use common_utils::{
consts::BASE64_ENGINE,
errors::CustomResult,
pii::{Email, IpAddress},
types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, ResponseId,
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
connectors::paybox::transformers::parse_url_encoded_to_struct,
types::{PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
BrowserInformationData, PaymentsAuthorizeRequestData, PaymentsSyncRequestData,
RouterData as _,
},
};
pub struct GetnetRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for GetnetRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Amount {
pub value: FloatMajorUnit,
pub currency: enums::Currency,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Address {
#[serde(rename = "street1")]
pub street1: Option<Secret<String>>,
pub city: Option<String>,
pub state: Option<Secret<String>>,
pub country: Option<CountryAlpha2>,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct AccountHolder {
#[serde(rename = "first-name")]
pub first_name: Option<Secret<String>>,
#[serde(rename = "last-name")]
pub last_name: Option<Secret<String>>,
pub email: Option<Email>,
pub phone: Option<Secret<String>>,
pub address: Option<Address>,
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct Card {
#[serde(rename = "account-number")]
pub account_number: CardNumber,
#[serde(rename = "expiration-month")]
pub expiration_month: Secret<String>,
#[serde(rename = "expiration-year")]
pub expiration_year: Secret<String>,
#[serde(rename = "card-security-code")]
pub card_security_code: Secret<String>,
#[serde(rename = "card-type")]
pub card_type: String,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum GetnetPaymentMethods {
CreditCard,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct PaymentMethod {
pub name: GetnetPaymentMethods,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Notification {
pub url: Option<String>,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct PaymentMethodContainer {
#[serde(rename = "payment-method")]
pub payment_method: Vec<PaymentMethod>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum NotificationFormat {
#[serde(rename = "application/json-signed")]
JsonSigned,
#[serde(rename = "application/json")]
Json,
#[serde(rename = "application/xml")]
Xml,
#[serde(rename = "application/html")]
Html,
#[serde(rename = "application/x-www-form-urlencoded")]
Urlencoded,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct NotificationContainer {
pub notification: Vec<Notification>,
pub format: NotificationFormat,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct MerchantAccountId {
pub value: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct PaymentData {
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
#[serde(rename = "account-holder")]
pub account_holder: Option<AccountHolder>,
pub card: Card,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
#[serde(rename = "payment-methods")]
pub payment_methods: PaymentMethodContainer,
pub notifications: Option<NotificationContainer>,
}
#[derive(Debug, Serialize)]
pub struct GetnetPaymentsRequest {
payment: PaymentData,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct GetnetCard {
number: CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<enums::PaymentMethodType> for PaymentMethodContainer {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(payment_method_type: enums::PaymentMethodType) -> Result<Self, Self::Error> {
match payment_method_type {
enums::PaymentMethodType::Credit => Ok(Self {
payment_method: vec![PaymentMethod {
name: GetnetPaymentMethods::CreditCard,
}],
}),
_ => Err(errors::ConnectorError::NotSupported {
message: "Payment method type not supported".to_string(),
connector: "Getnet",
}
.into()),
}
}
}
impl TryFrom<&GetnetRouterData<&PaymentsAuthorizeRouterData>> for GetnetPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &GetnetRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ref req_card) => {
if item.router_data.is_three_ds() {
return Err(errors::ConnectorError::NotSupported {
message: "3DS payments".to_string(),
connector: "Getnet",
}
.into());
}
let request = &item.router_data.request;
let auth_type = GetnetAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let merchant_account_id = MerchantAccountId {
value: auth_type.merchant_id,
};
let requested_amount = Amount {
value: item.amount,
currency: request.currency,
};
let account_holder = AccountHolder {
first_name: item.router_data.get_optional_billing_first_name(),
last_name: item.router_data.get_optional_billing_last_name(),
email: item.router_data.request.get_optional_email(),
phone: item.router_data.get_optional_billing_phone_number(),
address: Some(Address {
street1: item.router_data.get_optional_billing_line2(),
city: item.router_data.get_optional_billing_city(),
state: item.router_data.get_optional_billing_state(),
country: item.router_data.get_optional_billing_country(),
}),
};
let card = Card {
account_number: req_card.card_number.clone(),
expiration_month: req_card.card_exp_month.clone(),
expiration_year: req_card.card_exp_year.clone(),
card_security_code: req_card.card_cvc.clone(),
card_type: req_card
.card_network
.as_ref()
.map(|network| network.to_string().to_lowercase())
.unwrap_or_default(),
};
let pmt = item.router_data.request.get_payment_method_type()?;
let payment_method = PaymentMethodContainer::try_from(pmt)?;
let notifications: NotificationContainer = NotificationContainer {
format: NotificationFormat::JsonSigned,
notification: vec![Notification {
url: Some(item.router_data.request.get_webhook_url()?),
}],
};
let transaction_type = if request.is_auto_capture()? {
GetnetTransactionType::Purchase
} else {
GetnetTransactionType::Authorization
};
let payment_data = PaymentData {
merchant_account_id,
request_id: item.router_data.payment_id.clone(),
transaction_type,
requested_amount,
account_holder: Some(account_holder),
card,
ip_address: Some(request.get_browser_info()?.get_ip_address()?),
payment_methods: payment_method,
notifications: Some(notifications),
};
Ok(Self {
payment: payment_data,
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
pub struct GetnetAuthType {
pub username: Secret<String>,
pub password: Secret<String>,
pub merchant_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for GetnetAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
username: key1.to_owned(),
password: api_key.to_owned(),
merchant_id: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum GetnetPaymentStatus {
Success,
Failed,
#[default]
InProgress,
}
impl From<GetnetPaymentStatus> for AttemptStatus {
fn from(item: GetnetPaymentStatus) -> Self {
match item {
GetnetPaymentStatus::Success => Self::Charged,
GetnetPaymentStatus::Failed => Self::Failure,
GetnetPaymentStatus::InProgress => Self::Pending,
}
}
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Status {
pub code: String,
pub description: String,
pub severity: String,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Statuses {
pub status: Vec<Status>,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct CardToken {
#[serde(rename = "token-id")]
pub token_id: Secret<String>,
#[serde(rename = "masked-account-number")]
pub masked_account_number: Secret<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct PaymentResponseData {
pub statuses: Statuses,
pub descriptor: Option<String>,
pub notifications: NotificationContainer,
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "transaction-id")]
pub transaction_id: String,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "transaction-state")]
pub transaction_state: GetnetPaymentStatus,
#[serde(rename = "completion-time-stamp")]
pub completion_time_stamp: Option<i64>,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
#[serde(rename = "account-holder")]
pub account_holder: Option<AccountHolder>,
#[serde(rename = "card-token")]
pub card_token: CardToken,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
#[serde(rename = "payment-methods")]
pub payment_methods: PaymentMethodContainer,
#[serde(rename = "api-id")]
pub api_id: String,
#[serde(rename = "self")]
pub self_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentsResponse {
payment: PaymentResponseData,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetnetPaymentsResponse {
PaymentsResponse(Box<PaymentsResponse>),
GetnetWebhookNotificationResponse(Box<GetnetWebhookNotificationResponseBody>),
}
pub fn authorization_attempt_status_from_transaction_state(
getnet_status: GetnetPaymentStatus,
is_auto_capture: bool,
) -> AttemptStatus {
match getnet_status {
GetnetPaymentStatus::Success => {
if is_auto_capture {
AttemptStatus::Charged
} else {
AttemptStatus::Authorized
}
}
GetnetPaymentStatus::InProgress => AttemptStatus::Pending,
GetnetPaymentStatus::Failed => AttemptStatus::Failure,
}
}
impl<F>
TryFrom<
ResponseRouterData<F, GetnetPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
GetnetPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
GetnetPaymentsResponse::PaymentsResponse(ref payment_response) => Ok(Self {
status: authorization_attempt_status_from_transaction_state(
payment_response.payment.transaction_state.clone(),
item.data.request.is_auto_capture()?,
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
payment_response.payment.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
_ => Err(error_stack::Report::new(
errors::ConnectorError::ResponseHandlingFailed,
)),
}
}
}
pub fn psync_attempt_status_from_transaction_state(
getnet_status: GetnetPaymentStatus,
is_auto_capture: bool,
transaction_type: GetnetTransactionType,
) -> AttemptStatus {
match getnet_status {
GetnetPaymentStatus::Success => {
if is_auto_capture && transaction_type == GetnetTransactionType::CaptureAuthorization {
AttemptStatus::Charged
} else {
AttemptStatus::Authorized
}
}
GetnetPaymentStatus::InProgress => AttemptStatus::Pending,
GetnetPaymentStatus::Failed => AttemptStatus::Failure,
}
}
impl TryFrom<PaymentsSyncResponseRouterData<GetnetPaymentsResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<GetnetPaymentsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
GetnetPaymentsResponse::PaymentsResponse(ref payment_response) => Ok(Self {
status: authorization_attempt_status_from_transaction_state(
payment_response.payment.transaction_state.clone(),
item.data.request.is_auto_capture()?,
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
payment_response.payment.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
GetnetPaymentsResponse::GetnetWebhookNotificationResponse(ref webhook_response) => {
Ok(Self {
status: psync_attempt_status_from_transaction_state(
webhook_response.payment.transaction_state.clone(),
item.data.request.is_auto_capture()?,
webhook_response.payment.transaction_type.clone(),
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
webhook_response.payment.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CapturePaymentData {
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "parent-transaction-id")]
pub parent_transaction_id: String,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
pub notifications: NotificationContainer,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
}
#[derive(Debug, Serialize)]
pub struct GetnetCaptureRequest {
pub payment: CapturePaymentData,
}
impl TryFrom<&GetnetRouterData<&PaymentsCaptureRouterData>> for GetnetCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &GetnetRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
let auth_type = GetnetAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let merchant_account_id = MerchantAccountId {
value: auth_type.merchant_id,
};
let requested_amount = Amount {
value: item.amount,
currency: request.currency,
};
let req = &item.router_data.request;
let webhook_url = &req.webhook_url;
let notifications = NotificationContainer {
format: NotificationFormat::JsonSigned,
notification: vec![Notification {
url: webhook_url.clone(),
}],
};
let transaction_type = GetnetTransactionType::CaptureAuthorization;
let ip_address = req
.browser_info
.as_ref()
.and_then(|info| info.ip_address.as_ref())
.map(|ip| Secret::new(ip.to_string()));
let request_id = item.router_data.connector_request_reference_id.clone();
let parent_transaction_id = item.router_data.request.connector_transaction_id.clone();
let capture_payment_data = CapturePaymentData {
merchant_account_id,
request_id,
transaction_type,
parent_transaction_id,
requested_amount,
notifications,
ip_address,
};
Ok(Self {
payment: capture_payment_data,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CaptureResponseData {
pub statuses: Statuses,
pub descriptor: String,
pub notifications: NotificationContainer,
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "transaction-id")]
pub transaction_id: String,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "transaction-state")]
pub transaction_state: GetnetPaymentStatus,
#[serde(rename = "completion-time-stamp")]
pub completion_time_stamp: Option<i64>,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
#[serde(rename = "parent-transaction-id")]
pub parent_transaction_id: String,
#[serde(rename = "account-holder")]
pub account_holder: Option<AccountHolder>,
#[serde(rename = "card-token")]
pub card_token: CardToken,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
#[serde(rename = "payment-methods")]
pub payment_methods: PaymentMethodContainer,
#[serde(rename = "parent-transaction-amount")]
pub parent_transaction_amount: Amount,
#[serde(rename = "authorization-code")]
pub authorization_code: String,
#[serde(rename = "api-id")]
pub api_id: String,
#[serde(rename = "self")]
pub self_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetnetCaptureResponse {
payment: CaptureResponseData,
}
pub fn capture_status_from_transaction_state(getnet_status: GetnetPaymentStatus) -> AttemptStatus {
match getnet_status {
GetnetPaymentStatus::Success => AttemptStatus::Charged,
GetnetPaymentStatus::InProgress => AttemptStatus::Pending,
GetnetPaymentStatus::Failed => AttemptStatus::Authorized,
}
}
impl<F>
TryFrom<ResponseRouterData<F, GetnetCaptureResponse, PaymentsCaptureData, PaymentsResponseData>>
for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
GetnetCaptureResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: capture_status_from_transaction_state(item.response.payment.transaction_state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.payment.transaction_id,
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct RefundPaymentData {
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "parent-transaction-id")]
pub parent_transaction_id: String,
pub notifications: NotificationContainer,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
}
#[derive(Debug, Serialize)]
pub struct GetnetRefundRequest {
pub payment: RefundPaymentData,
}
impl<F> TryFrom<&GetnetRouterData<&RefundsRouterData<F>>> for GetnetRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &GetnetRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
let auth_type = GetnetAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let url = request.webhook_url.clone();
let merchant_account_id = MerchantAccountId {
value: auth_type.merchant_id,
};
let notifications = NotificationContainer {
format: NotificationFormat::JsonSigned,
notification: vec![Notification { url }],
};
let capture_method = request.capture_method;
let transaction_type = match capture_method {
Some(CaptureMethod::Automatic) => GetnetTransactionType::RefundPurchase,
Some(CaptureMethod::Manual) => GetnetTransactionType::RefundCapture,
Some(CaptureMethod::ManualMultiple)
| Some(CaptureMethod::Scheduled)
| Some(CaptureMethod::SequentialAutomatic)
| None => {
return Err(errors::ConnectorError::CaptureMethodNotSupported {}.into());
}
};
let ip_address = request
.browser_info
.as_ref()
.and_then(|browser_info| browser_info.ip_address.as_ref())
.map(|ip| Secret::new(ip.to_string()));
let request_id = item
.router_data
.refund_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?;
let parent_transaction_id = item.router_data.request.connector_transaction_id.clone();
let refund_payment_data = RefundPaymentData {
merchant_account_id,
request_id,
transaction_type,
parent_transaction_id,
notifications,
ip_address,
};
Ok(Self {
payment: refund_payment_data,
})
}
}
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum RefundStatus {
Success,
Failed,
#[default]
InProgress,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Success => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::InProgress => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RefundResponseData {
pub statuses: Statuses,
pub descriptor: String,
pub notifications: NotificationContainer,
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "transaction-id")]
pub transaction_id: String,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "transaction-state")]
pub transaction_state: RefundStatus,
#[serde(rename = "completion-time-stamp")]
pub completion_time_stamp: Option<i64>,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
#[serde(rename = "parent-transaction-id")]
#[serde(skip_serializing_if = "Option::is_none")]
pub parent_transaction_id: Option<String>,
#[serde(rename = "account-holder")]
pub account_holder: Option<AccountHolder>,
#[serde(rename = "card-token")]
pub card_token: CardToken,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
#[serde(rename = "payment-methods")]
pub payment_methods: PaymentMethodContainer,
#[serde(rename = "parent-transaction-amount")]
#[serde(skip_serializing_if = "Option::is_none")]
pub parent_transaction_amount: Option<Amount>,
#[serde(rename = "api-id")]
pub api_id: String,
#[serde(rename = "self")]
pub self_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
payment: RefundResponseData,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.payment.transaction_id,
refund_status: enums::RefundStatus::from(item.response.payment.transaction_state),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.payment.transaction_id,
refund_status: enums::RefundStatus::from(item.response.payment.transaction_state),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CancelPaymentData {
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "parent-transaction-id")]
pub parent_transaction_id: String,
pub notifications: NotificationContainer,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
}
#[derive(Debug, Serialize)]
pub struct GetnetCancelRequest {
pub payment: CancelPaymentData,
}
impl TryFrom<&PaymentsCancelRouterData> for GetnetCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let request = &item.request;
let auth_type = GetnetAuthType::try_from(&item.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let merchant_account_id = MerchantAccountId {
value: auth_type.merchant_id,
};
let webhook_url = &item.request.webhook_url;
let notifications = NotificationContainer {
format: NotificationFormat::JsonSigned,
notification: vec![Notification {
url: webhook_url.clone(),
}],
};
let capture_method = &item.request.capture_method;
let transaction_type = match capture_method {
Some(CaptureMethod::Automatic) => GetnetTransactionType::VoidPurchase,
Some(CaptureMethod::Manual) => GetnetTransactionType::VoidAuthorization,
Some(CaptureMethod::ManualMultiple)
| Some(CaptureMethod::Scheduled)
| Some(CaptureMethod::SequentialAutomatic) => {
return Err(errors::ConnectorError::CaptureMethodNotSupported {}.into());
}
None => {
return Err(errors::ConnectorError::CaptureMethodNotSupported {}.into());
}
};
let ip_address = request
.browser_info
.as_ref()
.and_then(|browser_info| browser_info.ip_address.as_ref())
.map(|ip| Secret::new(ip.to_string()));
let request_id = &item.connector_request_reference_id.clone();
let parent_transaction_id = item.request.connector_transaction_id.clone();
let cancel_payment_data = CancelPaymentData {
merchant_account_id,
request_id: request_id.to_string(),
transaction_type,
parent_transaction_id,
notifications,
ip_address,
};
Ok(Self {
payment: cancel_payment_data,
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum GetnetTransactionType {
Purchase,
#[serde(rename = "capture-authorization")]
CaptureAuthorization,
#[serde(rename = "refund-purchase")]
RefundPurchase,
#[serde(rename = "refund-capture")]
RefundCapture,
#[serde(rename = "void-authorization")]
VoidAuthorization,
#[serde(rename = "void-purchase")]
VoidPurchase,
Authorization,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub struct CancelResponseData {
pub statuses: Statuses,
pub descriptor: String,
pub notifications: NotificationContainer,
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "transaction-id")]
pub transaction_id: String,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "transaction-state")]
pub transaction_state: GetnetPaymentStatus,
#[serde(rename = "completion-time-stamp")]
pub completion_time_stamp: Option<i64>,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
#[serde(rename = "parent-transaction-id")]
pub parent_transaction_id: String,
#[serde(rename = "account-holder")]
pub account_holder: Option<AccountHolder>,
#[serde(rename = "card-token")]
pub card_token: CardToken,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
#[serde(rename = "payment-methods")]
pub payment_methods: PaymentMethodContainer,
#[serde(rename = "parent-transaction-amount")]
pub parent_transaction_amount: Amount,
#[serde(rename = "api-id")]
pub api_id: String,
#[serde(rename = "self")]
pub self_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetnetCancelResponse {
payment: CancelResponseData,
}
pub fn cancel_status_from_transaction_state(getnet_status: GetnetPaymentStatus) -> AttemptStatus {
match getnet_status {
GetnetPaymentStatus::Success => AttemptStatus::Voided,
GetnetPaymentStatus::InProgress => AttemptStatus::Pending,
GetnetPaymentStatus::Failed => AttemptStatus::VoidFailed,
}
}
impl<F>
TryFrom<ResponseRouterData<F, GetnetCancelResponse, PaymentsCancelData, PaymentsResponseData>>
for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, GetnetCancelResponse, PaymentsCancelData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: cancel_status_from_transaction_state(item.response.payment.transaction_state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.payment.transaction_id,
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct GetnetErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct GetnetWebhookNotificationResponse {
#[serde(rename = "response-signature-base64")]
pub response_signature_base64: Secret<String>,
#[serde(rename = "response-signature-algorithm")]
pub response_signature_algorithm: Secret<String>,
#[serde(rename = "response-base64")]
pub response_base64: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct WebhookResponseData {
pub statuses: Statuses,
pub descriptor: String,
pub notifications: NotificationContainer,
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "transaction-id")]
pub transaction_id: String,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "transaction-state")]
pub transaction_state: GetnetPaymentStatus,
#[serde(rename = "completion-time-stamp")]
pub completion_time_stamp: u64,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
#[serde(rename = "parent-transaction-id")]
#[serde(skip_serializing_if = "Option::is_none")]
pub parent_transaction_id: Option<String>,
#[serde(rename = "account-holder")]
pub account_holder: Option<AccountHolder>,
#[serde(rename = "card-token")]
pub card_token: CardToken,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
#[serde(rename = "payment-methods")]
pub payment_methods: PaymentMethodContainer,
#[serde(rename = "parent-transaction-amount")]
#[serde(skip_serializing_if = "Option::is_none")]
pub parent_transaction_amount: Option<Amount>,
#[serde(rename = "authorization-code")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization_code: Option<String>,
#[serde(rename = "api-id")]
pub api_id: String,
#[serde(rename = "provider-account-id")]
#[serde(skip_serializing_if = "Option::is_none")]
pub provider_account_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct GetnetWebhookNotificationResponseBody {
pub payment: WebhookResponseData,
}
pub fn is_refund_event(transaction_type: &GetnetTransactionType) -> bool {
matches!(
transaction_type,
GetnetTransactionType::RefundPurchase | GetnetTransactionType::RefundCapture
)
}
pub fn get_webhook_object_from_body(
body: &[u8],
) -> CustomResult<GetnetWebhookNotificationResponseBody, errors::ConnectorError> {
let body_bytes = bytes::Bytes::copy_from_slice(body);
let parsed_param: GetnetWebhookNotificationResponse =
parse_url_encoded_to_struct(body_bytes)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let response_base64 = &parsed_param.response_base64.peek();
let decoded_response = BASE64_ENGINE
.decode(response_base64)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let getnet_webhook_notification_response: GetnetWebhookNotificationResponseBody =
match serde_json::from_slice::<GetnetWebhookNotificationResponseBody>(&decoded_response) {
Ok(response) => response,
Err(_e) => {
return Err(errors::ConnectorError::WebhookBodyDecodingFailed)?;
}
};
Ok(getnet_webhook_notification_response)
}
pub fn get_webhook_response(
body: &[u8],
) -> CustomResult<GetnetWebhookNotificationResponse, errors::ConnectorError> {
let body_bytes = bytes::Bytes::copy_from_slice(body);
let parsed_param: GetnetWebhookNotificationResponse =
parse_url_encoded_to_struct(body_bytes)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(parsed_param)
}
pub fn get_incoming_webhook_event(
transaction_type: GetnetTransactionType,
transaction_status: GetnetPaymentStatus,
) -> IncomingWebhookEvent {
match transaction_type {
GetnetTransactionType::Purchase => match transaction_status {
GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentSuccess,
GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentFailure,
GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentProcessing,
},
GetnetTransactionType::Authorization => match transaction_status {
GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentAuthorizationSuccess,
GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentAuthorizationFailure,
GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentProcessing,
},
GetnetTransactionType::CaptureAuthorization => match transaction_status {
GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentCaptureSuccess,
GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentCaptureFailure,
GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentCaptureFailure,
},
GetnetTransactionType::RefundPurchase => match transaction_status {
GetnetPaymentStatus::Success => IncomingWebhookEvent::RefundSuccess,
GetnetPaymentStatus::Failed => IncomingWebhookEvent::RefundFailure,
GetnetPaymentStatus::InProgress => IncomingWebhookEvent::RefundFailure,
},
GetnetTransactionType::RefundCapture => match transaction_status {
GetnetPaymentStatus::Success => IncomingWebhookEvent::RefundSuccess,
GetnetPaymentStatus::Failed => IncomingWebhookEvent::RefundFailure,
GetnetPaymentStatus::InProgress => IncomingWebhookEvent::RefundFailure,
},
GetnetTransactionType::VoidAuthorization => match transaction_status {
GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentCancelled,
GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentCancelFailure,
GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentCancelFailure,
},
GetnetTransactionType::VoidPurchase => match transaction_status {
GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentCancelled,
GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentCancelFailure,
GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentCancelFailure,
},
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 8674
}
|
large_file_7173959942773449599
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
</path>
<file>
use cards::CardNumber;
use common_enums::enums;
use common_utils::{pii::Email, request::Method, types::StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankDebitData, BankRedirectData, PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
utils::{
AddressDetailsData, BrowserInformationData, CardData as CardDataUtil,
PaymentMethodTokenizationRequestData, PaymentsAuthorizeRequestData, RouterData as _,
},
};
type Error = error_stack::Report<errors::ConnectorError>;
#[derive(Debug, Serialize)]
pub struct MollieRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for MollieRouterData<T> {
fn from((amount, router_data): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MolliePaymentsRequest {
amount: Amount,
description: String,
redirect_url: String,
cancel_url: Option<String>,
webhook_url: String,
locale: Option<String>,
#[serde(flatten)]
payment_method_data: MolliePaymentMethodData,
metadata: Option<MollieMetadata>,
sequence_type: SequenceType,
mandate_id: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct Amount {
currency: enums::Currency,
value: StringMajorUnit,
}
#[derive(Debug, Serialize)]
#[serde(tag = "method")]
#[serde(rename_all = "lowercase")]
pub enum MolliePaymentMethodData {
Applepay(Box<ApplePayMethodData>),
Eps,
Giropay,
Ideal(Box<IdealMethodData>),
Paypal(Box<PaypalMethodData>),
Sofort,
Przelewy24(Box<Przelewy24MethodData>),
Bancontact,
CreditCard(Box<CreditCardMethodData>),
DirectDebit(Box<DirectDebitMethodData>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayMethodData {
apple_pay_payment_token: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IdealMethodData {
issuer: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaypalMethodData {
billing_address: Option<Address>,
shipping_address: Option<Address>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Przelewy24MethodData {
billing_email: Option<Email>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DirectDebitMethodData {
consumer_name: Option<Secret<String>>,
consumer_account: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreditCardMethodData {
billing_address: Option<Address>,
shipping_address: Option<Address>,
card_token: Option<Secret<String>>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SequenceType {
#[default]
Oneoff,
First,
Recurring,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Address {
pub street_and_number: Secret<String>,
pub postal_code: Secret<String>,
pub city: String,
pub region: Option<Secret<String>>,
pub country: api_models::enums::CountryAlpha2,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MollieMetadata {
pub order_id: String,
}
impl TryFrom<&MollieRouterData<&types::PaymentsAuthorizeRouterData>> for MolliePaymentsRequest {
type Error = Error;
fn try_from(
item: &MollieRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let amount = Amount {
currency: item.router_data.request.currency,
value: item.amount.clone(),
};
let description = item.router_data.get_description()?;
let redirect_url = item.router_data.request.get_router_return_url()?;
let payment_method_data = match item.router_data.request.capture_method.unwrap_or_default()
{
enums::CaptureMethod::Automatic | enums::CaptureMethod::SequentialAutomatic => {
match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(_) => {
let pm_token = item.router_data.get_payment_method_token()?;
Ok(MolliePaymentMethodData::CreditCard(Box::new(
CreditCardMethodData {
billing_address: get_billing_details(item.router_data)?,
shipping_address: get_shipping_details(item.router_data)?,
card_token: Some(match pm_token {
PaymentMethodToken::Token(token) => token,
PaymentMethodToken::ApplePayDecrypt(_) => {
Err(unimplemented_payment_method!(
"Apple Pay",
"Simplified",
"Mollie"
))?
}
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Mollie"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Mollie"))?
}
}),
},
)))
}
PaymentMethodData::BankRedirect(ref redirect_data) => {
MolliePaymentMethodData::try_from((item.router_data, redirect_data))
}
PaymentMethodData::Wallet(ref wallet_data) => {
get_payment_method_for_wallet(item.router_data, wallet_data)
}
PaymentMethodData::BankDebit(ref directdebit_data) => {
MolliePaymentMethodData::try_from((directdebit_data, item.router_data))
}
_ => Err(
errors::ConnectorError::NotImplemented("Payment Method".to_string()).into(),
),
}
}
_ => Err(errors::ConnectorError::FlowNotSupported {
flow: format!(
"{} capture",
item.router_data.request.capture_method.unwrap_or_default()
),
connector: "Mollie".to_string(),
}
.into()),
}?;
Ok(Self {
amount,
description,
redirect_url,
cancel_url: None,
/* webhook_url is a mandatory field.
But we can't support webhook in our core hence keeping it as empty string */
webhook_url: "".to_string(),
locale: None,
payment_method_data,
metadata: Some(MollieMetadata {
order_id: item.router_data.connector_request_reference_id.clone(),
}),
sequence_type: SequenceType::Oneoff,
mandate_id: None,
})
}
}
impl TryFrom<(&types::PaymentsAuthorizeRouterData, &BankRedirectData)> for MolliePaymentMethodData {
type Error = Error;
fn try_from(
(item, value): (&types::PaymentsAuthorizeRouterData, &BankRedirectData),
) -> Result<Self, Self::Error> {
match value {
BankRedirectData::Eps { .. } => Ok(Self::Eps),
BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
BankRedirectData::Ideal { .. } => {
Ok(Self::Ideal(Box::new(IdealMethodData {
// To do if possible this should be from the payment request
issuer: None,
})))
}
BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
BankRedirectData::Przelewy24 { .. } => {
Ok(Self::Przelewy24(Box::new(Przelewy24MethodData {
billing_email: item.get_optional_billing_email(),
})))
}
BankRedirectData::BancontactCard { .. } => Ok(Self::Bancontact),
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
impl TryFrom<(&BankDebitData, &types::PaymentsAuthorizeRouterData)> for MolliePaymentMethodData {
type Error = Error;
fn try_from(
(bank_debit_data, item): (&BankDebitData, &types::PaymentsAuthorizeRouterData),
) -> Result<Self, Self::Error> {
match bank_debit_data {
BankDebitData::SepaBankDebit { iban, .. } => {
Ok(Self::DirectDebit(Box::new(DirectDebitMethodData {
consumer_name: item.get_optional_billing_full_name(),
consumer_account: iban.clone(),
})))
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MollieCardTokenRequest {
card_holder: Secret<String>,
card_number: CardNumber,
card_cvv: Secret<String>,
card_expiry_date: Secret<String>,
locale: String,
testmode: bool,
profile_token: Secret<String>,
}
impl TryFrom<&types::TokenizationRouterData> for MollieCardTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => {
let auth = MollieAuthType::try_from(&item.connector_auth_type)?;
let card_holder = item
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string()));
let card_number = ccard.card_number.clone();
let card_expiry_date =
ccard.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?;
let card_cvv = ccard.card_cvc;
let locale = item.request.get_browser_info()?.get_language()?;
let testmode =
item.test_mode
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "test_mode",
})?;
let profile_token = auth
.profile_token
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(Self {
card_holder,
card_number,
card_cvv,
card_expiry_date,
locale,
testmode,
profile_token,
})
}
_ => Err(errors::ConnectorError::NotImplemented(
"Payment Method".to_string(),
))?,
}
}
}
fn get_payment_method_for_wallet(
item: &types::PaymentsAuthorizeRouterData,
wallet_data: &WalletData,
) -> Result<MolliePaymentMethodData, Error> {
match wallet_data {
WalletData::PaypalRedirect { .. } => Ok(MolliePaymentMethodData::Paypal(Box::new(
PaypalMethodData {
billing_address: get_billing_details(item)?,
shipping_address: get_shipping_details(item)?,
},
))),
WalletData::ApplePay(applepay_wallet_data) => {
let apple_pay_encrypted_data = applepay_wallet_data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
Ok(MolliePaymentMethodData::Applepay(Box::new(
ApplePayMethodData {
apple_pay_payment_token: Secret::new(apple_pay_encrypted_data.to_owned()),
},
)))
}
_ => Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into()),
}
}
fn get_shipping_details(
item: &types::PaymentsAuthorizeRouterData,
) -> Result<Option<Address>, Error> {
let shipping_address = item
.get_optional_shipping()
.and_then(|shipping| shipping.address.as_ref());
get_address_details(shipping_address)
}
fn get_billing_details(
item: &types::PaymentsAuthorizeRouterData,
) -> Result<Option<Address>, Error> {
let billing_address = item
.get_optional_billing()
.and_then(|billing| billing.address.as_ref());
get_address_details(billing_address)
}
fn get_address_details(
address: Option<&hyperswitch_domain_models::address::AddressDetails>,
) -> Result<Option<Address>, Error> {
let address_details = match address {
Some(address) => {
let street_and_number = address.get_combined_address_line()?;
let postal_code = address.get_zip()?.to_owned();
let city = address.get_city()?.to_owned();
let region = None;
let country = address.get_country()?.to_owned();
Some(Address {
street_and_number,
postal_code,
city,
region,
country,
})
}
None => None,
};
Ok(address_details)
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MolliePaymentsResponse {
pub resource: String,
pub id: String,
pub amount: Amount,
pub description: Option<String>,
pub metadata: Option<MollieMetadata>,
pub status: MolliePaymentStatus,
pub is_cancelable: Option<bool>,
pub sequence_type: SequenceType,
pub redirect_url: Option<String>,
pub webhook_url: Option<String>,
#[serde(rename = "_links")]
pub links: Links,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum MolliePaymentStatus {
Open,
Canceled,
#[default]
Pending,
Authorized,
Expired,
Failed,
Paid,
}
impl From<MolliePaymentStatus> for enums::AttemptStatus {
fn from(item: MolliePaymentStatus) -> Self {
match item {
MolliePaymentStatus::Paid => Self::Charged,
MolliePaymentStatus::Failed => Self::Failure,
MolliePaymentStatus::Pending => Self::Pending,
MolliePaymentStatus::Open => Self::AuthenticationPending,
MolliePaymentStatus::Canceled => Self::Voided,
MolliePaymentStatus::Authorized => Self::Authorized,
MolliePaymentStatus::Expired => Self::Failure,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Link {
href: Url,
#[serde(rename = "type")]
type_: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Links {
#[serde(rename = "self")]
self_: Option<Link>,
checkout: Option<Link>,
dashboard: Option<Link>,
documentation: Option<Link>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardDetails {
pub card_number: Secret<String>,
pub card_holder: Secret<String>,
pub card_expiry_date: Secret<String>,
pub card_cvv: Secret<String>,
}
pub struct MollieAuthType {
pub(super) api_key: Secret<String>,
pub(super) profile_token: Option<Secret<String>>,
}
impl TryFrom<&ConnectorAuthType> for MollieAuthType {
type Error = Error;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
profile_token: None,
}),
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
profile_token: Some(key1.to_owned()),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MollieCardTokenResponse {
card_token: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, MollieCardTokenResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, MollieCardTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::Pending,
payment_method_token: Some(PaymentMethodToken::Token(item.response.card_token.clone())),
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.card_token.expose(),
}),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, MolliePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, MolliePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let url = item
.response
.links
.checkout
.map(|link| RedirectForm::from((link.href, Method::Get)));
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(url),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
#[derive(Default, Debug, Serialize)]
pub struct MollieRefundRequest {
amount: Amount,
description: Option<String>,
metadata: Option<MollieMetadata>,
}
impl<F> TryFrom<&MollieRouterData<&types::RefundsRouterData<F>>> for MollieRefundRequest {
type Error = Error;
fn try_from(
item: &MollieRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let amount = Amount {
currency: item.router_data.request.currency,
value: item.amount.clone(),
};
Ok(Self {
amount,
description: item.router_data.request.reason.to_owned(),
metadata: Some(MollieMetadata {
order_id: item.router_data.request.refund_id.clone(),
}),
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
resource: String,
id: String,
amount: Amount,
settlement_id: Option<String>,
settlement_amount: Option<Amount>,
status: MollieRefundStatus,
description: Option<String>,
metadata: Option<MollieMetadata>,
payment_id: String,
#[serde(rename = "_links")]
links: Links,
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MollieRefundStatus {
Queued,
#[default]
Pending,
Processing,
Refunded,
Failed,
Canceled,
}
impl From<MollieRefundStatus> for enums::RefundStatus {
fn from(item: MollieRefundStatus) -> Self {
match item {
MollieRefundStatus::Queued
| MollieRefundStatus::Pending
| MollieRefundStatus::Processing => Self::Pending,
MollieRefundStatus::Refunded => Self::Success,
MollieRefundStatus::Failed | MollieRefundStatus::Canceled => Self::Failure,
}
}
}
impl<T> TryFrom<RefundsResponseRouterData<T, RefundResponse>> for types::RefundsRouterData<T> {
type Error = Error;
fn try_from(item: RefundsResponseRouterData<T, RefundResponse>) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct MollieErrorResponse {
pub status: u16,
pub title: Option<String>,
pub detail: String,
pub field: Option<String>,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4485
}
|
large_file_6584291409836162841
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs
</path>
<file>
use api_models::{payouts, webhooks};
use common_enums::enums;
use common_utils::pii;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::types::{self, PayoutsRouterData};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use super::{AdyenPlatformRouterData, Error};
use crate::{
connectors::adyen::transformers as adyen,
types::PayoutsResponseRouterData,
utils::{
self, AddressDetailsData, CardData, PayoutFulfillRequestData, PayoutsData as _,
RouterData as _,
},
};
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct AdyenPlatformConnectorMetadataObject {
source_balance_account: Option<Secret<String>>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for AdyenPlatformConnectorMetadataObject {
type Error = Error;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(ConnectorError::InvalidConnectorConfig { config: "metadata" })?;
Ok(metadata)
}
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenTransferRequest {
amount: adyen::Amount,
balance_account_id: Secret<String>,
category: AdyenPayoutMethod,
counterparty: AdyenPayoutMethodDetails,
priority: Option<AdyenPayoutPriority>,
reference: String,
reference_for_beneficiary: String,
description: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenPayoutMethod {
Bank,
Card,
PlatformPayment,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenPayoutMethodDetails {
BankAccount(AdyenBankAccountDetails),
Card(AdyenCardDetails),
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenBankAccountDetails {
account_holder: AdyenAccountHolder,
account_identification: AdyenBankAccountIdentification,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenAccountHolder {
address: Option<AdyenAddress>,
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
full_name: Option<Secret<String>>,
email: Option<pii::Email>,
#[serde(rename = "reference")]
customer_id: Option<String>,
#[serde(rename = "type")]
entity_type: Option<EntityType>,
}
#[serde_with::skip_serializing_none]
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenAddress {
line1: Secret<String>,
line2: Secret<String>,
postal_code: Option<Secret<String>>,
state_or_province: Option<Secret<String>>,
city: String,
country: enums::CountryAlpha2,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AdyenBankAccountIdentification {
#[serde(rename = "type")]
bank_type: String,
#[serde(flatten)]
account_details: AdyenBankAccountIdentificationDetails,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AdyenBankAccountIdentificationDetails {
Sepa(SepaDetails),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SepaDetails {
iban: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenCardDetails {
card_holder: AdyenAccountHolder,
card_identification: AdyenCardIdentification,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum AdyenCardIdentification {
Card(AdyenRawCardIdentification),
Stored(AdyenStoredCardIdentification),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenRawCardIdentification {
#[serde(rename = "number")]
card_number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
issue_number: Option<String>,
start_month: Option<String>,
start_year: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenStoredCardIdentification {
stored_payment_method_id: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenPayoutPriority {
Instant,
Fast,
Regular,
Wire,
CrossBorder,
Internal,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EntityType {
Individual,
Organization,
Unknown,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenTransferResponse {
id: String,
account_holder: AdyenPlatformAccountHolder,
amount: adyen::Amount,
balance_account: AdyenBalanceAccount,
category: AdyenPayoutMethod,
category_data: Option<AdyenCategoryData>,
direction: AdyenTransactionDirection,
reference: String,
reference_for_beneficiary: String,
status: AdyenTransferStatus,
#[serde(rename = "type")]
transaction_type: AdyenTransactionType,
reason: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AdyenPlatformAccountHolder {
description: String,
id: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AdyenCategoryData {
priority: AdyenPayoutPriority,
#[serde(rename = "type")]
category: AdyenPayoutMethod,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AdyenBalanceAccount {
description: String,
id: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AdyenTransactionDirection {
Incoming,
Outgoing,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, strum::Display)]
#[serde(rename_all = "lowercase")]
pub enum AdyenTransferStatus {
Authorised,
Refused,
Error,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenTransactionType {
BankTransfer,
CardTransfer,
InternalTransfer,
Payment,
Refund,
}
impl TryFrom<&hyperswitch_domain_models::address::AddressDetails> for AdyenAddress {
type Error = Error;
fn try_from(
address: &hyperswitch_domain_models::address::AddressDetails,
) -> Result<Self, Self::Error> {
let line1 = address
.get_line1()
.change_context(ConnectorError::MissingRequiredField {
field_name: "billing.address.line1",
})?
.clone();
let line2 = address
.get_line2()
.change_context(ConnectorError::MissingRequiredField {
field_name: "billing.address.line2",
})?
.clone();
Ok(Self {
line1,
line2,
postal_code: address.get_optional_zip(),
state_or_province: address.get_optional_state(),
city: address.get_city()?.to_owned(),
country: address.get_country()?.to_owned(),
})
}
}
impl<F> TryFrom<(&PayoutsRouterData<F>, &payouts::CardPayout)> for AdyenAccountHolder {
type Error = Error;
fn try_from(
(router_data, card): (&PayoutsRouterData<F>, &payouts::CardPayout),
) -> Result<Self, Self::Error> {
let billing_address = router_data.get_optional_billing();
let address = billing_address
.and_then(|billing| billing.address.as_ref().map(|addr| addr.try_into()))
.transpose()?
.ok_or(ConnectorError::MissingRequiredField {
field_name: "address",
})?;
let (first_name, last_name) = if let Some(card_holder_name) = &card.card_holder_name {
let exposed_name = card_holder_name.clone().expose();
let name_parts: Vec<&str> = exposed_name.split_whitespace().collect();
let first_name = name_parts
.first()
.map(|s| Secret::new(s.to_string()))
.ok_or(ConnectorError::MissingRequiredField {
field_name: "card_holder_name.first_name",
})?;
let last_name = if name_parts.len() > 1 {
let remaining_names: Vec<&str> = name_parts.iter().skip(1).copied().collect();
Some(Secret::new(remaining_names.join(" ")))
} else {
return Err(ConnectorError::MissingRequiredField {
field_name: "card_holder_name.last_name",
}
.into());
};
(Some(first_name), last_name)
} else {
return Err(ConnectorError::MissingRequiredField {
field_name: "card_holder_name",
}
.into());
};
let customer_id_reference = match router_data.get_connector_customer_id() {
Ok(connector_customer_id) => connector_customer_id,
Err(_) => {
let customer_id = router_data.get_customer_id()?;
format!(
"{}_{}",
router_data.merchant_id.get_string_repr(),
customer_id.get_string_repr()
)
}
};
Ok(Self {
address: Some(address),
first_name,
last_name,
full_name: None,
email: router_data.get_optional_billing_email(),
customer_id: Some(customer_id_reference),
entity_type: Some(EntityType::from(router_data.request.entity_type)),
})
}
}
impl<F> TryFrom<(&PayoutsRouterData<F>, &payouts::Bank)> for AdyenAccountHolder {
type Error = Error;
fn try_from(
(router_data, _bank): (&PayoutsRouterData<F>, &payouts::Bank),
) -> Result<Self, Self::Error> {
let billing_address = router_data.get_optional_billing();
let address = billing_address
.and_then(|billing| billing.address.as_ref().map(|addr| addr.try_into()))
.transpose()?
.ok_or(ConnectorError::MissingRequiredField {
field_name: "address",
})?;
let full_name = router_data.get_billing_full_name()?;
let customer_id_reference = match router_data.get_connector_customer_id() {
Ok(connector_customer_id) => connector_customer_id,
Err(_) => {
let customer_id = router_data.get_customer_id()?;
format!(
"{}_{}",
router_data.merchant_id.get_string_repr(),
customer_id.get_string_repr()
)
}
};
Ok(Self {
address: Some(address),
first_name: None,
last_name: None,
full_name: Some(full_name),
email: router_data.get_optional_billing_email(),
customer_id: Some(customer_id_reference),
entity_type: Some(EntityType::from(router_data.request.entity_type)),
})
}
}
#[derive(Debug)]
pub struct StoredPaymentCounterparty<'a, F> {
pub item: &'a AdyenPlatformRouterData<&'a PayoutsRouterData<F>>,
pub stored_payment_method_id: String,
}
#[derive(Debug)]
pub struct RawPaymentCounterparty<'a, F> {
pub item: &'a AdyenPlatformRouterData<&'a PayoutsRouterData<F>>,
pub raw_payout_method_data: payouts::PayoutMethodData,
}
impl<F> TryFrom<StoredPaymentCounterparty<'_, F>>
for (AdyenPayoutMethodDetails, Option<AdyenPayoutPriority>)
{
type Error = Error;
fn try_from(stored_payment: StoredPaymentCounterparty<'_, F>) -> Result<Self, Self::Error> {
let request = &stored_payment.item.router_data.request;
let payout_type = request.get_payout_type()?;
match payout_type {
enums::PayoutType::Card => {
let billing_address = stored_payment.item.router_data.get_optional_billing();
let address = billing_address
.and_then(|billing| billing.address.as_ref())
.ok_or(ConnectorError::MissingRequiredField {
field_name: "address",
})?
.try_into()?;
let customer_id_reference =
match stored_payment.item.router_data.get_connector_customer_id() {
Ok(connector_customer_id) => connector_customer_id,
Err(_) => {
let customer_id = stored_payment.item.router_data.get_customer_id()?;
format!(
"{}_{}",
stored_payment
.item
.router_data
.merchant_id
.get_string_repr(),
customer_id.get_string_repr()
)
}
};
let card_holder = AdyenAccountHolder {
address: Some(address),
first_name: stored_payment
.item
.router_data
.get_optional_billing_first_name(),
last_name: stored_payment
.item
.router_data
.get_optional_billing_last_name(),
full_name: stored_payment
.item
.router_data
.get_optional_billing_full_name(),
email: stored_payment.item.router_data.get_optional_billing_email(),
customer_id: Some(customer_id_reference),
entity_type: Some(EntityType::from(request.entity_type)),
};
let card_identification =
AdyenCardIdentification::Stored(AdyenStoredCardIdentification {
stored_payment_method_id: Secret::new(
stored_payment.stored_payment_method_id,
),
});
let counterparty = AdyenPayoutMethodDetails::Card(AdyenCardDetails {
card_holder,
card_identification,
});
Ok((counterparty, None))
}
_ => Err(ConnectorError::NotSupported {
message: "Stored payment method is only supported for card payouts".to_string(),
connector: "Adyenplatform",
}
.into()),
}
}
}
impl<F> TryFrom<RawPaymentCounterparty<'_, F>>
for (AdyenPayoutMethodDetails, Option<AdyenPayoutPriority>)
{
type Error = Error;
fn try_from(raw_payment: RawPaymentCounterparty<'_, F>) -> Result<Self, Self::Error> {
let request = &raw_payment.item.router_data.request;
match raw_payment.raw_payout_method_data {
payouts::PayoutMethodData::Wallet(_) | payouts::PayoutMethodData::BankRedirect(_) => {
Err(ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyenplatform"),
))?
}
payouts::PayoutMethodData::Card(c) => {
let card_holder: AdyenAccountHolder =
(raw_payment.item.router_data, &c).try_into()?;
let card_identification =
AdyenCardIdentification::Card(AdyenRawCardIdentification {
expiry_year: c.get_expiry_year_4_digit(),
card_number: c.card_number,
expiry_month: c.expiry_month,
issue_number: None,
start_month: None,
start_year: None,
});
let counterparty = AdyenPayoutMethodDetails::Card(AdyenCardDetails {
card_holder,
card_identification,
});
Ok((counterparty, None))
}
payouts::PayoutMethodData::Bank(bd) => {
let account_holder: AdyenAccountHolder =
(raw_payment.item.router_data, &bd).try_into()?;
let bank_details = match bd {
payouts::Bank::Sepa(b) => AdyenBankAccountIdentification {
bank_type: "iban".to_string(),
account_details: AdyenBankAccountIdentificationDetails::Sepa(SepaDetails {
iban: b.iban,
}),
},
payouts::Bank::Ach(..) => Err(ConnectorError::NotSupported {
message: "Bank transfer via ACH is not supported".to_string(),
connector: "Adyenplatform",
})?,
payouts::Bank::Bacs(..) => Err(ConnectorError::NotSupported {
message: "Bank transfer via Bacs is not supported".to_string(),
connector: "Adyenplatform",
})?,
payouts::Bank::Pix(..) => Err(ConnectorError::NotSupported {
message: "Bank transfer via Pix is not supported".to_string(),
connector: "Adyenplatform",
})?,
};
let counterparty = AdyenPayoutMethodDetails::BankAccount(AdyenBankAccountDetails {
account_holder,
account_identification: bank_details,
});
let priority = request
.priority
.ok_or(ConnectorError::MissingRequiredField {
field_name: "priority",
})?;
Ok((counterparty, Some(AdyenPayoutPriority::from(priority))))
}
}
}
}
impl<F> TryFrom<&AdyenPlatformRouterData<&PayoutsRouterData<F>>> for AdyenTransferRequest {
type Error = Error;
fn try_from(
item: &AdyenPlatformRouterData<&PayoutsRouterData<F>>,
) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
let stored_payment_method_result =
item.router_data.request.get_connector_transfer_method_id();
let raw_payout_method_result = item.router_data.get_payout_method_data();
let (counterparty, priority) =
if let Ok(stored_payment_method_id) = stored_payment_method_result {
StoredPaymentCounterparty {
item,
stored_payment_method_id,
}
.try_into()?
} else if let Ok(raw_payout_method_data) = raw_payout_method_result {
RawPaymentCounterparty {
item,
raw_payout_method_data,
}
.try_into()?
} else {
return Err(ConnectorError::MissingRequiredField {
field_name: "payout_method_data or stored_payment_method_id",
}
.into());
};
let adyen_connector_metadata_object =
AdyenPlatformConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?;
let balance_account_id = adyen_connector_metadata_object
.source_balance_account
.ok_or(ConnectorError::InvalidConnectorConfig {
config: "metadata.source_balance_account",
})?;
let payout_type = request.get_payout_type()?;
Ok(Self {
amount: adyen::Amount {
value: item.amount,
currency: request.destination_currency,
},
balance_account_id,
category: AdyenPayoutMethod::try_from(payout_type)?,
counterparty,
priority,
reference: item.router_data.connector_request_reference_id.clone(),
reference_for_beneficiary: item.router_data.connector_request_reference_id.clone(),
description: item.router_data.description.clone(),
})
}
}
impl<F> TryFrom<PayoutsResponseRouterData<F, AdyenTransferResponse>> for PayoutsRouterData<F> {
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, AdyenTransferResponse>,
) -> Result<Self, Self::Error> {
let response: AdyenTransferResponse = item.response;
let status = enums::PayoutStatus::from(response.status);
if matches!(status, enums::PayoutStatus::Failed) {
return Ok(Self {
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: response.status.to_string(),
message: if !response.reason.is_empty() {
response.reason
} else {
response.status.to_string()
},
reason: None,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(response.id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
});
}
Ok(Self {
response: Ok(types::PayoutsResponseData {
status: Some(status),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
impl From<AdyenTransferStatus> for enums::PayoutStatus {
fn from(adyen_status: AdyenTransferStatus) -> Self {
match adyen_status {
AdyenTransferStatus::Authorised => Self::Initiated,
AdyenTransferStatus::Error | AdyenTransferStatus::Refused => Self::Failed,
}
}
}
impl From<enums::PayoutEntityType> for EntityType {
fn from(entity: enums::PayoutEntityType) -> Self {
match entity {
enums::PayoutEntityType::Individual
| enums::PayoutEntityType::Personal
| enums::PayoutEntityType::NaturalPerson => Self::Individual,
enums::PayoutEntityType::Company | enums::PayoutEntityType::Business => {
Self::Organization
}
_ => Self::Unknown,
}
}
}
impl From<enums::PayoutSendPriority> for AdyenPayoutPriority {
fn from(entity: enums::PayoutSendPriority) -> Self {
match entity {
enums::PayoutSendPriority::Instant => Self::Instant,
enums::PayoutSendPriority::Fast => Self::Fast,
enums::PayoutSendPriority::Regular => Self::Regular,
enums::PayoutSendPriority::Wire => Self::Wire,
enums::PayoutSendPriority::CrossBorder => Self::CrossBorder,
enums::PayoutSendPriority::Internal => Self::Internal,
}
}
}
impl TryFrom<enums::PayoutType> for AdyenPayoutMethod {
type Error = Error;
fn try_from(payout_type: enums::PayoutType) -> Result<Self, Self::Error> {
match payout_type {
enums::PayoutType::Bank => Ok(Self::Bank),
enums::PayoutType::Card => Ok(Self::Card),
enums::PayoutType::Wallet | enums::PayoutType::BankRedirect => {
Err(report!(ConnectorError::NotSupported {
message: "Bakredirect or wallet payouts".to_string(),
connector: "Adyenplatform",
}))
}
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenplatformIncomingWebhook {
pub data: AdyenplatformIncomingWebhookData,
#[serde(rename = "type")]
pub webhook_type: AdyenplatformWebhookEventType,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenplatformIncomingWebhookData {
pub status: AdyenplatformWebhookStatus,
pub reference: String,
pub tracking: Option<AdyenplatformTrackingData>,
pub category: Option<AdyenPayoutMethod>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenplatformTrackingData {
status: TrackingStatus,
estimated_arrival_time: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum TrackingStatus {
Accepted,
Pending,
Credited,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum AdyenplatformWebhookEventType {
#[serde(rename = "balancePlatform.transfer.created")]
PayoutCreated,
#[serde(rename = "balancePlatform.transfer.updated")]
PayoutUpdated,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenplatformWebhookStatus {
Authorised,
Booked,
Pending,
Failed,
Returned,
Received,
}
pub fn get_adyen_payout_webhook_event(
event_type: AdyenplatformWebhookEventType,
status: AdyenplatformWebhookStatus,
tracking_data: Option<AdyenplatformTrackingData>,
) -> webhooks::IncomingWebhookEvent {
match (event_type, status, tracking_data) {
(AdyenplatformWebhookEventType::PayoutCreated, _, _) => {
webhooks::IncomingWebhookEvent::PayoutCreated
}
(AdyenplatformWebhookEventType::PayoutUpdated, _, Some(tracking_data)) => {
match tracking_data.status {
TrackingStatus::Credited | TrackingStatus::Accepted => {
webhooks::IncomingWebhookEvent::PayoutSuccess
}
TrackingStatus::Pending => webhooks::IncomingWebhookEvent::PayoutProcessing,
}
}
(AdyenplatformWebhookEventType::PayoutUpdated, status, _) => match status {
AdyenplatformWebhookStatus::Authorised | AdyenplatformWebhookStatus::Received => {
webhooks::IncomingWebhookEvent::PayoutCreated
}
AdyenplatformWebhookStatus::Booked | AdyenplatformWebhookStatus::Pending => {
webhooks::IncomingWebhookEvent::PayoutProcessing
}
AdyenplatformWebhookStatus::Failed => webhooks::IncomingWebhookEvent::PayoutFailure,
AdyenplatformWebhookStatus::Returned => webhooks::IncomingWebhookEvent::PayoutReversed,
},
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenTransferErrorResponse {
pub error_code: String,
#[serde(rename = "type")]
pub error_type: String,
pub status: u16,
pub title: String,
pub detail: Option<String>,
pub request_id: Option<String>,
pub invalid_fields: Option<Vec<AdyenInvalidField>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenInvalidField {
pub name: Option<String>,
pub value: Option<String>,
pub message: Option<String>,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5540
}
|
large_file_7332232380438301553
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs
</path>
<file>
use std::collections::HashMap;
use cards::CardNumber;
use common_enums::{enums, Currency};
use common_utils::{pii, request::Method, types::FloatMajorUnit};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{
PaymentsAuthorizeData, PaymentsCaptureData, PaymentsPreProcessingData, ResponseId,
},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsPreProcessingRouterData,
PaymentsSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
get_unimplemented_payment_method_error_message, CardData, PaymentsAuthorizeRequestData,
PaymentsSyncRequestData, RouterData as OtherRouterData,
},
};
//TODO: Fill the struct with respective fields
pub struct XenditRouterData<T> {
pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
#[derive(Serialize, Deserialize, Debug)]
pub enum PaymentMethodType {
CARD,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChannelProperties {
pub success_return_url: String,
pub failure_return_url: String,
pub skip_three_d_secure: bool,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum PaymentMethod {
Card(CardPaymentRequest),
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CardPaymentRequest {
#[serde(rename = "type")]
pub payment_type: PaymentMethodType,
pub card: CardInfo,
pub reusability: TransactionType,
pub reference_id: Secret<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct MandatePaymentRequest {
pub amount: FloatMajorUnit,
pub currency: Currency,
pub capture_method: String,
pub payment_method_id: Secret<String>,
pub channel_properties: ChannelProperties,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct XenditRedirectionResponse {
pub status: PaymentStatus,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct XenditPaymentsCaptureRequest {
pub capture_amount: FloatMajorUnit,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct XenditPaymentsRequest {
pub amount: FloatMajorUnit,
pub currency: Currency,
pub capture_method: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method: Option<PaymentMethod>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_id: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub channel_properties: Option<ChannelProperties>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct XenditSplitRoute {
#[serde(skip_serializing_if = "Option::is_none")]
pub flat_amount: Option<FloatMajorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub percent_amount: Option<i64>,
pub currency: Currency,
pub destination_account_id: String,
pub reference_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct XenditSplitRequest {
pub name: String,
pub description: String,
pub routes: Vec<XenditSplitRoute>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct XenditSplitRequestData {
#[serde(flatten)]
pub split_data: XenditSplitRequest,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct XenditSplitResponse {
id: String,
name: String,
description: String,
routes: Vec<XenditSplitRoute>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CardInfo {
pub channel_properties: ChannelProperties,
pub card_information: CardInformation,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CardInformation {
pub card_number: CardNumber,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cvv: Option<Secret<String>>,
pub cardholder_name: Secret<String>,
pub cardholder_email: pii::Email,
pub cardholder_phone_number: Secret<String>,
}
pub mod auth_headers {
pub const WITH_SPLIT_RULE: &str = "with-split-rule";
pub const FOR_USER_ID: &str = "for-user-id";
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionType {
OneTimeUse,
MultipleUse,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct XenditErrorResponse {
pub error_code: String,
pub message: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentStatus {
Pending,
RequiresAction,
Failed,
Succeeded,
AwaitingCapture,
Verified,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum XenditResponse {
Payment(XenditPaymentResponse),
Webhook(XenditWebhookEvent),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct XenditPaymentResponse {
pub id: String,
pub status: PaymentStatus,
pub actions: Option<Vec<Action>>,
pub payment_method: PaymentMethodInfo,
pub failure_code: Option<String>,
pub reference_id: Secret<String>,
pub amount: FloatMajorUnit,
pub currency: Currency,
}
fn map_payment_response_to_attempt_status(
response: XenditPaymentResponse,
is_auto_capture: bool,
) -> enums::AttemptStatus {
match response.status {
PaymentStatus::Failed => enums::AttemptStatus::Failure,
PaymentStatus::Succeeded | PaymentStatus::Verified => {
if is_auto_capture {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
PaymentStatus::Pending => enums::AttemptStatus::Pending,
PaymentStatus::RequiresAction => enums::AttemptStatus::AuthenticationPending,
PaymentStatus::AwaitingCapture => enums::AttemptStatus::Authorized,
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct XenditCaptureResponse {
pub id: String,
pub status: PaymentStatus,
pub actions: Option<Vec<Action>>,
pub payment_method: PaymentMethodInfo,
pub failure_code: Option<String>,
pub reference_id: Secret<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum MethodType {
Get,
Post,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Action {
pub method: MethodType,
pub url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentMethodInfo {
pub id: Secret<String>,
}
impl TryFrom<XenditRouterData<&PaymentsAuthorizeRouterData>> for XenditPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: XenditRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(card_data) => Ok(Self {
capture_method: match item.router_data.request.is_auto_capture()? {
true => "AUTOMATIC".to_string(),
false => "MANUAL".to_string(),
},
currency: item.router_data.request.currency,
amount: item.amount,
payment_method: Some(PaymentMethod::Card(CardPaymentRequest {
payment_type: PaymentMethodType::CARD,
reference_id: Secret::new(
item.router_data.connector_request_reference_id.clone(),
),
card: CardInfo {
channel_properties: ChannelProperties {
success_return_url: item.router_data.request.get_router_return_url()?,
failure_return_url: item.router_data.request.get_router_return_url()?,
skip_three_d_secure: !item.router_data.is_three_ds(),
},
card_information: CardInformation {
card_number: card_data.card_number.clone(),
expiry_month: card_data.card_exp_month.clone(),
expiry_year: card_data.get_expiry_year_4_digit(),
cvv: if card_data.card_cvc.clone().expose().is_empty() {
None
} else {
Some(card_data.card_cvc.clone())
},
cardholder_name: card_data
.get_cardholder_name()
.or(item.router_data.get_billing_full_name())?,
cardholder_email: item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?,
cardholder_phone_number: item.router_data.get_billing_phone_number()?,
},
},
reusability: match item.router_data.request.is_mandate_payment() {
true => TransactionType::MultipleUse,
false => TransactionType::OneTimeUse,
},
})),
payment_method_id: None,
channel_properties: None,
}),
PaymentMethodData::MandatePayment => Ok(Self {
channel_properties: Some(ChannelProperties {
success_return_url: item.router_data.request.get_router_return_url()?,
failure_return_url: item.router_data.request.get_router_return_url()?,
skip_three_d_secure: true,
}),
capture_method: match item.router_data.request.is_auto_capture()? {
true => "AUTOMATIC".to_string(),
false => "MANUAL".to_string(),
},
currency: item.router_data.request.currency,
amount: item.amount,
payment_method_id: Some(Secret::new(
item.router_data.request.get_connector_mandate_id()?,
)),
payment_method: None,
}),
_ => Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("xendit"),
)
.into()),
}
}
}
impl TryFrom<XenditRouterData<&PaymentsCaptureRouterData>> for XenditPaymentsCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: XenditRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
Ok(Self {
capture_amount: item.amount,
})
}
}
impl<F>
TryFrom<
ResponseRouterData<F, XenditPaymentResponse, PaymentsAuthorizeData, PaymentsResponseData>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
XenditPaymentResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = map_payment_response_to_attempt_status(
item.response.clone(),
item.data.request.is_auto_capture()?,
);
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item
.response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: item
.response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: Some(
item.response
.failure_code
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
),
attempt_status: None,
connector_transaction_id: Some(item.response.id.clone()),
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
let charges = match item.data.request.split_payments.as_ref() {
Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
common_types::payments::XenditSplitRequest::MultipleSplits(_),
)) => item
.data
.response
.as_ref()
.ok()
.and_then(|response| match response {
PaymentsResponseData::TransactionResponse { charges, .. } => {
charges.clone()
}
_ => None,
}),
Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
common_types::payments::XenditSplitRequest::SingleSplit(ref split_data),
)) => {
let charges = common_types::domain::XenditSplitSubMerchantData {
for_user_id: split_data.for_user_id.clone(),
};
Some(
common_types::payments::ConnectorChargeResponseData::XenditSplitPayment(
common_types::payments::XenditChargeResponseData::SingleSplit(charges),
),
)
}
_ => None,
};
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: match item.response.actions {
Some(actions) if !actions.is_empty() => {
actions.first().map_or(Box::new(None), |single_action| {
Box::new(Some(RedirectForm::Form {
endpoint: single_action.url.clone(),
method: match single_action.method {
MethodType::Get => Method::Get,
MethodType::Post => Method::Post,
},
form_fields: HashMap::new(),
}))
})
}
_ => Box::new(None),
},
mandate_reference: match item.data.request.is_mandate_payment() {
true => Box::new(Some(MandateReference {
connector_mandate_id: Some(item.response.payment_method.id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})),
false => Box::new(None),
},
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
item.response.reference_id.peek().to_string(),
),
incremental_authorization_allowed: None,
charges,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl<F>
TryFrom<ResponseRouterData<F, XenditCaptureResponse, PaymentsCaptureData, PaymentsResponseData>>
for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
XenditCaptureResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = match item.response.status {
PaymentStatus::Failed => enums::AttemptStatus::Failure,
PaymentStatus::Succeeded | PaymentStatus::Verified => enums::AttemptStatus::Charged,
PaymentStatus::Pending => enums::AttemptStatus::Pending,
PaymentStatus::RequiresAction => enums::AttemptStatus::AuthenticationPending,
PaymentStatus::AwaitingCapture => enums::AttemptStatus::Authorized,
};
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item
.response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: item
.response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: Some(
item.response
.failure_code
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
item.response.reference_id.peek().to_string(),
),
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl<F>
TryFrom<
ResponseRouterData<F, XenditSplitResponse, PaymentsPreProcessingData, PaymentsResponseData>,
> for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
XenditSplitResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let for_user_id = match item.data.request.split_payments {
Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
common_types::payments::XenditSplitRequest::MultipleSplits(ref split_data),
)) => split_data.for_user_id.clone(),
_ => None,
};
let routes: Vec<common_types::payments::XenditSplitRoute> = item
.response
.routes
.iter()
.map(|route| {
let required_conversion_type = common_utils::types::FloatMajorUnitForConnector;
route
.flat_amount
.map(|amount| {
common_utils::types::AmountConvertor::convert_back(
&required_conversion_type,
amount,
item.data.request.currency.unwrap_or(Currency::USD),
)
.map_err(|_| {
errors::ConnectorError::RequestEncodingFailedWithReason(
"Failed to convert the amount into a major unit".to_owned(),
)
})
})
.transpose()
.map(|flat_amount| common_types::payments::XenditSplitRoute {
flat_amount,
percent_amount: route.percent_amount,
currency: route.currency,
destination_account_id: route.destination_account_id.clone(),
reference_id: route.reference_id.clone(),
})
})
.collect::<Result<Vec<_>, _>>()?;
let charges = common_types::payments::XenditMultipleSplitResponse {
split_rule_id: item.response.id,
for_user_id,
name: item.response.name,
description: item.response.description,
routes,
};
let response = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: Some(
common_types::payments::ConnectorChargeResponseData::XenditSplitPayment(
common_types::payments::XenditChargeResponseData::MultipleSplits(charges),
),
),
};
Ok(Self {
response: Ok(response),
..item.data
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<XenditResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: PaymentsSyncResponseRouterData<XenditResponse>) -> Result<Self, Self::Error> {
match item.response {
XenditResponse::Payment(payment_response) => {
let status = map_payment_response_to_attempt_status(
payment_response.clone(),
item.data.request.is_auto_capture()?,
);
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: payment_response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: payment_response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: Some(
payment_response
.failure_code
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
),
attempt_status: None,
connector_transaction_id: Some(payment_response.id.clone()),
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
XenditResponse::Webhook(webhook_event) => {
let status = match webhook_event.event {
XenditEventType::PaymentSucceeded | XenditEventType::CaptureSucceeded => {
enums::AttemptStatus::Charged
}
XenditEventType::PaymentAwaitingCapture => enums::AttemptStatus::Authorized,
XenditEventType::PaymentFailed | XenditEventType::CaptureFailed => {
enums::AttemptStatus::Failure
}
};
Ok(Self {
status,
..item.data
})
}
}
}
}
impl<T> From<(FloatMajorUnit, T)> for XenditRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub struct XenditAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for XenditAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<&PaymentsPreProcessingRouterData> for XenditSplitRequestData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> {
if let Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
common_types::payments::XenditSplitRequest::MultipleSplits(ref split_data),
)) = item.request.split_payments.clone()
{
let routes: Vec<XenditSplitRoute> = split_data
.routes
.iter()
.map(|route| {
let required_conversion_type = common_utils::types::FloatMajorUnitForConnector;
route
.flat_amount
.map(|amount| {
common_utils::types::AmountConvertor::convert(
&required_conversion_type,
amount,
item.request.currency.unwrap_or(Currency::USD),
)
.map_err(|_| {
errors::ConnectorError::RequestEncodingFailedWithReason(
"Failed to convert the amount into a major unit".to_owned(),
)
})
})
.transpose()
.map(|flat_amount| XenditSplitRoute {
flat_amount,
percent_amount: route.percent_amount,
currency: route.currency,
destination_account_id: route.destination_account_id.clone(),
reference_id: route.reference_id.clone(),
})
})
.collect::<Result<Vec<_>, _>>()?;
let split_data = XenditSplitRequest {
name: split_data.name.clone(),
description: split_data.description.clone(),
routes,
};
Ok(Self { split_data })
} else {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Xendit"),
)
.into())
}
}
}
//TODO: Fill the struct with respective fields
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct XenditRefundRequest {
pub amount: FloatMajorUnit,
pub payment_request_id: String,
pub reason: String,
}
impl<F> TryFrom<&XenditRouterData<&RefundsRouterData<F>>> for XenditRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &XenditRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
payment_request_id: item.router_data.request.connector_transaction_id.clone(),
reason: "REQUESTED_BY_CUSTOMER".to_string(),
})
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundStatus {
RequiresAction,
Succeeded,
Failed,
Pending,
Cancelled,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed | RefundStatus::Cancelled => Self::Failure,
RefundStatus::Pending | RefundStatus::RequiresAction => Self::Pending,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
pub id: String,
pub status: RefundStatus,
pub amount: FloatMajorUnit,
pub currency: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct XenditMetadata {
pub for_user_id: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct XenditWebhookEvent {
pub event: XenditEventType,
pub data: EventDetails,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct EventDetails {
pub id: String,
pub payment_request_id: Option<String>,
pub amount: FloatMajorUnit,
pub currency: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum XenditEventType {
#[serde(rename = "payment.succeeded")]
PaymentSucceeded,
#[serde(rename = "payment.awaiting_capture")]
PaymentAwaitingCapture,
#[serde(rename = "payment.failed")]
PaymentFailed,
#[serde(rename = "capture.succeeded")]
CaptureSucceeded,
#[serde(rename = "capture.failed")]
CaptureFailed,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5995
}
|
large_file_3135988660164471727
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/authipay/transformers.rs
</path>
<file>
use cards;
use common_enums::enums;
use common_utils::types::FloatMajorUnit;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils,
};
// Type definition for router data with amount
pub struct AuthipayRouterData<T> {
pub amount: FloatMajorUnit, // Amount in major units (e.g., dollars instead of cents)
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for AuthipayRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
// Basic request/response structs used across multiple operations
#[derive(Default, Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
total: FloatMajorUnit,
currency: String,
#[serde(skip_serializing_if = "Option::is_none")]
components: Option<AmountComponents>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmountComponents {
subtotal: FloatMajorUnit,
}
#[derive(Default, Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ExpiryDate {
month: Secret<String>,
year: Secret<String>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Card {
number: cards::CardNumber,
security_code: Secret<String>,
expiry_date: ExpiryDate,
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethod {
payment_card: Card,
}
#[derive(Default, Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SplitShipment {
total_count: i32,
final_shipment: bool,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayPaymentsRequest {
request_type: &'static str,
transaction_amount: Amount,
payment_method: PaymentMethod,
// split_shipment: Option<SplitShipment>,
// incremental_flag: Option<bool>,
}
impl TryFrom<&AuthipayRouterData<&PaymentsAuthorizeRouterData>> for AuthipayPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthipayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
// Check if 3DS is being requested - Authipay doesn't support 3DS
if matches!(
item.router_data.auth_type,
enums::AuthenticationType::ThreeDs
) {
return Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authipay"),
)
.into());
}
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let expiry_date = ExpiryDate {
month: req_card.card_exp_month.clone(),
year: req_card.card_exp_year.clone(),
};
let card = Card {
number: req_card.card_number.clone(),
security_code: req_card.card_cvc.clone(),
expiry_date,
};
let payment_method = PaymentMethod { payment_card: card };
let transaction_amount = Amount {
total: item.amount,
currency: item.router_data.request.currency.to_string(),
components: None,
};
// Determine request type based on capture method
let request_type = match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual) => "PaymentCardPreAuthTransaction",
Some(enums::CaptureMethod::Automatic) => "PaymentCardSaleTransaction",
Some(enums::CaptureMethod::SequentialAutomatic) => "PaymentCardSaleTransaction",
Some(enums::CaptureMethod::ManualMultiple)
| Some(enums::CaptureMethod::Scheduled) => {
return Err(errors::ConnectorError::NotSupported {
message: "Capture method not supported by Authipay".to_string(),
connector: "Authipay",
}
.into());
}
None => "PaymentCardSaleTransaction", // Default when not specified
};
let request = Self {
request_type,
transaction_amount,
payment_method,
};
Ok(request)
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authipay"),
)
.into()),
}
}
}
//TODO: Fill the struct with respective fields
// Auth Struct
pub struct AuthipayAuthType {
pub(super) api_key: Secret<String>,
pub(super) api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AuthipayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
api_secret,
..
} => Ok(Self {
api_key: api_key.to_owned(),
api_secret: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// Transaction Status enum (like Fiserv's FiservPaymentStatus)
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum AuthipayTransactionStatus {
Authorized,
Captured,
Voided,
Declined,
Failed,
#[default]
Processing,
}
impl From<AuthipayTransactionStatus> for enums::AttemptStatus {
fn from(item: AuthipayTransactionStatus) -> Self {
match item {
AuthipayTransactionStatus::Captured => Self::Charged,
AuthipayTransactionStatus::Declined | AuthipayTransactionStatus::Failed => {
Self::Failure
}
AuthipayTransactionStatus::Processing => Self::Pending,
AuthipayTransactionStatus::Authorized => Self::Authorized,
AuthipayTransactionStatus::Voided => Self::Voided,
}
}
}
// Transaction Processing Details (like Fiserv's TransactionProcessingDetails)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayTransactionProcessingDetails {
pub order_id: String,
pub transaction_id: String,
}
// Gateway Response (like Fiserv's GatewayResponse)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayGatewayResponse {
pub transaction_state: AuthipayTransactionStatus,
pub transaction_processing_details: AuthipayTransactionProcessingDetails,
}
// Payment Receipt (like Fiserv's PaymentReceipt)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayPaymentReceipt {
pub approved_amount: Amount,
pub processor_response_details: Option<Processor>,
}
// Main Response (like Fiserv's FiservPaymentsResponse) - but flat for JSON deserialization
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayPaymentsResponse {
#[serde(rename = "type")]
response_type: Option<String>,
client_request_id: String,
api_trace_id: String,
ipg_transaction_id: String,
order_id: String,
transaction_type: String,
payment_token: Option<PaymentToken>,
transaction_origin: Option<String>,
payment_method_details: Option<PaymentMethodDetails>,
country: Option<String>,
terminal_id: Option<String>,
merchant_id: Option<String>,
transaction_time: i64,
approved_amount: Amount,
transaction_amount: Amount,
// For payment transactions (SALE)
transaction_status: Option<String>,
// For refund transactions (RETURN)
transaction_result: Option<String>,
transaction_state: Option<String>,
approval_code: String,
scheme_transaction_id: Option<String>,
processor: Processor,
}
impl AuthipayPaymentsResponse {
/// Get gateway response (like Fiserv's gateway_response)
pub fn gateway_response(&self) -> AuthipayGatewayResponse {
AuthipayGatewayResponse {
transaction_state: self.get_transaction_status(),
transaction_processing_details: AuthipayTransactionProcessingDetails {
order_id: self.order_id.clone(),
transaction_id: self.ipg_transaction_id.clone(),
},
}
}
/// Get payment receipt (like Fiserv's payment_receipt)
pub fn payment_receipt(&self) -> AuthipayPaymentReceipt {
AuthipayPaymentReceipt {
approved_amount: self.approved_amount.clone(),
processor_response_details: Some(self.processor.clone()),
}
}
/// Determine the transaction status based on transaction type and various status fields (like Fiserv)
fn get_transaction_status(&self) -> AuthipayTransactionStatus {
match self.transaction_type.as_str() {
"RETURN" => {
// Refund transaction - use transaction_result
match self.transaction_result.as_deref() {
Some("APPROVED") => AuthipayTransactionStatus::Captured,
Some("DECLINED") | Some("FAILED") => AuthipayTransactionStatus::Failed,
_ => AuthipayTransactionStatus::Processing,
}
}
"VOID" => {
// Void transaction - use transaction_result, fallback to transaction_state
match self.transaction_result.as_deref() {
Some("APPROVED") => AuthipayTransactionStatus::Voided,
Some("DECLINED") | Some("FAILED") => AuthipayTransactionStatus::Failed,
Some("PENDING") | Some("PROCESSING") => AuthipayTransactionStatus::Processing,
_ => {
// Fallback to transaction_state for void operations
match self.transaction_state.as_deref() {
Some("VOIDED") => AuthipayTransactionStatus::Voided,
Some("FAILED") | Some("DECLINED") => AuthipayTransactionStatus::Failed,
_ => AuthipayTransactionStatus::Voided, // Default assumption for void requests
}
}
}
}
_ => {
// Payment transaction - prioritize transaction_state over transaction_status
match self.transaction_state.as_deref() {
Some("AUTHORIZED") => AuthipayTransactionStatus::Authorized,
Some("CAPTURED") => AuthipayTransactionStatus::Captured,
Some("VOIDED") => AuthipayTransactionStatus::Voided,
Some("DECLINED") | Some("FAILED") => AuthipayTransactionStatus::Failed,
_ => {
// Fallback to transaction_status with transaction_type context
match (
self.transaction_type.as_str(),
self.transaction_status.as_deref(),
) {
// For PREAUTH transactions, "APPROVED" means authorized and awaiting capture
("PREAUTH", Some("APPROVED")) => AuthipayTransactionStatus::Authorized,
// For POSTAUTH transactions, "APPROVED" means successfully captured
("POSTAUTH", Some("APPROVED")) => AuthipayTransactionStatus::Captured,
// For SALE transactions, "APPROVED" means completed payment
("SALE", Some("APPROVED")) => AuthipayTransactionStatus::Captured,
// For VOID transactions, "APPROVED" means successfully voided
("VOID", Some("APPROVED")) => AuthipayTransactionStatus::Voided,
// Generic status mappings for other cases
(_, Some("APPROVED")) => AuthipayTransactionStatus::Captured,
(_, Some("AUTHORIZED")) => AuthipayTransactionStatus::Authorized,
(_, Some("DECLINED") | Some("FAILED")) => {
AuthipayTransactionStatus::Failed
}
_ => AuthipayTransactionStatus::Processing,
}
}
}
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentToken {
reusable: Option<bool>,
decline_duplicates: Option<bool>,
brand: Option<String>,
#[serde(rename = "type")]
token_type: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethodDetails {
payment_card: Option<PaymentCardDetails>,
payment_method_type: Option<String>,
payment_method_brand: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentCardDetails {
expiry_date: ExpiryDate,
bin: String,
last4: String,
brand: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Processor {
reference_number: Option<String>,
authorization_code: Option<String>,
response_code: String,
response_message: String,
avs_response: Option<AvsResponse>,
security_code_response: Option<String>,
tax_refund_data: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AvsResponse {
street_match: Option<String>,
postal_code_match: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, AuthipayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AuthipayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
// Get gateway response (like Fiserv pattern)
let gateway_resp = item.response.gateway_response();
// Store order_id in connector_metadata for void operations (like Fiserv)
let mut metadata = std::collections::HashMap::new();
metadata.insert(
"order_id".to_string(),
serde_json::Value::String(gateway_resp.transaction_processing_details.order_id.clone()),
);
let connector_metadata = Some(serde_json::Value::Object(serde_json::Map::from_iter(
metadata,
)));
Ok(Self {
status: enums::AttemptStatus::from(gateway_resp.transaction_state.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
gateway_resp
.transaction_processing_details
.transaction_id
.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(
gateway_resp.transaction_processing_details.order_id.clone(),
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// Type definition for CaptureRequest
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayCaptureRequest {
request_type: &'static str,
transaction_amount: Amount,
}
impl TryFrom<&AuthipayRouterData<&PaymentsCaptureRouterData>> for AuthipayCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthipayRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
request_type: "PostAuthTransaction",
transaction_amount: Amount {
total: item.amount,
currency: item.router_data.request.currency.to_string(),
components: None,
},
})
}
}
// Type definition for VoidRequest
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayVoidRequest {
request_type: &'static str,
}
impl TryFrom<&AuthipayRouterData<&PaymentsCancelRouterData>> for AuthipayVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
_item: &AuthipayRouterData<&PaymentsCancelRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
request_type: "VoidTransaction",
})
}
}
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayRefundRequest {
request_type: &'static str,
transaction_amount: Amount,
}
impl<F> TryFrom<&AuthipayRouterData<&RefundsRouterData<F>>> for AuthipayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AuthipayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
request_type: "ReturnTransaction",
transaction_amount: Amount {
total: item.amount.to_owned(),
currency: item.router_data.request.currency.to_string(),
components: None,
},
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
// Reusing the payments response structure for refunds
// because Authipay uses the same endpoint and response format
pub type RefundResponse = AuthipayPaymentsResponse;
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = if item.response.transaction_type == "RETURN" {
match item.response.transaction_result.as_deref() {
Some("APPROVED") => RefundStatus::Succeeded,
Some("DECLINED") | Some("FAILED") => RefundStatus::Failed,
_ => RefundStatus::Processing,
}
} else {
RefundStatus::Processing
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.ipg_transaction_id.to_string(),
refund_status: enums::RefundStatus::from(refund_status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = if item.response.transaction_type == "RETURN" {
match item.response.transaction_result.as_deref() {
Some("APPROVED") => RefundStatus::Succeeded,
Some("DECLINED") | Some("FAILED") => RefundStatus::Failed,
_ => RefundStatus::Processing,
}
} else {
RefundStatus::Processing
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.ipg_transaction_id.to_string(),
refund_status: enums::RefundStatus::from(refund_status),
}),
..item.data
})
}
}
// Error Response structs
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorDetailItem {
pub field: String,
pub message: String,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorDetails {
pub code: Option<String>,
pub message: String,
pub details: Option<Vec<ErrorDetailItem>>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayErrorResponse {
pub client_request_id: Option<String>,
pub api_trace_id: Option<String>,
pub response_type: Option<String>,
#[serde(rename = "type")]
pub response_object_type: Option<String>,
pub error: ErrorDetails,
pub decline_reason_code: Option<String>,
}
impl From<&AuthipayErrorResponse> for ErrorResponse {
fn from(item: &AuthipayErrorResponse) -> Self {
Self {
status_code: 500, // Default to Internal Server Error, will be overridden by actual HTTP status
code: item.error.code.clone().unwrap_or_default(),
message: item.error.message.clone(),
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/authipay/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4572
}
|
large_file_4246523894633170534
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
</path>
<file>
use std::collections::HashMap;
use api_models::payments::{QrCodeInformation, VoucherNextStepData};
use common_enums::{enums, AttemptStatus};
use common_utils::{
errors::CustomResult,
ext_traits::{ByteSliceExt, Encode},
id_type,
request::Method,
types::{AmountConvertor, FloatMajorUnit, StringMajorUnit, StringMajorUnitForConnector},
};
use crc::{Algorithm, Crc};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankTransferData, PaymentMethodData, VoucherData},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use time::OffsetDateTime;
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self as connector_utils, QrImage, RouterData as _},
};
const CRC_16_CCITT_FALSE: Algorithm<u16> = Algorithm {
width: 16,
poly: 0x1021,
init: 0xFFFF,
refin: false,
refout: false,
xorout: 0x0000,
check: 0x29B1,
residue: 0x0000,
};
type Error = error_stack::Report<errors::ConnectorError>;
pub struct SantanderRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for SantanderRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SantanderMetadataObject {
pub pix_key: Secret<String>,
pub expiration_time: i32,
pub cpf: Secret<String>,
pub merchant_city: String,
pub merchant_name: String,
pub workspace_id: String,
pub covenant_code: String, // max_size : 9
}
impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for SantanderMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
meta_data: &Option<common_utils::pii::SecretSerdeValue>,
) -> Result<Self, Self::Error> {
let metadata = connector_utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
pub fn format_emv_field(id: &str, value: &str) -> String {
format!("{id}{:02}{value}", value.len())
}
pub fn generate_emv_string(
payload_url: &str,
merchant_name: &str,
merchant_city: &str,
amount: Option<&str>,
txid: Option<&str>,
) -> String {
let mut emv = String::new();
// 00: Payload Format Indicator
emv += &format_emv_field("00", "01");
// 01: Point of Initiation Method (dynamic)
emv += &format_emv_field("01", "12");
// 26: Merchant Account Info
let gui = format_emv_field("00", "br.gov.bcb.pix");
let url = format_emv_field("25", payload_url);
let merchant_account_info = format_emv_field("26", &(gui + &url));
emv += &merchant_account_info;
// 52: Merchant Category Code (0000)
emv += &format_emv_field("52", "0000");
// 53: Currency Code (986 for BRL)
emv += &format_emv_field("53", "986");
// 54: Amount (optional)
if let Some(amount) = amount {
emv += &format_emv_field("54", amount);
}
// 58: Country Code (BR)
emv += &format_emv_field("58", "BR");
// 59: Merchant Name
emv += &format_emv_field("59", merchant_name);
// 60: Merchant City
emv += &format_emv_field("60", merchant_city);
// 62: Additional Data Field Template (optional TXID)
if let Some(txid) = txid {
let reference = format_emv_field("05", txid);
emv += &format_emv_field("62", &reference);
}
// Placeholder for CRC (we need to calculate this last)
emv += "6304";
// Compute CRC16-CCITT (False) checksum
let crc = Crc::<u16>::new(&CRC_16_CCITT_FALSE);
let checksum = crc.checksum(emv.as_bytes());
emv += &format!("{checksum:04X}");
emv
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SantanderAuthUpdateResponse {
#[serde(rename = "camelCase")]
pub refresh_url: String,
pub token_type: String,
pub client_id: String,
pub access_token: Secret<String>,
pub scopes: String,
pub expires_in: i64,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct SantanderCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SantanderPSyncBoletoRequest {
payer_document_number: Secret<i64>,
}
pub struct SantanderAuthType {
pub(super) _api_key: Secret<String>,
pub(super) _key1: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for SantanderAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
_api_key: api_key.to_owned(),
_key1: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, SantanderAuthUpdateResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SantanderAuthUpdateResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
impl TryFrom<&SantanderRouterData<&PaymentsAuthorizeRouterData>> for SantanderPaymentRequest {
type Error = Error;
fn try_from(
value: &SantanderRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if value.router_data.request.capture_method != Some(enums::CaptureMethod::Automatic) {
return Err(errors::ConnectorError::FlowNotSupported {
flow: format!("{:?}", value.router_data.request.capture_method),
connector: "Santander".to_string(),
}
.into());
}
match value.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankTransfer(ref bank_transfer_data) => {
Self::try_from((value, bank_transfer_data.as_ref()))
}
PaymentMethodData::Voucher(ref voucher_data) => Self::try_from((value, voucher_data)),
_ => Err(errors::ConnectorError::NotImplemented(
crate::utils::get_unimplemented_payment_method_error_message("Santander"),
))?,
}
}
}
impl TryFrom<&SantanderRouterData<&PaymentsSyncRouterData>> for SantanderPSyncBoletoRequest {
type Error = Error;
fn try_from(value: &SantanderRouterData<&PaymentsSyncRouterData>) -> Result<Self, Self::Error> {
let payer_document_number: i64 = value
.router_data
.connector_request_reference_id
.parse()
.map_err(|_| errors::ConnectorError::ParsingFailed)?;
Ok(Self {
payer_document_number: Secret::new(payer_document_number),
})
}
}
impl
TryFrom<(
&SantanderRouterData<&PaymentsAuthorizeRouterData>,
&VoucherData,
)> for SantanderPaymentRequest
{
type Error = Error;
fn try_from(
value: (
&SantanderRouterData<&PaymentsAuthorizeRouterData>,
&VoucherData,
),
) -> Result<Self, Self::Error> {
let santander_mca_metadata =
SantanderMetadataObject::try_from(&value.0.router_data.connector_meta_data)?;
let voucher_data = match &value.0.router_data.request.payment_method_data {
PaymentMethodData::Voucher(VoucherData::Boleto(boleto_data)) => boleto_data,
_ => {
return Err(errors::ConnectorError::NotImplemented(
crate::utils::get_unimplemented_payment_method_error_message("Santander"),
)
.into());
}
};
let nsu_code = if value
.0
.router_data
.is_payment_id_from_merchant
.unwrap_or(false)
&& value.0.router_data.payment_id.len() > 20
{
return Err(errors::ConnectorError::MaxFieldLengthViolated {
connector: "Santander".to_string(),
field_name: "payment_id".to_string(),
max_length: 20,
received_length: value.0.router_data.payment_id.len(),
}
.into());
} else {
value.0.router_data.payment_id.clone()
};
Ok(Self::Boleto(Box::new(SantanderBoletoPaymentRequest {
environment: Environment::from(router_env::env::which()),
nsu_code,
nsu_date: OffsetDateTime::now_utc()
.date()
.format(&time::macros::format_description!("[year]-[month]-[day]"))
.change_context(errors::ConnectorError::DateFormattingFailed)?,
covenant_code: santander_mca_metadata.covenant_code.clone(),
bank_number: voucher_data.bank_number.clone().ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "document_type",
}
})?, // size: 13
client_number: Some(value.0.router_data.get_customer_id()?),
due_date: voucher_data.due_date.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "due_date",
},
)?,
issue_date: OffsetDateTime::now_utc()
.date()
.format(&time::macros::format_description!("[year]-[month]-[day]"))
.change_context(errors::ConnectorError::DateFormattingFailed)?,
currency: Some(value.0.router_data.request.currency),
nominal_value: value.0.amount.to_owned(),
participant_code: value
.0
.router_data
.request
.merchant_order_reference_id
.clone(),
payer: Payer {
name: value.0.router_data.get_billing_full_name()?,
document_type: voucher_data.document_type.ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "document_type",
}
})?,
document_number: voucher_data.social_security_number.clone(),
address: Secret::new(
[
value.0.router_data.get_billing_line1()?,
value.0.router_data.get_billing_line2()?,
]
.map(|s| s.expose())
.join(" "),
),
neighborhood: value.0.router_data.get_billing_line1()?,
city: value.0.router_data.get_billing_city()?,
state: value.0.router_data.get_billing_state()?,
zipcode: value.0.router_data.get_billing_zip()?,
},
beneficiary: None,
document_kind: BoletoDocumentKind::BillProposal, // to change
discount: Some(Discount {
discount_type: DiscountType::Free,
discount_one: None,
discount_two: None,
discount_three: None,
}),
fine_percentage: voucher_data.fine_percentage.clone(),
fine_quantity_days: voucher_data.fine_quantity_days.clone(),
interest_percentage: voucher_data.interest_percentage.clone(),
deduction_value: None,
protest_type: None,
protest_quantity_days: None,
write_off_quantity_days: voucher_data.write_off_quantity_days.clone(),
payment_type: PaymentType::Registration,
parcels_quantity: None,
value_type: None,
min_value_or_percentage: None,
max_value_or_percentage: None,
iof_percentage: None,
sharing: None,
key: None,
tx_id: None,
messages: voucher_data.messages.clone(),
})))
}
}
impl
TryFrom<(
&SantanderRouterData<&PaymentsAuthorizeRouterData>,
&BankTransferData,
)> for SantanderPaymentRequest
{
type Error = Error;
fn try_from(
value: (
&SantanderRouterData<&PaymentsAuthorizeRouterData>,
&BankTransferData,
),
) -> Result<Self, Self::Error> {
let santander_mca_metadata =
SantanderMetadataObject::try_from(&value.0.router_data.connector_meta_data)?;
let debtor = Some(SantanderDebtor {
cpf: santander_mca_metadata.cpf.clone(),
name: value.0.router_data.get_billing_full_name()?,
});
Ok(Self::PixQR(Box::new(SantanderPixQRPaymentRequest {
calender: SantanderCalendar {
creation: OffsetDateTime::now_utc()
.date()
.format(&time::macros::format_description!("[year]-[month]-[day]"))
.change_context(errors::ConnectorError::DateFormattingFailed)?,
expiration: santander_mca_metadata.expiration_time,
},
debtor,
value: SantanderValue {
original: value.0.amount.to_owned(),
},
key: santander_mca_metadata.pix_key.clone(),
request_payer: value.0.router_data.request.statement_descriptor.clone(),
additional_info: None,
})))
}
}
#[derive(Debug, Serialize)]
pub enum SantanderPaymentRequest {
PixQR(Box<SantanderPixQRPaymentRequest>),
Boleto(Box<SantanderBoletoPaymentRequest>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Discount {
#[serde(rename = "type")]
pub discount_type: DiscountType,
pub discount_one: Option<DiscountObject>,
pub discount_two: Option<DiscountObject>,
pub discount_three: Option<DiscountObject>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SantanderBoletoPaymentRequest {
pub environment: Environment,
pub nsu_code: String,
pub nsu_date: String,
pub covenant_code: String,
pub bank_number: Secret<String>,
pub client_number: Option<id_type::CustomerId>,
pub due_date: String,
pub issue_date: String,
pub currency: Option<enums::Currency>,
pub nominal_value: StringMajorUnit,
pub participant_code: Option<String>,
pub payer: Payer,
pub beneficiary: Option<Beneficiary>,
pub document_kind: BoletoDocumentKind,
pub discount: Option<Discount>,
pub fine_percentage: Option<String>,
pub fine_quantity_days: Option<String>,
pub interest_percentage: Option<String>,
pub deduction_value: Option<FloatMajorUnit>,
pub protest_type: Option<ProtestType>,
pub protest_quantity_days: Option<i64>,
pub write_off_quantity_days: Option<String>,
pub payment_type: PaymentType,
pub parcels_quantity: Option<i64>,
pub value_type: Option<String>,
pub min_value_or_percentage: Option<f64>,
pub max_value_or_percentage: Option<f64>,
pub iof_percentage: Option<f64>,
pub sharing: Option<Sharing>,
pub key: Option<Key>,
pub tx_id: Option<String>,
pub messages: Option<Vec<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Payer {
pub name: Secret<String>,
pub document_type: enums::DocumentKind,
pub document_number: Option<Secret<String>>,
pub address: Secret<String>,
pub neighborhood: Secret<String>,
pub city: String,
pub state: Secret<String>,
pub zipcode: Secret<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Beneficiary {
pub name: Option<Secret<String>>,
pub document_type: Option<enums::DocumentKind>,
pub document_number: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Environment {
#[serde(rename = "Teste")]
Sandbox,
#[serde(rename = "Producao")]
Production,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum SantanderDocumentKind {
Cpf,
Cnpj,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BoletoDocumentKind {
#[serde(rename = "DUPLICATA_MERCANTIL")]
DuplicateMercantil,
#[serde(rename = "DUPLICATA_SERVICO")]
DuplicateService,
#[serde(rename = "NOTA_PROMISSORIA")]
PromissoryNote,
#[serde(rename = "NOTA_PROMISSORIA_RURAL")]
RuralPromissoryNote,
#[serde(rename = "RECIBO")]
Receipt,
#[serde(rename = "APOLICE_SEGURO")]
InsurancePolicy,
#[serde(rename = "BOLETO_CARTAO_CREDITO")]
BillCreditCard,
#[serde(rename = "BOLETO_PROPOSTA")]
BillProposal,
#[serde(rename = "BOLETO_DEPOSITO_APORTE")]
BoletoDepositoAponte,
#[serde(rename = "CHEQUE")]
Check,
#[serde(rename = "NOTA_PROMISSORIA_DIRETA")]
DirectPromissoryNote,
#[serde(rename = "OUTROS")]
Others,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DiscountType {
#[serde(rename = "ISENTO")]
Free,
#[serde(rename = "VALOR_DATA_FIXA")]
FixedDateValue,
#[serde(rename = "VALOR_DIA_CORRIDO")]
ValueDayConductor,
#[serde(rename = "VALOR_DIA_UTIL")]
ValueWorthDay,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct DiscountObject {
pub value: f64,
pub limit_date: String, // YYYY-MM-DD
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ProtestType {
#[serde(rename = "SEM_PROTESTO")]
WithoutProtest,
#[serde(rename = "DIAS_CORRIDOS")]
DaysConducted,
#[serde(rename = "DIAS_UTEIS")]
WorkingDays,
#[serde(rename = "CADASTRO_CONVENIO")]
RegistrationAgreement,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaymentType {
#[serde(rename = "REGISTRO")]
Registration,
#[serde(rename = "DIVERGENTE")]
Divergent,
#[serde(rename = "PARCIAL")]
Partial,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Sharing {
pub code: String,
pub value: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Key {
#[serde(rename = "type")]
pub key_type: Option<String>,
pub dict_key: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SantanderPixQRCodeRequest {
#[serde(rename = "calendario")]
pub calender: SantanderCalendar,
#[serde(rename = "devedor")]
pub debtor: SantanderDebtor,
#[serde(rename = "valor")]
pub value: SantanderValue,
#[serde(rename = "chave")]
pub key: Secret<String>,
#[serde(rename = "solicitacaoPagador")]
pub request_payer: Option<String>,
#[serde(rename = "infoAdicionais")]
pub additional_info: Option<Vec<SantanderAdditionalInfo>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SantanderPixQRPaymentRequest {
#[serde(rename = "calendario")]
pub calender: SantanderCalendar,
#[serde(rename = "devedor")]
pub debtor: Option<SantanderDebtor>,
#[serde(rename = "valor")]
pub value: SantanderValue,
#[serde(rename = "chave")]
pub key: Secret<String>,
#[serde(rename = "solicitacaoPagador")]
pub request_payer: Option<String>,
#[serde(rename = "infoAdicionais")]
pub additional_info: Option<Vec<SantanderAdditionalInfo>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SantanderDebtor {
pub cpf: Secret<String>,
#[serde(rename = "nome")]
pub name: Secret<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SantanderValue {
pub original: StringMajorUnit,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SantanderAdditionalInfo {
#[serde(rename = "nome")]
pub name: String,
#[serde(rename = "valor")]
pub value: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SantanderPaymentStatus {
Active,
Completed,
RemovedByReceivingUser,
RemovedByPSP,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SantanderVoidStatus {
RemovedByReceivingUser,
}
impl From<SantanderPaymentStatus> for AttemptStatus {
fn from(item: SantanderPaymentStatus) -> Self {
match item {
SantanderPaymentStatus::Active => Self::Authorizing,
SantanderPaymentStatus::Completed => Self::Charged,
SantanderPaymentStatus::RemovedByReceivingUser => Self::Voided,
SantanderPaymentStatus::RemovedByPSP => Self::Failure,
}
}
}
impl From<router_env::env::Env> for Environment {
fn from(item: router_env::env::Env) -> Self {
match item {
router_env::env::Env::Sandbox | router_env::env::Env::Development => Self::Sandbox,
router_env::env::Env::Production => Self::Production,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SantanderPaymentsResponse {
PixQRCode(Box<SantanderPixQRCodePaymentsResponse>),
Boleto(Box<SantanderBoletoPaymentsResponse>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SantanderBoletoPaymentsResponse {
pub environment: Environment,
pub nsu_code: String,
pub nsu_date: String,
pub covenant_code: String,
pub bank_number: String,
pub client_number: Option<id_type::CustomerId>,
pub due_date: String,
pub issue_date: String,
pub participant_code: Option<String>,
pub nominal_value: StringMajorUnit,
pub payer: Payer,
pub beneficiary: Option<Beneficiary>,
pub document_kind: BoletoDocumentKind,
pub discount: Option<Discount>,
pub fine_percentage: Option<String>,
pub fine_quantity_days: Option<String>,
pub interest_percentage: Option<String>,
pub deduction_value: Option<FloatMajorUnit>,
pub protest_type: Option<ProtestType>,
pub protest_quantity_days: Option<i64>,
pub write_off_quantity_days: Option<String>,
pub payment_type: PaymentType,
pub parcels_quantity: Option<i64>,
pub value_type: Option<String>,
pub min_value_or_percentage: Option<f64>,
pub max_value_or_percentage: Option<f64>,
pub iof_percentage: Option<f64>,
pub sharing: Option<Sharing>,
pub key: Option<Key>,
pub tx_id: Option<String>,
pub messages: Option<Vec<String>>,
pub barcode: Option<String>,
pub digitable_line: Option<Secret<String>>,
pub entry_date: Option<String>,
pub qr_code_pix: Option<String>,
pub qr_code_url: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SantanderPixQRCodePaymentsResponse {
pub status: SantanderPaymentStatus,
#[serde(rename = "calendario")]
pub calendar: SantanderCalendar,
#[serde(rename = "txid")]
pub transaction_id: String,
#[serde(rename = "revisao")]
pub revision: i32,
#[serde(rename = "devedor")]
pub debtor: Option<SantanderDebtor>,
pub location: Option<String>,
#[serde(rename = "valor")]
pub value: SantanderValue,
#[serde(rename = "chave")]
pub key: Secret<String>,
#[serde(rename = "solicitacaoPagador")]
pub request_payer: Option<String>,
#[serde(rename = "infoAdicionais")]
pub additional_info: Option<Vec<SantanderAdditionalInfo>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SantanderPixVoidResponse {
#[serde(rename = "calendario")]
pub calendar: SantanderCalendar,
#[serde(rename = "txid")]
pub transaction_id: String,
#[serde(rename = "revisao")]
pub revision: i32,
#[serde(rename = "devedor")]
pub debtor: Option<SantanderDebtor>,
pub location: Option<String>,
pub status: SantanderPaymentStatus,
#[serde(rename = "valor")]
pub value: SantanderValue,
#[serde(rename = "chave")]
pub key: Secret<String>,
#[serde(rename = "solicitacaoPagador")]
pub request_payer: Option<String>,
#[serde(rename = "infoAdicionais")]
pub additional_info: Option<Vec<SantanderAdditionalInfo>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SantanderCalendar {
#[serde(rename = "calendario")]
pub creation: String,
#[serde(rename = "expiracao")]
pub expiration: i32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SantanderPaymentsSyncResponse {
PixQRCode(Box<SantanderPixPSyncResponse>),
Boleto(Box<SantanderBoletoPSyncResponse>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SantanderBoletoPSyncResponse {
pub link: Option<Url>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SantanderPixPSyncResponse {
#[serde(flatten)]
pub base: SantanderPixQRCodePaymentsResponse,
pub pix: Vec<SantanderPix>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SantanderPix {
pub end_to_end_id: Secret<String>,
#[serde(rename = "txid")]
pub transaction_id: Secret<String>,
#[serde(rename = "valor")]
pub value: String,
#[serde(rename = "horario")]
pub time: String,
#[serde(rename = "infoPagador")]
pub info_payer: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SantanderPaymentsCancelRequest {
pub status: Option<SantanderVoidStatus>,
}
impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SantanderPaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response = item.response.clone();
match response {
SantanderPaymentsSyncResponse::PixQRCode(pix_data) => {
let attempt_status = AttemptStatus::from(pix_data.base.status.clone());
match attempt_status {
AttemptStatus::Failure => {
let response = Err(get_error_response(
Box::new(pix_data.base),
item.http_code,
attempt_status,
));
Ok(Self {
response,
..item.data
})
}
_ => {
let connector_metadata = pix_data.pix.first().map(|pix| {
serde_json::json!({
"end_to_end_id": pix.end_to_end_id.clone().expose()
})
});
Ok(Self {
status: AttemptStatus::from(pix_data.base.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
pix_data.base.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
}
SantanderPaymentsSyncResponse::Boleto(boleto_data) => {
let redirection_data = boleto_data.link.clone().map(|url| RedirectForm::Form {
endpoint: url.to_string(),
method: Method::Get,
form_fields: HashMap::new(),
});
Ok(Self {
status: AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
}
}
pub fn get_error_response(
pix_data: Box<SantanderPixQRCodePaymentsResponse>,
status_code: u16,
attempt_status: AttemptStatus,
) -> ErrorResponse {
ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: None,
status_code,
attempt_status: Some(attempt_status),
connector_transaction_id: Some(pix_data.transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SantanderPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response = item.response.clone();
match response {
SantanderPaymentsResponse::PixQRCode(pix_data) => {
let attempt_status = AttemptStatus::from(pix_data.status.clone());
match attempt_status {
AttemptStatus::Failure => {
let response = Err(get_error_response(
Box::new(*pix_data),
item.http_code,
attempt_status,
));
Ok(Self {
response,
..item.data
})
}
_ => Ok(Self {
status: AttemptStatus::from(pix_data.status.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
pix_data.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: get_qr_code_data(&item, &pix_data)?,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
}
}
SantanderPaymentsResponse::Boleto(boleto_data) => {
let voucher_data = VoucherNextStepData {
expires_at: None,
digitable_line: boleto_data.digitable_line.clone(),
reference: boleto_data.barcode.ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "barcode",
},
)?,
entry_date: boleto_data.entry_date,
download_url: None,
instructions_url: None,
};
let connector_metadata = Some(voucher_data.encode_to_value())
.transpose()
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let resource_id = match boleto_data.tx_id {
Some(tx_id) => ResponseId::ConnectorTransactionId(tx_id),
None => ResponseId::NoResponseId,
};
let connector_response_reference_id = Some(
boleto_data
.digitable_line
.as_ref()
.map(|s| s.peek().to_owned())
.clone()
.or_else(|| {
boleto_data.beneficiary.as_ref().map(|beneficiary| {
format!(
"{}.{:?}",
boleto_data.bank_number,
beneficiary.document_number.clone()
)
})
})
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "beneficiary.document_number",
})?,
);
Ok(Self {
status: AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, SantanderPixVoidResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SantanderPixVoidResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response = item.response.clone();
Ok(Self {
status: AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.transaction_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: *Box::new(None),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for SantanderPaymentsCancelRequest {
type Error = Error;
fn try_from(_item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Ok(Self {
status: Some(SantanderVoidStatus::RemovedByReceivingUser),
})
}
}
fn get_qr_code_data<F, T>(
item: &ResponseRouterData<F, SantanderPaymentsResponse, T, PaymentsResponseData>,
pix_data: &SantanderPixQRCodePaymentsResponse,
) -> CustomResult<Option<Value>, errors::ConnectorError> {
let santander_mca_metadata = SantanderMetadataObject::try_from(&item.data.connector_meta_data)?;
let response = pix_data.clone();
let expiration_time = response.calendar.expiration;
let expiration_i64 = i64::from(expiration_time);
let rfc3339_expiry = (OffsetDateTime::now_utc() + time::Duration::seconds(expiration_i64))
.format(&time::format_description::well_known::Rfc3339)
.map_err(|_| errors::ConnectorError::ResponseHandlingFailed)?;
let qr_expiration_duration = OffsetDateTime::parse(
rfc3339_expiry.as_str(),
&time::format_description::well_known::Rfc3339,
)
.map_err(|_| errors::ConnectorError::ResponseHandlingFailed)?
.unix_timestamp()
* 1000;
let merchant_city = santander_mca_metadata.merchant_city.as_str();
let merchant_name = santander_mca_metadata.merchant_name.as_str();
let payload_url = if let Some(location) = response.location {
location
} else {
return Err(errors::ConnectorError::ResponseHandlingFailed)?;
};
let amount_i64 = StringMajorUnitForConnector
.convert_back(response.value.original, enums::Currency::BRL)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?
.get_amount_as_i64();
let amount_string = amount_i64.to_string();
let amount = amount_string.as_str();
let dynamic_pix_code = generate_emv_string(
payload_url.as_str(),
merchant_name,
merchant_city,
Some(amount),
Some(response.transaction_id.as_str()),
);
let image_data = QrImage::new_from_data(dynamic_pix_code.clone())
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let image_data_url = Url::parse(image_data.data.clone().as_str())
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let qr_code_info = QrCodeInformation::QrDataUrl {
image_data_url,
display_to_timestamp: Some(qr_expiration_duration),
};
Some(qr_code_info.encode_to_value())
.transpose()
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
#[derive(Default, Debug, Serialize)]
pub struct SantanderRefundRequest {
#[serde(rename = "valor")]
pub value: StringMajorUnit,
}
impl<F> TryFrom<&SantanderRouterData<&RefundsRouterData<F>>> for SantanderRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SantanderRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
value: item.amount.to_owned(),
})
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SantanderRefundStatus {
InProcessing,
Returned,
NotDone,
}
impl From<SantanderRefundStatus> for enums::RefundStatus {
fn from(item: SantanderRefundStatus) -> Self {
match item {
SantanderRefundStatus::Returned => Self::Success,
SantanderRefundStatus::NotDone => Self::Failure,
SantanderRefundStatus::InProcessing => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SantanderRefundResponse {
pub id: Secret<String>,
pub rtr_id: Secret<String>,
#[serde(rename = "valor")]
pub value: StringMajorUnit,
#[serde(rename = "horario")]
pub time: SantanderTime,
pub status: SantanderRefundStatus,
#[serde(rename = "motivo")]
pub reason: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SantanderTime {
#[serde(rename = "solicitacao")]
pub request: Option<String>,
#[serde(rename = "liquidacao")]
pub liquidation: Option<String>,
}
impl<F> TryFrom<RefundsResponseRouterData<F, SantanderRefundResponse>> for RefundsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<F, SantanderRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.rtr_id.clone().expose(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub enum SantanderErrorResponse {
PixQrCode(SantanderPixQRCodeErrorResponse),
Boleto(SantanderBoletoErrorResponse),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SantanderBoletoErrorResponse {
#[serde(rename = "_errorCode")]
pub error_code: i64,
#[serde(rename = "_message")]
pub error_message: String,
#[serde(rename = "_details")]
pub issuer_error_message: String,
#[serde(rename = "_timestamp")]
pub timestamp: String,
#[serde(rename = "_traceId")]
pub trace_id: String,
#[serde(rename = "_errors")]
pub errors: Option<Vec<ErrorObject>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorObject {
#[serde(rename = "_code")]
pub code: Option<i64>,
#[serde(rename = "_field")]
pub field: Option<String>,
#[serde(rename = "_message")]
pub message: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SantanderPixQRCodeErrorResponse {
#[serde(rename = "type")]
pub field_type: Secret<String>,
pub title: String,
pub status: i64,
pub detail: Option<String>,
pub correlation_id: Option<String>,
#[serde(rename = "violacoes")]
pub violations: Option<Vec<SantanderViolations>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SantanderViolations {
#[serde(rename = "razao")]
pub reason: Option<String>,
#[serde(rename = "propriedade")]
pub property: Option<String>,
#[serde(rename = "valor")]
pub value: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SantanderWebhookBody {
pub message: MessageCode, // meaning of this enum variant is not clear
pub function: FunctionType, // event type of the webhook
pub payment_type: WebhookPaymentType,
pub issue_date: String,
pub payment_date: String,
pub bank_code: String,
pub payment_channel: PaymentChannel,
pub payment_kind: PaymentKind,
pub covenant: String,
pub type_of_person_agreement: enums::DocumentKind,
pub agreement_document: String,
pub bank_number: String,
pub client_number: String,
pub participant_code: String,
pub tx_id: String,
pub payer_document_type: enums::DocumentKind,
pub payer_document_number: String,
pub payer_name: String,
pub final_beneficiary_document_type: enums::DocumentKind,
pub final_beneficiary_document_number: String,
pub final_beneficiary_name: String,
pub due_date: String,
pub nominal_value: StringMajorUnit,
pub payed_value: String,
pub interest_value: String,
pub fine: String,
pub deduction_value: String,
pub rebate_value: String,
pub iof_value: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum MessageCode {
Wbhkpagest,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FunctionType {
Pagamento, // Payment
Estorno, // Refund
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum WebhookPaymentType {
Santander,
OutrosBancos,
Pix,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
/// Represents the channel through which a boleto payment was made.
pub enum PaymentChannel {
/// Payment made at a bank branch or ATM (self-service).
AgenciasAutoAtendimento,
/// Payment made through online banking.
InternetBanking,
/// Payment made at a physical correspondent agent (e.g., convenience stores, partner outlets).
CorrespondenteBancarioFisico,
/// Payment made via Santander’s call center.
CentralDeAtendimento,
/// Payment made via electronic file, typically for bulk company payments.
ArquivoEletronico,
/// Payment made via DDA (Débito Direto Autorizado) / electronic bill presentment system.
Dda,
/// Payment made via digital correspondent channels (apps, kiosks, digital partners).
CorrespondenteBancarioDigital,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
/// Represents the type of payment instrument used to pay a boleto.
pub enum PaymentKind {
/// Payment made in cash or physical form (not via account or card).
Especie,
/// Payment made via direct debit from a bank account.
DebitoEmConta,
/// Payment made via credit card.
CartaoDeCredito,
/// Payment made via check.
Cheque,
}
pub(crate) fn get_webhook_object_from_body(
body: &[u8],
) -> CustomResult<SantanderWebhookBody, common_utils::errors::ParsingError> {
let webhook: SantanderWebhookBody = body.parse_struct("SantanderIncomingWebhook")?;
Ok(webhook)
}
pub(crate) fn get_santander_webhook_event(
event_type: FunctionType,
) -> api_models::webhooks::IncomingWebhookEvent {
// need to confirm about the other possible webhook event statues, as of now only two known
match event_type {
FunctionType::Pagamento => api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess,
FunctionType::Estorno => api_models::webhooks::IncomingWebhookEvent::RefundSuccess,
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/santander/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 10304
}
|
large_file_-6666250599344814190
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs
</path>
<file>
use common_enums::enums;
use common_utils::{request::Method, types::FloatMajorUnit};
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::PaymentsAuthorizeRequestData,
};
#[derive(Debug, Serialize)]
pub struct BitpayRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for BitpayRouterData<T> {
fn from((amount, router_data): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum TransactionSpeed {
Low,
#[default]
Medium,
High,
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct BitpayPaymentsRequest {
price: FloatMajorUnit,
currency: String,
#[serde(rename = "redirectURL")]
redirect_url: String,
#[serde(rename = "notificationURL")]
notification_url: String,
transaction_speed: TransactionSpeed,
token: Secret<String>,
order_id: String,
}
impl TryFrom<&BitpayRouterData<&types::PaymentsAuthorizeRouterData>> for BitpayPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BitpayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
get_crypto_specific_payment_data(item)
}
}
// Auth Struct
pub struct BitpayAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BitpayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum BitpayPaymentStatus {
#[default]
New,
Paid,
Confirmed,
Complete,
Expired,
Invalid,
}
impl From<BitpayPaymentStatus> for enums::AttemptStatus {
fn from(item: BitpayPaymentStatus) -> Self {
match item {
BitpayPaymentStatus::New => Self::AuthenticationPending,
BitpayPaymentStatus::Complete | BitpayPaymentStatus::Confirmed => Self::Charged,
BitpayPaymentStatus::Expired => Self::Failure,
_ => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ExceptionStatus {
#[default]
Unit,
Bool(bool),
String(String),
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BitpayPaymentResponseData {
pub url: Option<url::Url>,
pub status: BitpayPaymentStatus,
pub price: FloatMajorUnit,
pub currency: String,
pub amount_paid: FloatMajorUnit,
pub invoice_time: Option<FloatMajorUnit>,
pub rate_refresh_time: Option<i64>,
pub expiration_time: Option<i64>,
pub current_time: Option<i64>,
pub id: String,
pub order_id: Option<String>,
pub low_fee_detected: Option<bool>,
pub display_amount_paid: Option<String>,
pub exception_status: ExceptionStatus,
pub redirect_url: Option<String>,
pub refund_address_request_pending: Option<bool>,
pub merchant_name: Option<Secret<String>>,
pub token: Option<Secret<String>>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct BitpayPaymentsResponse {
data: BitpayPaymentResponseData,
facade: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, BitpayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BitpayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.data
.url
.map(|x| RedirectForm::from((x, Method::Get)));
let connector_id = ResponseId::ConnectorTransactionId(item.response.data.id.clone());
let attempt_status = item.response.data.status;
Ok(Self {
status: enums::AttemptStatus::from(attempt_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: connector_id,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
.response
.data
.order_id
.or(Some(item.response.data.id)),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct BitpayRefundRequest {
pub amount: FloatMajorUnit,
}
impl<F> TryFrom<&BitpayRouterData<&types::RefundsRouterData<F>>> for BitpayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BitpayRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct BitpayErrorResponse {
pub error: String,
pub code: Option<String>,
pub message: Option<String>,
}
fn get_crypto_specific_payment_data(
item: &BitpayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<BitpayPaymentsRequest, error_stack::Report<errors::ConnectorError>> {
let price = item.amount;
let currency = item.router_data.request.currency.to_string();
let redirect_url = item.router_data.request.get_router_return_url()?;
let notification_url = item.router_data.request.get_webhook_url()?;
let transaction_speed = TransactionSpeed::Medium;
let auth_type = item.router_data.connector_auth_type.clone();
let token = match auth_type {
ConnectorAuthType::HeaderKey { api_key } => api_key,
_ => String::default().into(),
};
let order_id = item.router_data.connector_request_reference_id.clone();
Ok(BitpayPaymentsRequest {
price,
currency,
redirect_url,
notification_url,
transaction_speed,
token,
order_id,
})
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BitpayWebhookDetails {
pub event: Event,
pub data: BitpayPaymentResponseData,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Event {
pub code: i64,
pub name: WebhookEventType,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum WebhookEventType {
#[serde(rename = "invoice_paidInFull")]
Paid,
#[serde(rename = "invoice_confirmed")]
Confirmed,
#[serde(rename = "invoice_completed")]
Completed,
#[serde(rename = "invoice_expired")]
Expired,
#[serde(rename = "invoice_failedToConfirm")]
Invalid,
#[serde(rename = "invoice_declined")]
Declined,
#[serde(rename = "invoice_refundComplete")]
Refunded,
#[serde(rename = "invoice_manuallyNotified")]
Resent,
#[serde(other)]
Unknown,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2197
}
|
large_file_7451702866713123043
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/moneris/transformers.rs
</path>
<file>
use common_enums::enums;
use common_utils::types::MinorUnit;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefreshTokenRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{CardData as _, PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
const CLIENT_CREDENTIALS: &str = "client_credentials";
pub struct MonerisRouterData<T> {
pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for MonerisRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub mod auth_headers {
pub const X_MERCHANT_ID: &str = "X-Merchant-Id";
pub const API_VERSION: &str = "Api-Version";
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MonerisPaymentsRequest {
idempotency_key: String,
amount: Amount,
payment_method: PaymentMethod,
automatic_capture: bool,
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
currency: enums::Currency,
amount: MinorUnit,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum PaymentMethod {
Card(PaymentMethodCard),
PaymentMethodId(PaymentMethodId),
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethodCard {
payment_method_source: PaymentMethodSource,
card: MonerisCard,
store_payment_method: StorePaymentMethod,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethodId {
payment_method_source: PaymentMethodSource,
payment_method_id: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentMethodSource {
Card,
PaymentMethodId,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MonerisCard {
card_number: cards::CardNumber,
expiry_month: Secret<i64>,
expiry_year: Secret<i64>,
card_security_code: Secret<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum StorePaymentMethod {
DoNotStore,
CardholderInitiated,
MerchantInitiated,
}
impl TryFrom<&MonerisRouterData<&PaymentsAuthorizeRouterData>> for MonerisPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &MonerisRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if item.router_data.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Card 3DS".to_string(),
connector: "Moneris",
})?
};
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ref req_card) => {
let idempotency_key = uuid::Uuid::new_v4().to_string();
let amount = Amount {
currency: item.router_data.request.currency,
amount: item.amount,
};
let payment_method = PaymentMethod::Card(PaymentMethodCard {
payment_method_source: PaymentMethodSource::Card,
card: MonerisCard {
card_number: req_card.card_number.clone(),
expiry_month: Secret::new(
req_card
.card_exp_month
.peek()
.parse::<i64>()
.change_context(errors::ConnectorError::ParsingFailed)?,
),
expiry_year: Secret::new(
req_card
.get_expiry_year_4_digit()
.peek()
.parse::<i64>()
.change_context(errors::ConnectorError::ParsingFailed)?,
),
card_security_code: req_card.card_cvc.clone(),
},
store_payment_method: if item
.router_data
.request
.is_customer_initiated_mandate_payment()
{
StorePaymentMethod::CardholderInitiated
} else {
StorePaymentMethod::DoNotStore
},
});
let automatic_capture = item.router_data.request.is_auto_capture()?;
Ok(Self {
idempotency_key,
amount,
payment_method,
automatic_capture,
})
}
PaymentMethodData::MandatePayment => {
let idempotency_key = uuid::Uuid::new_v4().to_string();
let amount = Amount {
currency: item.router_data.request.currency,
amount: item.amount,
};
let automatic_capture = item.router_data.request.is_auto_capture()?;
let payment_method = PaymentMethod::PaymentMethodId(PaymentMethodId {
payment_method_source: PaymentMethodSource::PaymentMethodId,
payment_method_id: item
.router_data
.request
.connector_mandate_id()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
})?
.into(),
});
Ok(Self {
idempotency_key,
amount,
payment_method,
automatic_capture,
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
pub struct MonerisAuthType {
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
pub(super) merchant_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for MonerisAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
client_id: key1.to_owned(),
client_secret: api_key.to_owned(),
merchant_id: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct MonerisAuthRequest {
client_id: Secret<String>,
client_secret: Secret<String>,
grant_type: String,
}
impl TryFrom<&RefreshTokenRouterData> for MonerisAuthRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
let auth = MonerisAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
client_id: auth.client_id.clone(),
client_secret: auth.client_secret.clone(),
grant_type: CLIENT_CREDENTIALS.to_string(),
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MonerisAuthResponse {
access_token: Secret<String>,
token_type: String,
expires_in: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, MonerisAuthResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, MonerisAuthResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item
.response
.expires_in
.parse::<i64>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum MonerisPaymentStatus {
Succeeded,
#[default]
Processing,
Canceled,
Declined,
DeclinedRetry,
Authorized,
}
impl From<MonerisPaymentStatus> for common_enums::AttemptStatus {
fn from(item: MonerisPaymentStatus) -> Self {
match item {
MonerisPaymentStatus::Succeeded => Self::Charged,
MonerisPaymentStatus::Authorized => Self::Authorized,
MonerisPaymentStatus::Canceled => Self::Voided,
MonerisPaymentStatus::Declined | MonerisPaymentStatus::DeclinedRetry => Self::Failure,
MonerisPaymentStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MonerisPaymentsResponse {
payment_status: MonerisPaymentStatus,
payment_id: String,
payment_method: MonerisPaymentMethodData,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MonerisPaymentMethodData {
payment_method_id: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, MonerisPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, MonerisPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.payment_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.payment_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(Some(MandateReference {
connector_mandate_id: Some(
item.response
.payment_method
.payment_method_id
.peek()
.to_string(),
),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.payment_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MonerisPaymentsCaptureRequest {
amount: Amount,
idempotency_key: String,
}
impl TryFrom<&MonerisRouterData<&PaymentsCaptureRouterData>> for MonerisPaymentsCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &MonerisRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let amount = Amount {
currency: item.router_data.request.currency,
amount: item.amount,
};
let idempotency_key = uuid::Uuid::new_v4().to_string();
Ok(Self {
amount,
idempotency_key,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MonerisCancelRequest {
idempotency_key: String,
reason: Option<String>,
}
impl TryFrom<&PaymentsCancelRouterData> for MonerisCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let idempotency_key = uuid::Uuid::new_v4().to_string();
let reason = item.request.cancellation_reason.clone();
Ok(Self {
idempotency_key,
reason,
})
}
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MonerisRefundRequest {
pub refund_amount: Amount,
pub idempotency_key: String,
pub reason: Option<String>,
pub payment_id: String,
}
impl<F> TryFrom<&MonerisRouterData<&RefundsRouterData<F>>> for MonerisRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &MonerisRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let refund_amount = Amount {
currency: item.router_data.request.currency,
amount: item.amount,
};
let idempotency_key = uuid::Uuid::new_v4().to_string();
let reason = item.router_data.request.reason.clone();
let payment_id = item.router_data.request.connector_transaction_id.clone();
Ok(Self {
refund_amount,
idempotency_key,
reason,
payment_id,
})
}
}
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundStatus {
Succeeded,
#[default]
Processing,
Declined,
DeclinedRetry,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Declined | RefundStatus::DeclinedRetry => Self::Failure,
RefundStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
refund_id: String,
refund_status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund_id.to_string(),
refund_status: enums::RefundStatus::from(item.response.refund_status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund_id.to_string(),
refund_status: enums::RefundStatus::from(item.response.refund_status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MonerisErrorResponse {
pub status: u16,
pub category: String,
pub title: String,
pub errors: Option<Vec<MonerisError>>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MonerisError {
pub reason_code: String,
pub parameter_name: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct MonerisAuthErrorResponse {
pub error: String,
pub error_description: Option<String>,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/moneris/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3489
}
|
large_file_8948834638065638832
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
</path>
<file>
use common_enums::enums;
use common_utils::{id_type, pii::Email, request::Method, types::MinorUnit};
use hyperswitch_domain_models::{
payment_method_data::{BankRedirectData, PaymentMethodData},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::Execute,
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
use hyperswitch_interfaces::{consts, errors};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefreshTokenRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{self, is_payment_failure, AddressDetailsData, RouterData as _},
};
const PASSWORD: &str = "password";
pub struct VoltRouterData<T> {
pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for VoltRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub mod webhook_headers {
pub const X_VOLT_SIGNED: &str = "X-Volt-Signed";
pub const X_VOLT_TIMED: &str = "X-Volt-Timed";
pub const USER_AGENT: &str = "User-Agent";
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentsRequest {
amount: MinorUnit,
currency_code: enums::Currency,
#[serde(rename = "type")]
transaction_type: TransactionType,
merchant_internal_reference: String,
shopper: ShopperDetails,
payment_success_url: Option<String>,
payment_failure_url: Option<String>,
payment_pending_url: Option<String>,
payment_cancel_url: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionType {
Bills,
Goods,
PersonToPerson,
Other,
Services,
}
#[derive(Debug, Serialize)]
pub struct ShopperDetails {
reference: id_type::CustomerId,
email: Option<Email>,
first_name: Secret<String>,
last_name: Secret<String>,
}
impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &VoltRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankRedirect(ref bank_redirect) => match bank_redirect {
BankRedirectData::OpenBankingUk { .. } => {
let amount = item.amount;
let currency_code = item.router_data.request.currency;
let merchant_internal_reference =
item.router_data.connector_request_reference_id.clone();
let payment_success_url = item.router_data.request.router_return_url.clone();
let payment_failure_url = item.router_data.request.router_return_url.clone();
let payment_pending_url = item.router_data.request.router_return_url.clone();
let payment_cancel_url = item.router_data.request.router_return_url.clone();
let address = item.router_data.get_billing_address()?;
let first_name = address.get_first_name()?;
let shopper = ShopperDetails {
email: item.router_data.request.email.clone(),
first_name: first_name.to_owned(),
last_name: address.get_last_name().unwrap_or(first_name).to_owned(),
reference: item.router_data.get_customer_id()?.to_owned(),
};
let transaction_type = TransactionType::Services; //transaction_type is a form of enum, it is pre defined and value for this can not be taken from user so we are keeping it as Services as this transaction is type of service.
Ok(Self {
amount,
currency_code,
merchant_internal_reference,
payment_success_url,
payment_failure_url,
payment_pending_url,
payment_cancel_url,
shopper,
transaction_type,
})
}
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Bizum {}
| BankRedirectData::Blik { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Eps { .. }
| BankRedirectData::Giropay { .. }
| BankRedirectData::Ideal { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::Sofort { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Volt"),
)
.into())
}
},
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Volt"),
)
.into())
}
}
}
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct VoltAuthUpdateRequest {
grant_type: String,
client_id: Secret<String>,
client_secret: Secret<String>,
username: Secret<String>,
password: Secret<String>,
}
impl TryFrom<&RefreshTokenRouterData> for VoltAuthUpdateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
let auth = VoltAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
grant_type: PASSWORD.to_string(),
username: auth.username,
password: auth.password,
client_id: auth.client_id,
client_secret: auth.client_secret,
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct VoltAuthUpdateResponse {
pub access_token: Secret<String>,
pub token_type: String,
pub expires_in: i64,
pub refresh_token: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, VoltAuthUpdateResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, VoltAuthUpdateResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
pub struct VoltAuthType {
pub(super) username: Secret<String>,
pub(super) password: Secret<String>,
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for VoltAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Ok(Self {
username: api_key.to_owned(),
password: api_secret.to_owned(),
client_id: key1.to_owned(),
client_secret: key2.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
fn get_attempt_status(
(item, current_status): (VoltPaymentStatus, enums::AttemptStatus),
) -> enums::AttemptStatus {
match item {
VoltPaymentStatus::Received | VoltPaymentStatus::Settled => enums::AttemptStatus::Charged,
VoltPaymentStatus::Completed | VoltPaymentStatus::DelayedAtBank => {
enums::AttemptStatus::Pending
}
VoltPaymentStatus::NewPayment
| VoltPaymentStatus::BankRedirect
| VoltPaymentStatus::AwaitingCheckoutAuthorisation => {
enums::AttemptStatus::AuthenticationPending
}
VoltPaymentStatus::RefusedByBank
| VoltPaymentStatus::RefusedByRisk
| VoltPaymentStatus::NotReceived
| VoltPaymentStatus::ErrorAtBank
| VoltPaymentStatus::CancelledByUser
| VoltPaymentStatus::AbandonedByUser
| VoltPaymentStatus::Failed => enums::AttemptStatus::Failure,
VoltPaymentStatus::Unknown => current_status,
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentsResponse {
checkout_url: String,
id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, VoltPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, VoltPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let url = item.response.checkout_url;
let redirection_data = Some(RedirectForm::Form {
endpoint: url,
method: Method::Get,
form_fields: Default::default(),
});
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(strum::Display)]
pub enum VoltPaymentStatus {
NewPayment,
Completed,
Received,
NotReceived,
BankRedirect,
DelayedAtBank,
AwaitingCheckoutAuthorisation,
RefusedByBank,
RefusedByRisk,
ErrorAtBank,
CancelledByUser,
AbandonedByUser,
Failed,
Settled,
Unknown,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum VoltPaymentsResponseData {
PsyncResponse(VoltPsyncResponse),
WebhookResponse(VoltPaymentWebhookObjectResource),
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPsyncResponse {
status: VoltPaymentStatus,
id: String,
merchant_internal_reference: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, VoltPaymentsResponseData, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, VoltPaymentsResponseData, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
VoltPaymentsResponseData::PsyncResponse(payment_response) => {
let status =
get_attempt_status((payment_response.status.clone(), item.data.status));
Ok(Self {
status,
response: if is_payment_failure(status) {
Err(ErrorResponse {
code: payment_response.status.clone().to_string(),
message: payment_response.status.clone().to_string(),
reason: Some(payment_response.status.to_string()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(payment_response.id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
payment_response.id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: payment_response
.merchant_internal_reference
.or(Some(payment_response.id)),
incremental_authorization_allowed: None,
charges: None,
})
},
..item.data
})
}
VoltPaymentsResponseData::WebhookResponse(webhook_response) => {
let detailed_status = webhook_response.detailed_status.clone();
let status = enums::AttemptStatus::from(webhook_response.status);
Ok(Self {
status,
response: if is_payment_failure(status) {
Err(ErrorResponse {
code: detailed_status
.clone()
.map(|volt_status| volt_status.to_string())
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_owned()),
message: detailed_status
.clone()
.map(|volt_status| volt_status.to_string())
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_owned()),
reason: detailed_status
.clone()
.map(|volt_status| volt_status.to_string()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(webhook_response.payment.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
webhook_response.payment.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: webhook_response
.merchant_internal_reference
.or(Some(webhook_response.payment)),
incremental_authorization_allowed: None,
charges: None,
})
},
..item.data
})
}
}
}
}
impl From<VoltWebhookPaymentStatus> for enums::AttemptStatus {
fn from(status: VoltWebhookPaymentStatus) -> Self {
match status {
VoltWebhookPaymentStatus::Received => Self::Charged,
VoltWebhookPaymentStatus::Failed | VoltWebhookPaymentStatus::NotReceived => {
Self::Failure
}
VoltWebhookPaymentStatus::Completed | VoltWebhookPaymentStatus::Pending => {
Self::Pending
}
}
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltRefundRequest {
pub amount: MinorUnit,
pub external_reference: String,
}
impl<F> TryFrom<&VoltRouterData<&types::RefundsRouterData<F>>> for VoltRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &VoltRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
external_reference: item.router_data.request.refund_id.clone(),
})
}
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
id: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::Pending, //We get Refund Status only by Webhooks
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentWebhookBodyReference {
pub payment: String,
pub merchant_internal_reference: Option<String>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltRefundWebhookBodyReference {
pub refund: String,
pub external_reference: Option<String>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum WebhookResponse {
// the enum order shouldn't be changed as this is being used during serialization and deserialization
Refund(VoltRefundWebhookBodyReference),
Payment(VoltPaymentWebhookBodyReference),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum VoltWebhookBodyEventType {
Payment(VoltPaymentsWebhookBodyEventType),
Refund(VoltRefundsWebhookBodyEventType),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentsWebhookBodyEventType {
pub status: VoltWebhookPaymentStatus,
pub detailed_status: Option<VoltDetailedStatus>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltRefundsWebhookBodyEventType {
pub status: VoltWebhookRefundsStatus,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum VoltWebhookObjectResource {
Payment(VoltPaymentWebhookObjectResource),
Refund(VoltRefundWebhookObjectResource),
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentWebhookObjectResource {
#[serde(alias = "id")]
pub payment: String,
pub merchant_internal_reference: Option<String>,
pub status: VoltWebhookPaymentStatus,
pub detailed_status: Option<VoltDetailedStatus>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltRefundWebhookObjectResource {
pub refund: String,
pub external_reference: Option<String>,
pub status: VoltWebhookRefundsStatus,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum VoltWebhookPaymentStatus {
Completed,
Failed,
Pending,
Received,
NotReceived,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum VoltWebhookRefundsStatus {
RefundConfirmed,
RefundFailed,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(strum::Display)]
pub enum VoltDetailedStatus {
RefusedByRisk,
RefusedByBank,
ErrorAtBank,
CancelledByUser,
AbandonedByUser,
Failed,
Completed,
BankRedirect,
DelayedAtBank,
AwaitingCheckoutAuthorisation,
}
impl From<VoltWebhookBodyEventType> for api_models::webhooks::IncomingWebhookEvent {
fn from(status: VoltWebhookBodyEventType) -> Self {
match status {
VoltWebhookBodyEventType::Payment(payment_data) => match payment_data.status {
VoltWebhookPaymentStatus::Received => Self::PaymentIntentSuccess,
VoltWebhookPaymentStatus::Failed | VoltWebhookPaymentStatus::NotReceived => {
Self::PaymentIntentFailure
}
VoltWebhookPaymentStatus::Completed | VoltWebhookPaymentStatus::Pending => {
Self::PaymentIntentProcessing
}
},
VoltWebhookBodyEventType::Refund(refund_data) => match refund_data.status {
VoltWebhookRefundsStatus::RefundConfirmed => Self::RefundSuccess,
VoltWebhookRefundsStatus::RefundFailed => Self::RefundFailure,
},
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct VoltErrorResponse {
pub exception: VoltErrorException,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct VoltAuthErrorResponse {
pub code: u64,
pub message: String,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct VoltErrorException {
pub code: u64,
pub message: String,
pub error_list: Option<Vec<VoltErrorList>>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct VoltErrorList {
pub property: String,
pub message: String,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/volt/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4627
}
|
large_file_-315752936220904412
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
</path>
<file>
use common_enums::enums::{self, AttemptStatus};
use common_utils::{ext_traits::Encode, pii, request::Method, types::StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{Execute, RSync},
router_request_types::{MandateRevokeRequestData, ResponseId},
router_response_types::{
MandateReference, MandateRevokeResponseData, PaymentsResponseData, RedirectForm,
RefundsResponseData,
},
types::{
MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, CardData, GooglePayWalletData, PaymentsAuthorizeRequestData,
RevokeMandateRequestData, RouterData as OtherRouterData, WalletData as OtherWalletData,
},
};
// These needs to be accepted from SDK, need to be done after 1.0.0 stability as API contract will change
const GOOGLEPAY_API_VERSION_MINOR: u8 = 0;
const GOOGLEPAY_API_VERSION: u8 = 2;
#[derive(Debug, Serialize)]
pub struct NoonRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
pub mandate_amount: Option<StringMajorUnit>,
}
impl<T> From<(StringMajorUnit, T, Option<StringMajorUnit>)> for NoonRouterData<T> {
fn from(
(amount, router_data, mandate_amount): (StringMajorUnit, T, Option<StringMajorUnit>),
) -> Self {
Self {
amount,
router_data,
mandate_amount,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum NoonChannels {
Web,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum NoonSubscriptionType {
Unscheduled,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonSubscriptionData {
#[serde(rename = "type")]
subscription_type: NoonSubscriptionType,
//Short description about the subscription.
name: String,
max_amount: StringMajorUnit,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonBillingAddress {
street: Option<Secret<String>>,
street2: Option<Secret<String>>,
city: Option<String>,
state_province: Option<Secret<String>>,
country: Option<api_models::enums::CountryAlpha2>,
postal_code: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonBilling {
address: NoonBillingAddress,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonOrder {
amount: StringMajorUnit,
currency: Option<enums::Currency>,
channel: NoonChannels,
category: Option<String>,
reference: String,
//Short description of the order.
name: String,
nvp: Option<NoonOrderNvp>,
ip_address: Option<Secret<String, pii::IpAddress>>,
}
#[derive(Debug, Serialize)]
pub struct NoonOrderNvp {
#[serde(flatten)]
inner: std::collections::BTreeMap<String, Secret<String>>,
}
fn get_value_as_string(value: &serde_json::Value) -> String {
match value {
serde_json::Value::String(string) => string.to_owned(),
serde_json::Value::Null
| serde_json::Value::Bool(_)
| serde_json::Value::Number(_)
| serde_json::Value::Array(_)
| serde_json::Value::Object(_) => value.to_string(),
}
}
impl NoonOrderNvp {
pub fn new(metadata: &serde_json::Value) -> Self {
let metadata_as_string = metadata.to_string();
let hash_map: std::collections::BTreeMap<String, serde_json::Value> =
serde_json::from_str(&metadata_as_string).unwrap_or(std::collections::BTreeMap::new());
let inner = hash_map
.into_iter()
.enumerate()
.map(|(index, (hs_key, hs_value))| {
let noon_key = format!("{}", index + 1);
// to_string() function on serde_json::Value returns a string with "" quotes. Noon doesn't allow this. Hence get_value_as_string function
let noon_value = format!("{hs_key}={}", get_value_as_string(&hs_value));
(noon_key, Secret::new(noon_value))
})
.collect();
Self { inner }
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum NoonPaymentActions {
Authorize,
Sale,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonConfiguration {
tokenize_c_c: Option<bool>,
payment_action: NoonPaymentActions,
return_url: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonSubscription {
subscription_identifier: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonCard {
name_on_card: Option<Secret<String>>,
number_plain: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvv: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonApplePayPaymentMethod {
pub display_name: String,
pub network: String,
#[serde(rename = "type")]
pub pm_type: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonApplePayHeader {
ephemeral_public_key: Secret<String>,
public_key_hash: Secret<String>,
transaction_id: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NoonApplePaymentData {
version: Secret<String>,
data: Secret<String>,
signature: Secret<String>,
header: NoonApplePayHeader,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonApplePayData {
payment_data: NoonApplePaymentData,
payment_method: NoonApplePayPaymentMethod,
transaction_identifier: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonApplePayTokenData {
token: NoonApplePayData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonApplePay {
payment_info: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonGooglePay {
api_version_minor: u8,
api_version: u8,
payment_method_data: GooglePayWalletData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPayPal {
return_url: String,
}
#[derive(Debug, Serialize)]
#[serde(tag = "type", content = "data", rename_all = "UPPERCASE")]
pub enum NoonPaymentData {
Card(NoonCard),
Subscription(NoonSubscription),
ApplePay(NoonApplePay),
GooglePay(NoonGooglePay),
PayPal(NoonPayPal),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NoonApiOperations {
Initiate,
Capture,
Reverse,
Refund,
CancelSubscription,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsRequest {
api_operation: NoonApiOperations,
order: NoonOrder,
configuration: NoonConfiguration,
payment_data: NoonPaymentData,
subscription: Option<NoonSubscriptionData>,
billing: Option<NoonBilling>,
}
impl TryFrom<&NoonRouterData<&PaymentsAuthorizeRouterData>> for NoonPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(data: &NoonRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
let item = data.router_data;
let amount = &data.amount;
let mandate_amount = &data.mandate_amount;
let (payment_data, currency, category) = match item.request.connector_mandate_id() {
Some(mandate_id) => (
NoonPaymentData::Subscription(NoonSubscription {
subscription_identifier: Secret::new(mandate_id),
}),
None,
None,
),
_ => (
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => Ok(NoonPaymentData::Card(NoonCard {
name_on_card: item.get_optional_billing_full_name(),
number_plain: req_card.card_number.clone(),
expiry_month: req_card.card_exp_month.clone(),
expiry_year: req_card.get_expiry_year_4_digit(),
cvv: req_card.card_cvc,
})),
PaymentMethodData::Wallet(wallet_data) => match wallet_data.clone() {
WalletData::GooglePay(google_pay_data) => {
Ok(NoonPaymentData::GooglePay(NoonGooglePay {
api_version_minor: GOOGLEPAY_API_VERSION_MINOR,
api_version: GOOGLEPAY_API_VERSION,
payment_method_data: GooglePayWalletData::try_from(google_pay_data)
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "google_pay_data",
})?,
}))
}
WalletData::ApplePay(apple_pay_data) => {
let payment_token_data = NoonApplePayTokenData {
token: NoonApplePayData {
payment_data: wallet_data
.get_wallet_token_as_json("Apple Pay".to_string())?,
payment_method: NoonApplePayPaymentMethod {
display_name: apple_pay_data.payment_method.display_name,
network: apple_pay_data.payment_method.network,
pm_type: apple_pay_data.payment_method.pm_type,
},
transaction_identifier: Secret::new(
apple_pay_data.transaction_identifier,
),
},
};
let payment_token = payment_token_data
.encode_to_string_of_json()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(NoonPaymentData::ApplePay(NoonApplePay {
payment_info: Secret::new(payment_token),
}))
}
WalletData::PaypalRedirect(_) => Ok(NoonPaymentData::PayPal(NoonPayPal {
return_url: item.request.get_router_return_url()?,
})),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Noon"),
)),
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Noon"),
))
}
}?,
Some(item.request.currency),
Some(item.request.order_category.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "order_category",
},
)?),
),
};
let ip_address = item.request.get_ip_address_as_optional();
let channel = NoonChannels::Web;
let billing = item
.get_optional_billing()
.and_then(|billing_address| billing_address.address.as_ref())
.map(|address| NoonBilling {
address: NoonBillingAddress {
street: address.line1.clone(),
street2: address.line2.clone(),
city: address.city.clone(),
// If state is passed in request, country becomes mandatory, keep a check while debugging failed payments
state_province: address.state.clone(),
country: address.country,
postal_code: address.zip.clone(),
},
});
// The description should not have leading or trailing whitespaces, also it should not have double whitespaces and a max 50 chars according to Noon's Docs
let name: String = item
.get_description()?
.trim()
.replace(" ", " ")
.chars()
.take(50)
.collect();
let subscription = mandate_amount
.as_ref()
.map(|mandate_max_amount| NoonSubscriptionData {
subscription_type: NoonSubscriptionType::Unscheduled,
name: name.clone(),
max_amount: mandate_max_amount.to_owned(),
});
let tokenize_c_c = subscription.is_some().then_some(true);
let order = NoonOrder {
amount: amount.to_owned(),
currency,
channel,
category,
reference: item.connector_request_reference_id.clone(),
name,
nvp: item.request.metadata.as_ref().map(NoonOrderNvp::new),
ip_address,
};
let payment_action = if item.request.is_auto_capture()? {
NoonPaymentActions::Sale
} else {
NoonPaymentActions::Authorize
};
Ok(Self {
api_operation: NoonApiOperations::Initiate,
order,
billing,
configuration: NoonConfiguration {
payment_action,
return_url: item.request.router_return_url.clone(),
tokenize_c_c,
},
payment_data,
subscription,
})
}
}
// Auth Struct
pub struct NoonAuthType {
pub(super) api_key: Secret<String>,
pub(super) application_identifier: Secret<String>,
pub(super) business_identifier: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for NoonAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
api_key: api_key.to_owned(),
application_identifier: api_secret.to_owned(),
business_identifier: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Default, Debug, Deserialize, Serialize, strum::Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[strum(serialize_all = "UPPERCASE")]
pub enum NoonPaymentStatus {
Initiated,
Authorized,
Captured,
PartiallyCaptured,
PartiallyRefunded,
PaymentInfoAdded,
#[serde(rename = "3DS_ENROLL_INITIATED")]
ThreeDsEnrollInitiated,
#[serde(rename = "3DS_ENROLL_CHECKED")]
ThreeDsEnrollChecked,
#[serde(rename = "3DS_RESULT_VERIFIED")]
ThreeDsResultVerified,
MarkedForReview,
Authenticated,
PartiallyReversed,
#[default]
Pending,
Cancelled,
Failed,
Refunded,
Expired,
Reversed,
Rejected,
Locked,
}
fn get_payment_status(data: (NoonPaymentStatus, AttemptStatus)) -> AttemptStatus {
let (item, current_status) = data;
match item {
NoonPaymentStatus::Authorized => AttemptStatus::Authorized,
NoonPaymentStatus::Captured
| NoonPaymentStatus::PartiallyCaptured
| NoonPaymentStatus::PartiallyRefunded
| NoonPaymentStatus::Refunded => AttemptStatus::Charged,
NoonPaymentStatus::Reversed | NoonPaymentStatus::PartiallyReversed => AttemptStatus::Voided,
NoonPaymentStatus::Cancelled | NoonPaymentStatus::Expired => {
AttemptStatus::AuthenticationFailed
}
NoonPaymentStatus::ThreeDsEnrollInitiated | NoonPaymentStatus::ThreeDsEnrollChecked => {
AttemptStatus::AuthenticationPending
}
NoonPaymentStatus::ThreeDsResultVerified => AttemptStatus::AuthenticationSuccessful,
NoonPaymentStatus::Failed | NoonPaymentStatus::Rejected => AttemptStatus::Failure,
NoonPaymentStatus::Pending | NoonPaymentStatus::MarkedForReview => AttemptStatus::Pending,
NoonPaymentStatus::Initiated
| NoonPaymentStatus::PaymentInfoAdded
| NoonPaymentStatus::Authenticated => AttemptStatus::Started,
NoonPaymentStatus::Locked => current_status,
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NoonSubscriptionObject {
identifier: Secret<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsOrderResponse {
status: NoonPaymentStatus,
id: u64,
error_code: u64,
error_message: Option<String>,
reference: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonCheckoutData {
post_url: url::Url,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsResponseResult {
order: NoonPaymentsOrderResponse,
checkout_data: Option<NoonCheckoutData>,
subscription: Option<NoonSubscriptionObject>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NoonPaymentsResponse {
result: NoonPaymentsResponseResult,
}
impl<F, T> TryFrom<ResponseRouterData<F, NoonPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, NoonPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let order = item.response.result.order;
let status = get_payment_status((order.status, item.data.status));
let redirection_data =
item.response
.result
.checkout_data
.map(|redirection_data| RedirectForm::Form {
endpoint: redirection_data.post_url.to_string(),
method: Method::Post,
form_fields: std::collections::HashMap::new(),
});
let mandate_reference =
item.response
.result
.subscription
.map(|subscription_data| MandateReference {
connector_mandate_id: Some(subscription_data.identifier.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
Ok(Self {
status,
response: match order.error_message {
Some(error_message) => Err(ErrorResponse {
code: order.error_code.to_string(),
message: error_message.clone(),
reason: Some(error_message),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(order.id.to_string()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
_ => {
let connector_response_reference_id =
order.reference.or(Some(order.id.to_string()));
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(order.id.to_string()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id,
incremental_authorization_allowed: None,
charges: None,
})
}
},
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonActionTransaction {
amount: StringMajorUnit,
currency: enums::Currency,
transaction_reference: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonActionOrder {
id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsActionRequest {
api_operation: NoonApiOperations,
order: NoonActionOrder,
transaction: NoonActionTransaction,
}
impl TryFrom<&NoonRouterData<&PaymentsCaptureRouterData>> for NoonPaymentsActionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(data: &NoonRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let item = data.router_data;
let amount = &data.amount;
let order = NoonActionOrder {
id: item.request.connector_transaction_id.clone(),
};
let transaction = NoonActionTransaction {
amount: amount.to_owned(),
currency: item.request.currency,
transaction_reference: None,
};
Ok(Self {
api_operation: NoonApiOperations::Capture,
order,
transaction,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsCancelRequest {
api_operation: NoonApiOperations,
order: NoonActionOrder,
}
impl TryFrom<&PaymentsCancelRouterData> for NoonPaymentsCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let order = NoonActionOrder {
id: item.request.connector_transaction_id.clone(),
};
Ok(Self {
api_operation: NoonApiOperations::Reverse,
order,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonRevokeMandateRequest {
api_operation: NoonApiOperations,
subscription: NoonSubscriptionObject,
}
impl TryFrom<&MandateRevokeRouterData> for NoonRevokeMandateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &MandateRevokeRouterData) -> Result<Self, Self::Error> {
Ok(Self {
api_operation: NoonApiOperations::CancelSubscription,
subscription: NoonSubscriptionObject {
identifier: Secret::new(item.request.get_connector_mandate_id()?),
},
})
}
}
impl<F> TryFrom<&NoonRouterData<&RefundsRouterData<F>>> for NoonPaymentsActionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(data: &NoonRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let item = data.router_data;
let refund_amount = &data.amount;
let order = NoonActionOrder {
id: item.request.connector_transaction_id.clone(),
};
let transaction = NoonActionTransaction {
amount: refund_amount.to_owned(),
currency: item.request.currency,
transaction_reference: Some(item.request.refund_id.clone()),
};
Ok(Self {
api_operation: NoonApiOperations::Refund,
order,
transaction,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub enum NoonRevokeStatus {
Cancelled,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NoonCancelSubscriptionObject {
status: NoonRevokeStatus,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NoonRevokeMandateResult {
subscription: NoonCancelSubscriptionObject,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NoonRevokeMandateResponse {
result: NoonRevokeMandateResult,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
NoonRevokeMandateResponse,
MandateRevokeRequestData,
MandateRevokeResponseData,
>,
> for RouterData<F, MandateRevokeRequestData, MandateRevokeResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
NoonRevokeMandateResponse,
MandateRevokeRequestData,
MandateRevokeResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.result.subscription.status {
NoonRevokeStatus::Cancelled => Ok(Self {
response: Ok(MandateRevokeResponseData {
mandate_status: common_enums::MandateStatus::Revoked,
}),
..item.data
}),
}
}
}
#[derive(Debug, Default, Deserialize, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Success,
Failed,
#[default]
Pending,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Success => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Pending => Self::Pending,
}
}
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsTransactionResponse {
id: String,
status: RefundStatus,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonRefundResponseResult {
transaction: NoonPaymentsTransactionResponse,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
result: NoonRefundResponseResult,
result_code: u32,
class_description: String,
message: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let response = &item.response;
let refund_status =
enums::RefundStatus::from(response.result.transaction.status.to_owned());
let response = if utils::is_refund_failure(refund_status) {
Err(ErrorResponse {
status_code: item.http_code,
code: response.result_code.to_string(),
message: response.class_description.clone(),
reason: Some(response.message.clone()),
attempt_status: None,
connector_transaction_id: Some(response.result.transaction.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.result.transaction.id,
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonRefundResponseTransactions {
id: String,
status: RefundStatus,
transaction_reference: Option<String>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonRefundSyncResponseResult {
transactions: Vec<NoonRefundResponseTransactions>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundSyncResponse {
result: NoonRefundSyncResponseResult,
result_code: u32,
class_description: String,
message: String,
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundSyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundSyncResponse>,
) -> Result<Self, Self::Error> {
let noon_transaction: &NoonRefundResponseTransactions = item
.response
.result
.transactions
.iter()
.find(|transaction| {
transaction
.transaction_reference
.clone()
.is_some_and(|transaction_instance| {
transaction_instance == item.data.request.refund_id
})
})
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let refund_status = enums::RefundStatus::from(noon_transaction.status.to_owned());
let response = if utils::is_refund_failure(refund_status) {
let response = &item.response;
Err(ErrorResponse {
status_code: item.http_code,
code: response.result_code.to_string(),
message: response.class_description.clone(),
reason: Some(response.message.clone()),
attempt_status: None,
connector_transaction_id: Some(noon_transaction.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: noon_transaction.id.to_owned(),
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Debug, Deserialize, strum::Display)]
pub enum NoonWebhookEventTypes {
Authenticate,
Authorize,
Capture,
Fail,
Refund,
Sale,
#[serde(other)]
Unknown,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonWebhookBody {
pub order_id: u64,
pub order_status: NoonPaymentStatus,
pub event_type: NoonWebhookEventTypes,
pub event_id: String,
pub time_stamp: String,
}
#[derive(Debug, Deserialize)]
pub struct NoonWebhookSignature {
pub signature: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonWebhookOrderId {
pub order_id: u64,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonWebhookEvent {
pub order_status: NoonPaymentStatus,
pub event_type: NoonWebhookEventTypes,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonWebhookObject {
pub order_status: NoonPaymentStatus,
pub order_id: u64,
}
/// This from will ensure that webhook body would be properly parsed into PSync response
impl From<NoonWebhookObject> for NoonPaymentsResponse {
fn from(value: NoonWebhookObject) -> Self {
Self {
result: NoonPaymentsResponseResult {
order: NoonPaymentsOrderResponse {
status: value.order_status,
id: value.order_id,
//For successful payments Noon Always populates error_code as 0.
error_code: 0,
error_message: None,
reference: None,
},
checkout_data: None,
subscription: None,
},
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonErrorResponse {
pub result_code: u32,
pub message: String,
pub class_description: String,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/noon/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 7002
}
|
large_file_-3957861074166427981
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
</path>
<file>
use std::collections::HashMap;
use api_models::payments::{self, AdditionalPaymentData};
use common_enums::enums;
use common_utils::{pii::Email, request::Method, types::MinorUnit};
use hyperswitch_domain_models::{
payment_method_data::{Card, PaymentMethodData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{PaymentsAuthorizeData, ResponseId, SetupMandateRequestData},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types,
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
},
utils::{
get_unimplemented_payment_method_error_message, AdditionalCardInfo, CardData as _,
PaymentsAuthorizeRequestData, RouterData as _,
},
};
const TRANSACTION_ALREADY_CANCELLED: &str = "transaction already canceled";
const TRANSACTION_ALREADY_SETTLED: &str = "already settled";
const REDIRECTION_SBX_URL: &str = "https://pay.sandbox.datatrans.com";
const REDIRECTION_PROD_URL: &str = "https://pay.datatrans.com";
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct DatatransErrorResponse {
pub error: DatatransError,
}
pub struct DatatransAuthType {
pub(super) merchant_id: Secret<String>,
pub(super) passcode: Secret<String>,
}
pub struct DatatransRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DatatransPaymentsRequest {
pub amount: Option<MinorUnit>,
pub currency: enums::Currency,
pub card: DataTransPaymentDetails,
pub refno: String,
pub auto_settle: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub redirect: Option<RedirectUrls>,
pub option: Option<DataTransCreateAlias>,
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DataTransCreateAlias {
pub create_alias: bool,
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct RedirectUrls {
pub success_url: Option<String>,
pub cancel_url: Option<String>,
pub error_url: Option<String>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TransactionType {
Payment,
Credit,
CardCheck,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TransactionStatus {
Initialized,
Authenticated,
Authorized,
Settled,
Canceled,
Transmitted,
Failed,
ChallengeOngoing,
ChallengeRequired,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(untagged)]
pub enum DatatransSyncResponse {
Error(DatatransError),
Response(SyncResponse),
}
#[derive(Debug, Deserialize, Serialize)]
pub enum DataTransCaptureResponse {
Error(DatatransError),
Empty,
}
#[derive(Debug, Deserialize, Serialize)]
pub enum DataTransCancelResponse {
Error(DatatransError),
Empty,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SyncResponse {
pub transaction_id: String,
#[serde(rename = "type")]
pub res_type: TransactionType,
pub status: TransactionStatus,
pub detail: SyncDetails,
pub card: Option<SyncCardDetails>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SyncCardDetails {
pub alias: Option<String>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SyncDetails {
fail: Option<FailDetails>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct FailDetails {
reason: Option<String>,
message: Option<String>,
}
#[derive(Serialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum DataTransPaymentDetails {
Cards(PlainCardDetails),
Mandate(MandateDetails),
}
#[derive(Serialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PlainCardDetails {
#[serde(rename = "type")]
pub res_type: String,
pub number: cards::CardNumber,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
pub cvv: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "3D")]
pub three_ds: Option<ThreeDSecureData>,
}
#[derive(Serialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct MandateDetails {
#[serde(rename = "type")]
pub res_type: String,
pub alias: String,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
}
#[derive(Serialize, Clone, Debug)]
pub struct ThreedsInfo {
cardholder: CardHolder,
}
#[derive(Serialize, Clone, Debug)]
#[serde(untagged)]
pub enum ThreeDSecureData {
Cardholder(ThreedsInfo),
Authentication(ThreeDSData),
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSData {
#[serde(rename = "threeDSTransactionId")]
pub three_ds_transaction_id: Option<Secret<String>>,
pub cavv: Secret<String>,
pub eci: Option<String>,
pub xid: Option<Secret<String>>,
#[serde(rename = "threeDSVersion")]
pub three_ds_version: Option<String>,
#[serde(rename = "authenticationResponse")]
pub authentication_response: String,
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardHolder {
cardholder_name: Secret<String>,
email: Email,
}
#[derive(Debug, Clone, Serialize, Default, Deserialize)]
pub struct DatatransError {
pub code: String,
pub message: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DatatransResponse {
TransactionResponse(DatatransSuccessResponse),
ErrorResponse(DatatransError),
ThreeDSResponse(Datatrans3DSResponse),
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatatransSuccessResponse {
pub transaction_id: String,
pub acquirer_authorization_code: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DatatransRefundsResponse {
Success(DatatransSuccessResponse),
Error(DatatransError),
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Datatrans3DSResponse {
pub transaction_id: String,
#[serde(rename = "3D")]
pub three_ds_enrolled: ThreeDSEnolled,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSEnolled {
pub enrolled: bool,
}
#[derive(Default, Debug, Serialize)]
pub struct DatatransRefundRequest {
pub amount: MinorUnit,
pub currency: enums::Currency,
pub refno: String,
}
#[derive(Debug, Serialize, Clone)]
pub struct DataPaymentCaptureRequest {
pub amount: MinorUnit,
pub currency: enums::Currency,
pub refno: String,
}
impl<T> TryFrom<(MinorUnit, T)> for DatatransRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
impl TryFrom<&types::SetupMandateRouterData> for DatatransPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => Ok(Self {
amount: None,
currency: item.request.currency,
card: DataTransPaymentDetails::Cards(PlainCardDetails {
res_type: "PLAIN".to_string(),
number: req_card.card_number.clone(),
expiry_month: req_card.card_exp_month.clone(),
expiry_year: req_card.get_card_expiry_year_2_digit()?,
cvv: req_card.card_cvc.clone(),
three_ds: Some(ThreeDSecureData::Cardholder(ThreedsInfo {
cardholder: CardHolder {
cardholder_name: item.get_billing_full_name()?,
email: item.get_billing_email()?,
},
})),
}),
refno: item.connector_request_reference_id.clone(),
auto_settle: true, // zero auth doesn't support manual capture
option: Some(DataTransCreateAlias { create_alias: true }),
redirect: Some(RedirectUrls {
success_url: item.request.router_return_url.clone(),
cancel_url: item.request.router_return_url.clone(),
error_url: item.request.router_return_url.clone(),
}),
}),
PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Datatrans"),
))?
}
}
}
}
impl TryFrom<&DatatransRouterData<&types::PaymentsAuthorizeRouterData>>
for DatatransPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let is_mandate_payment = item.router_data.request.is_mandate_payment();
let option =
is_mandate_payment.then_some(DataTransCreateAlias { create_alias: true });
// provides return url for only mandate payment(CIT) or 3ds through datatrans
let redirect = if is_mandate_payment
|| (item.router_data.is_three_ds()
&& item.router_data.request.authentication_data.is_none())
{
Some(RedirectUrls {
success_url: item.router_data.request.router_return_url.clone(),
cancel_url: item.router_data.request.router_return_url.clone(),
error_url: item.router_data.request.router_return_url.clone(),
})
} else {
None
};
Ok(Self {
amount: Some(item.amount),
currency: item.router_data.request.currency,
card: create_card_details(item, &req_card)?,
refno: item.router_data.connector_request_reference_id.clone(),
auto_settle: item.router_data.request.is_auto_capture()?,
option,
redirect,
})
}
PaymentMethodData::MandatePayment => {
let additional_payment_data = match item
.router_data
.request
.additional_payment_method_data
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "additional_payment_method_data",
})? {
AdditionalPaymentData::Card(card) => *card,
_ => Err(errors::ConnectorError::NotSupported {
message: "Payment Method Not Supported".to_string(),
connector: "DataTrans",
})?,
};
Ok(Self {
amount: Some(item.amount),
currency: item.router_data.request.currency,
card: create_mandate_details(item, &additional_payment_data)?,
refno: item.router_data.connector_request_reference_id.clone(),
auto_settle: item.router_data.request.is_auto_capture()?,
option: None,
redirect: None,
})
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Datatrans"),
))?
}
}
}
}
impl TryFrom<&ConnectorAuthType> for DatatransAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
merchant_id: key1.clone(),
passcode: api_key.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
fn get_status(item: &DatatransResponse, is_auto_capture: bool) -> enums::AttemptStatus {
match item {
DatatransResponse::ErrorResponse(_) => enums::AttemptStatus::Failure,
DatatransResponse::TransactionResponse(_) => {
if is_auto_capture {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
DatatransResponse::ThreeDSResponse(_) => enums::AttemptStatus::AuthenticationPending,
}
}
fn create_card_details(
item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>,
card: &Card,
) -> Result<DataTransPaymentDetails, error_stack::Report<errors::ConnectorError>> {
let mut details = PlainCardDetails {
res_type: "PLAIN".to_string(),
number: card.card_number.clone(),
expiry_month: card.card_exp_month.clone(),
expiry_year: card.get_card_expiry_year_2_digit()?,
cvv: card.card_cvc.clone(),
three_ds: None,
};
if let Some(auth_data) = &item.router_data.request.authentication_data {
details.three_ds = Some(ThreeDSecureData::Authentication(ThreeDSData {
three_ds_transaction_id: auth_data
.threeds_server_transaction_id
.clone()
.map(Secret::new),
cavv: auth_data.cavv.clone(),
eci: auth_data.eci.clone(),
xid: auth_data.ds_trans_id.clone().map(Secret::new),
three_ds_version: auth_data
.message_version
.clone()
.map(|version| version.to_string()),
authentication_response: "Y".to_string(),
}));
} else if item.router_data.is_three_ds() {
details.three_ds = Some(ThreeDSecureData::Cardholder(ThreedsInfo {
cardholder: CardHolder {
cardholder_name: item.router_data.get_billing_full_name()?,
email: item.router_data.get_billing_email()?,
},
}));
}
Ok(DataTransPaymentDetails::Cards(details))
}
fn create_mandate_details(
item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>,
additional_card_details: &payments::AdditionalCardInfo,
) -> Result<DataTransPaymentDetails, error_stack::Report<errors::ConnectorError>> {
let alias = item.router_data.request.get_connector_mandate_id()?;
Ok(DataTransPaymentDetails::Mandate(MandateDetails {
res_type: "ALIAS".to_string(),
alias,
expiry_month: additional_card_details.card_exp_month.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "card_exp_month",
},
)?,
expiry_year: additional_card_details.get_card_expiry_year_2_digit()?,
}))
}
impl From<SyncResponse> for enums::AttemptStatus {
fn from(item: SyncResponse) -> Self {
match item.res_type {
TransactionType::Payment => match item.status {
TransactionStatus::Authorized => Self::Authorized,
TransactionStatus::Settled | TransactionStatus::Transmitted => Self::Charged,
TransactionStatus::ChallengeOngoing | TransactionStatus::ChallengeRequired => {
Self::AuthenticationPending
}
TransactionStatus::Canceled => Self::Voided,
TransactionStatus::Failed => Self::Failure,
TransactionStatus::Initialized | TransactionStatus::Authenticated => Self::Pending,
},
TransactionType::CardCheck => match item.status {
TransactionStatus::Settled
| TransactionStatus::Transmitted
| TransactionStatus::Authorized => Self::Charged,
TransactionStatus::ChallengeOngoing | TransactionStatus::ChallengeRequired => {
Self::AuthenticationPending
}
TransactionStatus::Canceled => Self::Voided,
TransactionStatus::Failed => Self::Failure,
TransactionStatus::Initialized | TransactionStatus::Authenticated => Self::Pending,
},
TransactionType::Credit => Self::Failure,
}
}
}
impl From<SyncResponse> for enums::RefundStatus {
fn from(item: SyncResponse) -> Self {
match item.res_type {
TransactionType::Credit => match item.status {
TransactionStatus::Settled | TransactionStatus::Transmitted => Self::Success,
TransactionStatus::ChallengeOngoing | TransactionStatus::ChallengeRequired => {
Self::Pending
}
TransactionStatus::Initialized
| TransactionStatus::Authenticated
| TransactionStatus::Authorized
| TransactionStatus::Canceled
| TransactionStatus::Failed => Self::Failure,
},
TransactionType::Payment | TransactionType::CardCheck => Self::Failure,
}
}
}
impl<F>
TryFrom<ResponseRouterData<F, DatatransResponse, PaymentsAuthorizeData, PaymentsResponseData>>
for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DatatransResponse, PaymentsAuthorizeData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = get_status(&item.response, item.data.request.is_auto_capture()?);
let response = match &item.response {
DatatransResponse::ErrorResponse(error) => Err(ErrorResponse {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
DatatransResponse::TransactionResponse(response) => {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
}
DatatransResponse::ThreeDSResponse(response) => {
let redirection_link = match item.data.test_mode {
Some(true) => format!("{REDIRECTION_SBX_URL}/v1/start"),
Some(false) | None => format!("{REDIRECTION_PROD_URL}/v1/start"),
};
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.transaction_id.clone(),
),
redirection_data: Box::new(Some(RedirectForm::Form {
endpoint: format!("{}/{}", redirection_link, response.transaction_id),
method: Method::Get,
form_fields: HashMap::new(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl<F>
TryFrom<ResponseRouterData<F, DatatransResponse, SetupMandateRequestData, PaymentsResponseData>>
for RouterData<F, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
DatatransResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
// zero auth doesn't support manual capture
let status = get_status(&item.response, true);
let response = match &item.response {
DatatransResponse::ErrorResponse(error) => Err(ErrorResponse {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
DatatransResponse::TransactionResponse(response) => {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
}
DatatransResponse::ThreeDSResponse(response) => {
let redirection_link = match item.data.test_mode {
Some(true) => format!("{REDIRECTION_SBX_URL}/v1/start"),
Some(false) | None => format!("{REDIRECTION_PROD_URL}/v1/start"),
};
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.transaction_id.clone(),
),
redirection_data: Box::new(Some(RedirectForm::Form {
endpoint: format!("{}/{}", redirection_link, response.transaction_id),
method: Method::Get,
form_fields: HashMap::new(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl<F> TryFrom<&DatatransRouterData<&types::RefundsRouterData<F>>> for DatatransRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DatatransRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
currency: item.router_data.request.currency,
refno: item.router_data.request.refund_id.clone(),
})
}
}
impl TryFrom<RefundsResponseRouterData<Execute, DatatransRefundsResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, DatatransRefundsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
DatatransRefundsResponse::Error(error) => Ok(Self {
response: Err(ErrorResponse {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
DatatransRefundsResponse::Success(response) => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: response.transaction_id,
refund_status: enums::RefundStatus::Success,
}),
..item.data
}),
}
}
}
impl TryFrom<RefundsResponseRouterData<RSync, DatatransSyncResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, DatatransSyncResponse>,
) -> Result<Self, Self::Error> {
let response = match item.response {
DatatransSyncResponse::Error(error) => Err(ErrorResponse {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
DatatransSyncResponse::Response(response) => Ok(RefundsResponseData {
connector_refund_id: response.transaction_id.to_string(),
refund_status: enums::RefundStatus::from(response),
}),
};
Ok(Self {
response,
..item.data
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<DatatransSyncResponse>>
for types::PaymentsSyncRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<DatatransSyncResponse>,
) -> Result<Self, Self::Error> {
match item.response {
DatatransSyncResponse::Error(error) => {
let response = Err(ErrorResponse {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
response,
..item.data
})
}
DatatransSyncResponse::Response(sync_response) => {
let status = enums::AttemptStatus::from(sync_response.clone());
let response = if status == enums::AttemptStatus::Failure {
let (code, message) = match sync_response.detail.fail {
Some(fail_details) => (
fail_details.reason.unwrap_or(NO_ERROR_CODE.to_string()),
fail_details.message.unwrap_or(NO_ERROR_MESSAGE.to_string()),
),
None => (NO_ERROR_CODE.to_string(), NO_ERROR_MESSAGE.to_string()),
};
Err(ErrorResponse {
code,
message: message.clone(),
reason: Some(message),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
let mandate_reference = sync_response
.card
.as_ref()
.and_then(|card| card.alias.as_ref())
.map(|alias| MandateReference {
connector_mandate_id: Some(alias.clone()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
sync_response.transaction_id.to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
}
}
impl TryFrom<&DatatransRouterData<&types::PaymentsCaptureRouterData>>
for DataPaymentCaptureRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DatatransRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
currency: item.router_data.request.currency,
refno: item.router_data.connector_request_reference_id.clone(),
})
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<DataTransCaptureResponse>>
for types::PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<DataTransCaptureResponse>,
) -> Result<Self, Self::Error> {
let status = match item.response {
DataTransCaptureResponse::Error(error) => {
if error.message == *TRANSACTION_ALREADY_SETTLED {
common_enums::AttemptStatus::Charged
} else {
common_enums::AttemptStatus::Failure
}
}
// Datatrans http code 204 implies Successful Capture
//https://api-reference.datatrans.ch/#tag/v1transactions/operation/settle
DataTransCaptureResponse::Empty => {
if item.http_code == 204 {
common_enums::AttemptStatus::Charged
} else {
common_enums::AttemptStatus::Failure
}
}
};
Ok(Self {
status,
..item.data
})
}
}
impl TryFrom<PaymentsCancelResponseRouterData<DataTransCancelResponse>>
for types::PaymentsCancelRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<DataTransCancelResponse>,
) -> Result<Self, Self::Error> {
let status = match item.response {
// Datatrans http code 204 implies Successful Cancellation
//https://api-reference.datatrans.ch/#tag/v1transactions/operation/cancel
DataTransCancelResponse::Empty => {
if item.http_code == 204 {
common_enums::AttemptStatus::Voided
} else {
common_enums::AttemptStatus::Failure
}
}
DataTransCancelResponse::Error(error) => {
if error.message == *TRANSACTION_ALREADY_CANCELLED {
common_enums::AttemptStatus::Voided
} else {
common_enums::AttemptStatus::Failure
}
}
};
Ok(Self {
status,
..item.data
})
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6890
}
|
large_file_-3454312787043720823
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
</path>
<file>
use std::str::FromStr;
use common_enums::enums::CaptureMethod;
use common_utils::types::MinorUnit;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{PaymentsCancelData, ResponseId},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefreshTokenRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
get_unimplemented_payment_method_error_message, CardData, RouterData as OtherRouterData,
},
};
pub struct JpmorganRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for JpmorganRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct JpmorganAuthUpdateRequest {
pub grant_type: String,
pub scope: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct JpmorganAuthUpdateResponse {
pub access_token: Secret<String>,
pub scope: String,
pub token_type: String,
pub expires_in: i64,
}
impl TryFrom<&RefreshTokenRouterData> for JpmorganAuthUpdateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(_item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
Ok(Self {
grant_type: String::from("client_credentials"),
scope: String::from("jpm:payments:sandbox"),
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, JpmorganAuthUpdateResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, JpmorganAuthUpdateResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPaymentsRequest {
capture_method: CapMethod,
amount: MinorUnit,
currency: common_enums::Currency,
merchant: JpmorganMerchant,
payment_method_type: JpmorganPaymentMethodType,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCard {
account_number: Secret<String>,
expiry: Expiry,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPaymentMethodType {
card: JpmorganCard,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Expiry {
month: Secret<i32>,
year: Secret<i32>,
}
#[derive(Serialize, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganMerchantSoftware {
company_name: Secret<String>,
product_name: Secret<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganMerchant {
merchant_software: JpmorganMerchantSoftware,
}
fn map_capture_method(
capture_method: CaptureMethod,
) -> Result<CapMethod, error_stack::Report<errors::ConnectorError>> {
match capture_method {
CaptureMethod::Automatic => Ok(CapMethod::Now),
CaptureMethod::Manual => Ok(CapMethod::Manual),
CaptureMethod::Scheduled
| CaptureMethod::ManualMultiple
| CaptureMethod::SequentialAutomatic => {
Err(errors::ConnectorError::NotImplemented("Capture Method".to_string()).into())
}
}
}
impl TryFrom<&JpmorganRouterData<&PaymentsAuthorizeRouterData>> for JpmorganPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &JpmorganRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
if item.router_data.is_three_ds() {
return Err(errors::ConnectorError::NotSupported {
message: "3DS payments".to_string(),
connector: "Jpmorgan",
}
.into());
}
let capture_method =
map_capture_method(item.router_data.request.capture_method.unwrap_or_default());
let merchant_software = JpmorganMerchantSoftware {
company_name: String::from("JPMC").into(),
product_name: String::from("Hyperswitch").into(),
};
let merchant = JpmorganMerchant { merchant_software };
let expiry: Expiry = Expiry {
month: Secret::new(
req_card
.card_exp_month
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
),
year: req_card.get_expiry_year_as_4_digit_i32()?,
};
let account_number = Secret::new(req_card.card_number.to_string());
let card = JpmorganCard {
account_number,
expiry,
};
let payment_method_type = JpmorganPaymentMethodType { card };
Ok(Self {
capture_method: capture_method?,
currency: item.router_data.request.currency,
amount: item.amount,
merchant,
payment_method_type,
})
}
PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("jpmorgan"),
)
.into()),
}
}
}
//JP Morgan uses access token only due to which we aren't reading the fields in this struct
#[derive(Debug)]
pub struct JpmorganAuthType {
pub(super) _api_key: Secret<String>,
pub(super) _key1: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for JpmorganAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
_api_key: api_key.to_owned(),
_key1: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum JpmorganTransactionStatus {
Success,
Denied,
Error,
}
#[derive(Default, Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum JpmorganTransactionState {
Closed,
Authorized,
Voided,
#[default]
Pending,
Declined,
Error,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPaymentsResponse {
transaction_id: String,
request_id: String,
transaction_state: JpmorganTransactionState,
response_status: String,
response_code: String,
response_message: String,
payment_method_type: PaymentMethodType,
capture_method: Option<CapMethod>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Merchant {
merchant_id: Option<String>,
merchant_software: JpmorganMerchantSoftware,
merchant_category_code: Option<String>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethodType {
card: Option<Card>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
expiry: Option<ExpiryResponse>,
card_type: Option<Secret<String>>,
card_type_name: Option<Secret<String>>,
masked_account_number: Option<Secret<String>>,
card_type_indicators: Option<CardTypeIndicators>,
network_response: Option<NetworkResponse>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkResponse {
address_verification_result: Option<Secret<String>>,
address_verification_result_code: Option<Secret<String>>,
card_verification_result_code: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExpiryResponse {
month: Option<Secret<i32>>,
year: Option<Secret<i32>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardTypeIndicators {
issuance_country_code: Option<Secret<String>>,
is_durbin_regulated: Option<bool>,
card_product_types: Secret<Vec<String>>,
}
pub fn attempt_status_from_transaction_state(
transaction_state: JpmorganTransactionState,
) -> common_enums::AttemptStatus {
match transaction_state {
JpmorganTransactionState::Authorized => common_enums::AttemptStatus::Authorized,
JpmorganTransactionState::Closed => common_enums::AttemptStatus::Charged,
JpmorganTransactionState::Declined | JpmorganTransactionState::Error => {
common_enums::AttemptStatus::Failure
}
JpmorganTransactionState::Pending => common_enums::AttemptStatus::Pending,
JpmorganTransactionState::Voided => common_enums::AttemptStatus::Voided,
}
}
impl<F, T> TryFrom<ResponseRouterData<F, JpmorganPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, JpmorganPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction_state = match item.response.transaction_state {
JpmorganTransactionState::Closed => match item.response.capture_method {
Some(CapMethod::Now) => JpmorganTransactionState::Closed,
_ => JpmorganTransactionState::Authorized,
},
JpmorganTransactionState::Authorized => JpmorganTransactionState::Authorized,
JpmorganTransactionState::Voided => JpmorganTransactionState::Voided,
JpmorganTransactionState::Pending => JpmorganTransactionState::Pending,
JpmorganTransactionState::Declined => JpmorganTransactionState::Declined,
JpmorganTransactionState::Error => JpmorganTransactionState::Error,
};
let status = attempt_status_from_transaction_state(transaction_state);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCaptureRequest {
capture_method: Option<CapMethod>,
amount: MinorUnit,
currency: Option<common_enums::Currency>,
}
#[derive(Debug, Default, Copy, Serialize, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum CapMethod {
#[default]
Now,
Delayed,
Manual,
}
impl TryFrom<&JpmorganRouterData<&PaymentsCaptureRouterData>> for JpmorganCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &JpmorganRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let capture_method = Some(map_capture_method(
item.router_data.request.capture_method.unwrap_or_default(),
)?);
Ok(Self {
capture_method,
amount: item.amount,
currency: Some(item.router_data.request.currency),
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCaptureResponse {
pub transaction_id: String,
pub request_id: String,
pub transaction_state: JpmorganTransactionState,
pub response_status: JpmorganTransactionStatus,
pub response_code: String,
pub response_message: String,
pub payment_method_type: PaymentMethodTypeCapRes,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethodTypeCapRes {
pub card: Option<CardCapRes>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardCapRes {
pub card_type: Option<Secret<String>>,
pub card_type_name: Option<Secret<String>>,
unmasked_account_number: Option<Secret<String>>,
}
impl<F, T> TryFrom<ResponseRouterData<F, JpmorganCaptureResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, JpmorganCaptureResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = attempt_status_from_transaction_state(item.response.transaction_state);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPSyncResponse {
transaction_id: String,
transaction_state: JpmorganTransactionState,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum JpmorganResponseStatus {
Success,
Denied,
Error,
}
impl<F, PaymentsSyncData>
TryFrom<ResponseRouterData<F, JpmorganPSyncResponse, PaymentsSyncData, PaymentsResponseData>>
for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, JpmorganPSyncResponse, PaymentsSyncData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = attempt_status_from_transaction_state(item.response.transaction_state);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TransactionData {
payment_type: Option<Secret<String>>,
status_code: Secret<i32>,
txn_secret: Option<Secret<String>>,
tid: Option<Secret<i64>>,
test_mode: Option<Secret<i8>>,
status: Option<JpmorganTransactionStatus>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganRefundRequest {
pub merchant: MerchantRefundReq,
pub amount: MinorUnit,
pub currency: common_enums::Currency,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantRefundReq {
pub merchant_software: JpmorganMerchantSoftware,
}
impl<F> TryFrom<&JpmorganRouterData<&RefundsRouterData<F>>> for JpmorganRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &JpmorganRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let merchant_software = JpmorganMerchantSoftware {
company_name: String::from("JPMC").into(),
product_name: String::from("Hyperswitch").into(),
};
let merchant = MerchantRefundReq { merchant_software };
let amount = item.amount;
let currency = item.router_data.request.currency;
Ok(Self {
merchant,
amount,
currency,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganRefundResponse {
pub transaction_id: Option<String>,
pub request_id: String,
pub transaction_state: JpmorganTransactionState,
pub amount: MinorUnit,
pub currency: common_enums::Currency,
pub response_status: JpmorganResponseStatus,
pub response_code: String,
pub response_message: String,
pub transaction_reference_id: Option<String>,
pub remaining_refundable_amount: Option<i64>,
}
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for common_enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
}
}
}
impl From<(JpmorganResponseStatus, JpmorganTransactionState)> for RefundStatus {
fn from(
(response_status, transaction_state): (JpmorganResponseStatus, JpmorganTransactionState),
) -> Self {
match response_status {
JpmorganResponseStatus::Success => match transaction_state {
JpmorganTransactionState::Voided | JpmorganTransactionState::Closed => {
Self::Succeeded
}
JpmorganTransactionState::Declined | JpmorganTransactionState::Error => {
Self::Failed
}
JpmorganTransactionState::Pending | JpmorganTransactionState::Authorized => {
Self::Processing
}
},
JpmorganResponseStatus::Denied | JpmorganResponseStatus::Error => Self::Failed,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, JpmorganRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, JpmorganRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item
.response
.transaction_id
.clone()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?,
refund_status: RefundStatus::from((
item.response.response_status,
item.response.transaction_state,
))
.into(),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganRefundSyncResponse {
transaction_id: String,
request_id: String,
transaction_state: JpmorganTransactionState,
amount: MinorUnit,
currency: common_enums::Currency,
response_status: JpmorganResponseStatus,
response_code: String,
}
impl TryFrom<RefundsResponseRouterData<RSync, JpmorganRefundSyncResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, JpmorganRefundSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id.clone(),
refund_status: RefundStatus::from((
item.response.response_status,
item.response.transaction_state,
))
.into(),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ReversalReason {
NoResponse,
LateResponse,
UnableToDeliver,
CardDeclined,
MacNotVerified,
MacSyncError,
ZekSyncError,
SystemMalfunction,
SuspectedFraud,
}
impl FromStr for ReversalReason {
type Err = error_stack::Report<errors::ConnectorError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_uppercase().as_str() {
"NO_RESPONSE" => Ok(Self::NoResponse),
"LATE_RESPONSE" => Ok(Self::LateResponse),
"UNABLE_TO_DELIVER" => Ok(Self::UnableToDeliver),
"CARD_DECLINED" => Ok(Self::CardDeclined),
"MAC_NOT_VERIFIED" => Ok(Self::MacNotVerified),
"MAC_SYNC_ERROR" => Ok(Self::MacSyncError),
"ZEK_SYNC_ERROR" => Ok(Self::ZekSyncError),
"SYSTEM_MALFUNCTION" => Ok(Self::SystemMalfunction),
"SUSPECTED_FRAUD" => Ok(Self::SuspectedFraud),
_ => Err(report!(errors::ConnectorError::InvalidDataFormat {
field_name: "cancellation_reason",
})),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCancelRequest {
pub amount: Option<i64>,
pub is_void: Option<bool>,
pub reversal_reason: Option<ReversalReason>,
}
impl TryFrom<JpmorganRouterData<&PaymentsCancelRouterData>> for JpmorganCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: JpmorganRouterData<&PaymentsCancelRouterData>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.router_data.request.amount,
is_void: Some(true),
reversal_reason: item
.router_data
.request
.cancellation_reason
.as_ref()
.map(|reason| ReversalReason::from_str(reason))
.transpose()?,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCancelResponse {
transaction_id: String,
request_id: String,
response_status: JpmorganResponseStatus,
response_code: String,
response_message: String,
payment_method_type: JpmorganPaymentMethodTypeCancelResponse,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPaymentMethodTypeCancelResponse {
pub card: CardCancelResponse,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardCancelResponse {
pub card_type: Secret<String>,
pub card_type_name: Secret<String>,
}
impl<F>
TryFrom<ResponseRouterData<F, JpmorganCancelResponse, PaymentsCancelData, PaymentsResponseData>>
for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
JpmorganCancelResponse,
PaymentsCancelData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = match item.response.response_status {
JpmorganResponseStatus::Success => common_enums::AttemptStatus::Voided,
JpmorganResponseStatus::Denied | JpmorganResponseStatus::Error => {
common_enums::AttemptStatus::Failure
}
};
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganValidationErrors {
pub code: Option<String>,
pub message: Option<String>,
pub entity: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganErrorInformation {
pub code: Option<String>,
pub message: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganErrorResponse {
pub response_status: JpmorganTransactionStatus,
pub response_code: String,
pub response_message: Option<String>,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5776
}
|
large_file_-4775291050014371800
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
</path>
<file>
use std::collections::HashMap;
use api_models::{
payments::{
AmountInfo, ApplePayPaymentRequest, ApplePaySessionResponse,
ApplepayCombinedSessionTokenData, ApplepaySessionTokenData, ApplepaySessionTokenMetadata,
ApplepaySessionTokenResponse, NextActionCall, NoThirdPartySdkSessionResponse,
SdkNextAction, SessionToken,
},
webhooks::IncomingWebhookEvent,
};
use base64::Engine;
use common_enums::{enums, CountryAlpha2};
use common_utils::{
consts::{APPLEPAY_VALIDATION_URL, BASE64_ENGINE},
errors::CustomResult,
ext_traits::{ByteSliceExt, Encode, OptionExt, StringExt, ValueExt},
pii::Email,
types::{FloatMajorUnit, StringMajorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
address::AddressDetails,
payment_method_data::{self, PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
types::{PaymentsSessionResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, ApplePay, CardData as _, ForeignTryFrom,
PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, RouterData as _,
},
};
const DISPLAY_METADATA: &str = "Y";
#[derive(Debug, Serialize)]
pub struct BluesnapRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(StringMajorUnit, T)> for BluesnapRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (StringMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapPaymentsRequest {
amount: StringMajorUnit,
#[serde(flatten)]
payment_method: PaymentMethodDetails,
currency: enums::Currency,
card_transaction_type: BluesnapTxnType,
transaction_fraud_info: Option<TransactionFraudInfo>,
card_holder_info: Option<BluesnapCardHolderInfo>,
merchant_transaction_id: Option<String>,
transaction_meta_data: Option<BluesnapMetadata>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapMetadata {
meta_data: Vec<RequestMetadata>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RequestMetadata {
meta_key: Option<String>,
meta_value: Option<String>,
is_visible: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapCardHolderInfo {
first_name: Secret<String>,
last_name: Secret<String>,
email: Email,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionFraudInfo {
fraud_session_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapCreateWalletToken {
wallet_type: String,
validation_url: Secret<String>,
domain_name: String,
display_name: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapThreeDSecureInfo {
three_d_secure_reference_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum PaymentMethodDetails {
CreditCard(Card),
Wallet(BluesnapWallet),
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
card_number: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
security_code: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapWallet {
wallet_type: BluesnapWalletTypes,
encoded_payment_token: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapGooglePayObject {
payment_method_data: utils::GooglePayWalletData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BluesnapWalletTypes {
GooglePay,
ApplePay,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct EncodedPaymentToken {
billing_contact: BillingDetails,
token: ApplepayPaymentData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BillingDetails {
country_code: Option<CountryAlpha2>,
address_lines: Option<Vec<Secret<String>>>,
family_name: Option<Secret<String>>,
given_name: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ApplepayPaymentData {
payment_data: ApplePayEncodedPaymentData,
payment_method: ApplepayPaymentMethod,
transaction_identifier: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ApplepayPaymentMethod {
display_name: String,
network: String,
#[serde(rename = "type")]
pm_type: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ApplePayEncodedPaymentData {
data: String,
header: Option<ApplepayHeader>,
signature: String,
version: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ApplepayHeader {
ephemeral_public_key: Secret<String>,
public_key_hash: Secret<String>,
transaction_id: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BluesnapConnectorMetaData {
pub merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapPaymentsTokenRequest {
cc_number: cards::CardNumber,
exp_date: Secret<String>,
}
impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>>
for BluesnapPaymentsTokenRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BluesnapRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => Ok(Self {
cc_number: ccard.card_number.clone(),
exp_date: ccard.get_expiry_date_as_mmyyyy("/"),
}),
PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
"Selected payment method via Token flow through bluesnap".to_string(),
)
.into())
}
}
}
}
impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for BluesnapPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BluesnapRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let auth_mode = match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual) => BluesnapTxnType::AuthOnly,
_ => BluesnapTxnType::AuthCapture,
};
let transaction_meta_data =
item.router_data
.request
.metadata
.as_ref()
.map(|metadata| BluesnapMetadata {
meta_data: convert_metadata_to_request_metadata(metadata.to_owned()),
});
let (payment_method, card_holder_info) = match item
.router_data
.request
.payment_method_data
.clone()
{
PaymentMethodData::Card(ref ccard) => Ok((
PaymentMethodDetails::CreditCard(Card {
card_number: ccard.card_number.clone(),
expiration_month: ccard.card_exp_month.clone(),
expiration_year: ccard.get_expiry_year_4_digit(),
security_code: ccard.card_cvc.clone(),
}),
get_card_holder_info(
item.router_data.get_billing_address()?,
item.router_data.request.get_email()?,
)?,
)),
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::GooglePay(payment_method_data) => {
let gpay_ecrypted_object = BluesnapGooglePayObject {
payment_method_data: utils::GooglePayWalletData::try_from(
payment_method_data,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
}
.encode_to_string_of_json()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok((
PaymentMethodDetails::Wallet(BluesnapWallet {
wallet_type: BluesnapWalletTypes::GooglePay,
encoded_payment_token: Secret::new(
BASE64_ENGINE.encode(gpay_ecrypted_object),
),
}),
None,
))
}
WalletData::ApplePay(payment_method_data) => {
let apple_pay_payment_data =
payment_method_data.get_applepay_decoded_payment_data()?;
let apple_pay_payment_data: ApplePayEncodedPaymentData = apple_pay_payment_data
.expose()
.as_bytes()
.parse_struct("ApplePayEncodedPaymentData")
.change_context(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?;
let billing = item.router_data.get_billing()?.to_owned();
let billing_address = billing
.address
.get_required_value("billing_address")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "billing",
})?;
let mut address = Vec::new();
if let Some(add) = billing_address.line1.to_owned() {
address.push(add)
}
if let Some(add) = billing_address.line2.to_owned() {
address.push(add)
}
if let Some(add) = billing_address.line3.to_owned() {
address.push(add)
}
let apple_pay_object = EncodedPaymentToken {
token: ApplepayPaymentData {
payment_data: apple_pay_payment_data,
payment_method: payment_method_data.payment_method.to_owned().into(),
transaction_identifier: payment_method_data.transaction_identifier,
},
billing_contact: BillingDetails {
country_code: billing_address.country,
address_lines: Some(address),
family_name: billing_address.last_name.to_owned(),
given_name: billing_address.first_name.to_owned(),
postal_code: billing_address.zip,
},
}
.encode_to_string_of_json()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok((
PaymentMethodDetails::Wallet(BluesnapWallet {
wallet_type: BluesnapWalletTypes::ApplePay,
encoded_payment_token: Secret::new(
BASE64_ENGINE.encode(apple_pay_object),
),
}),
get_card_holder_info(
item.router_data.get_billing_address()?,
item.router_data.request.get_email()?,
)?,
))
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::WeChatPayQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("bluesnap"),
)),
},
PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("bluesnap"),
))
}
}?;
Ok(Self {
amount: item.amount.to_owned(),
payment_method,
currency: item.router_data.request.currency,
card_transaction_type: auth_mode,
transaction_fraud_info: Some(TransactionFraudInfo {
fraud_session_id: item.router_data.payment_id.clone(),
}),
card_holder_info,
merchant_transaction_id: Some(item.router_data.connector_request_reference_id.clone()),
transaction_meta_data,
})
}
}
impl From<payment_method_data::ApplepayPaymentMethod> for ApplepayPaymentMethod {
fn from(item: payment_method_data::ApplepayPaymentMethod) -> Self {
Self {
display_name: item.display_name,
network: item.network,
pm_type: item.pm_type,
}
}
}
impl TryFrom<&types::PaymentsSessionRouterData> for BluesnapCreateWalletToken {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsSessionRouterData) -> Result<Self, Self::Error> {
let apple_pay_metadata = item.get_connector_meta()?.expose();
let applepay_metadata = apple_pay_metadata
.clone()
.parse_value::<ApplepayCombinedSessionTokenData>("ApplepayCombinedSessionTokenData")
.map(|combined_metadata| {
ApplepaySessionTokenMetadata::ApplePayCombined(combined_metadata.apple_pay_combined)
})
.or_else(|_| {
apple_pay_metadata
.parse_value::<ApplepaySessionTokenData>("ApplepaySessionTokenData")
.map(|old_metadata| {
ApplepaySessionTokenMetadata::ApplePay(old_metadata.apple_pay)
})
})
.change_context(errors::ConnectorError::ParsingFailed)?;
let session_token_data = match applepay_metadata {
ApplepaySessionTokenMetadata::ApplePay(apple_pay_data) => {
Ok(apple_pay_data.session_token_data)
}
ApplepaySessionTokenMetadata::ApplePayCombined(_apple_pay_combined_data) => {
Err(errors::ConnectorError::FlowNotSupported {
flow: "apple pay combined".to_string(),
connector: "bluesnap".to_string(),
})
}
}?;
let domain_name = session_token_data.initiative_context.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "apple pay initiative_context",
},
)?;
Ok(Self {
wallet_type: "APPLE_PAY".to_string(),
validation_url: APPLEPAY_VALIDATION_URL.to_string().into(),
domain_name,
display_name: Some(session_token_data.display_name),
})
}
}
impl
ForeignTryFrom<(
PaymentsSessionResponseRouterData<BluesnapWalletTokenResponse>,
StringMajorUnit,
)> for types::PaymentsSessionRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, apple_pay_amount): (
PaymentsSessionResponseRouterData<BluesnapWalletTokenResponse>,
StringMajorUnit,
),
) -> Result<Self, Self::Error> {
let response = &item.response;
let wallet_token = BASE64_ENGINE
.decode(response.wallet_token.clone().expose())
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let session_response: NoThirdPartySdkSessionResponse = wallet_token
.parse_struct("NoThirdPartySdkSessionResponse")
.change_context(errors::ConnectorError::ParsingFailed)?;
let metadata = item.data.get_connector_meta()?.expose();
let applepay_metadata = metadata
.clone()
.parse_value::<ApplepayCombinedSessionTokenData>("ApplepayCombinedSessionTokenData")
.map(|combined_metadata| {
ApplepaySessionTokenMetadata::ApplePayCombined(combined_metadata.apple_pay_combined)
})
.or_else(|_| {
metadata
.parse_value::<ApplepaySessionTokenData>("ApplepaySessionTokenData")
.map(|old_metadata| {
ApplepaySessionTokenMetadata::ApplePay(old_metadata.apple_pay)
})
})
.change_context(errors::ConnectorError::ParsingFailed)?;
let (payment_request_data, session_token_data) = match applepay_metadata {
ApplepaySessionTokenMetadata::ApplePayCombined(_apple_pay_combined) => {
Err(errors::ConnectorError::FlowNotSupported {
flow: "apple pay combined".to_string(),
connector: "bluesnap".to_string(),
})
}
ApplepaySessionTokenMetadata::ApplePay(apple_pay) => {
Ok((apple_pay.payment_request_data, apple_pay.session_token_data))
}
}?;
Ok(Self {
response: Ok(PaymentsResponseData::SessionResponse {
session_token: SessionToken::ApplePay(Box::new(ApplepaySessionTokenResponse {
session_token_data: Some(ApplePaySessionResponse::NoThirdPartySdk(
session_response,
)),
payment_request_data: Some(ApplePayPaymentRequest {
country_code: item.data.get_billing_country()?,
currency_code: item.data.request.currency,
total: AmountInfo {
label: payment_request_data.label,
total_type: Some("final".to_string()),
amount: apple_pay_amount,
},
merchant_capabilities: Some(payment_request_data.merchant_capabilities),
supported_networks: Some(payment_request_data.supported_networks),
merchant_identifier: Some(session_token_data.merchant_identifier),
required_billing_contact_fields: None,
required_shipping_contact_fields: None,
recurring_payment_request: None,
}),
connector: "bluesnap".to_string(),
delayed_session_token: false,
sdk_next_action: {
SdkNextAction {
next_action: NextActionCall::Confirm,
}
},
connector_reference_id: None,
connector_sdk_public_key: None,
connector_merchant_id: None,
})),
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapCompletePaymentsRequest {
amount: StringMajorUnit,
currency: enums::Currency,
card_transaction_type: BluesnapTxnType,
pf_token: Secret<String>,
three_d_secure: Option<BluesnapThreeDSecureInfo>,
transaction_fraud_info: Option<TransactionFraudInfo>,
card_holder_info: Option<BluesnapCardHolderInfo>,
merchant_transaction_id: Option<String>,
transaction_meta_data: Option<BluesnapMetadata>,
}
impl TryFrom<&BluesnapRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
for BluesnapCompletePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BluesnapRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let redirection_response: BluesnapRedirectionResponse = item
.router_data
.request
.redirect_response
.as_ref()
.and_then(|res| res.payload.to_owned())
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
})?
.parse_value("BluesnapRedirectionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let transaction_meta_data =
item.router_data
.request
.metadata
.as_ref()
.map(|metadata| BluesnapMetadata {
meta_data: convert_metadata_to_request_metadata(metadata.to_owned()),
});
let token = item
.router_data
.request
.redirect_response
.clone()
.and_then(|res| res.params.to_owned())
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.params",
})?
.peek()
.split_once('=')
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.params.paymentToken",
})?
.1
.to_string();
let redirection_result: BluesnapThreeDsResult = redirection_response
.authentication_response
.parse_struct("BluesnapThreeDsResult")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let auth_mode = match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual) => BluesnapTxnType::AuthOnly,
_ => BluesnapTxnType::AuthCapture,
};
Ok(Self {
amount: item.amount.to_owned(),
currency: item.router_data.request.currency,
card_transaction_type: auth_mode,
three_d_secure: Some(BluesnapThreeDSecureInfo {
three_d_secure_reference_id: redirection_result
.three_d_secure
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "three_d_secure_reference_id",
})?
.three_d_secure_reference_id,
}),
transaction_fraud_info: Some(TransactionFraudInfo {
fraud_session_id: item.router_data.payment_id.clone(),
}),
card_holder_info: get_card_holder_info(
item.router_data.get_billing_address()?,
item.router_data.request.get_email()?,
)?,
merchant_transaction_id: Some(item.router_data.connector_request_reference_id.clone()),
pf_token: Secret::new(token),
transaction_meta_data,
})
}
}
#[derive(Debug, Deserialize)]
pub struct BluesnapRedirectionResponse {
pub authentication_response: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapThreeDsResult {
three_d_secure: Option<BluesnapThreeDsReference>,
pub status: String,
pub code: Option<String>,
pub info: Option<RedirectErrorMessage>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RedirectErrorMessage {
pub errors: Option<Vec<String>>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapThreeDsReference {
three_d_secure_reference_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapVoidRequest {
card_transaction_type: BluesnapTxnType,
transaction_id: String,
}
impl TryFrom<&types::PaymentsCancelRouterData> for BluesnapVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let card_transaction_type = BluesnapTxnType::AuthReversal;
let transaction_id = item.request.connector_transaction_id.to_string();
Ok(Self {
card_transaction_type,
transaction_id,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapCaptureRequest {
card_transaction_type: BluesnapTxnType,
transaction_id: String,
amount: Option<StringMajorUnit>,
}
impl TryFrom<&BluesnapRouterData<&types::PaymentsCaptureRouterData>> for BluesnapCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BluesnapRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let card_transaction_type = BluesnapTxnType::Capture;
let transaction_id = item
.router_data
.request
.connector_transaction_id
.to_string();
Ok(Self {
card_transaction_type,
transaction_id,
amount: Some(item.amount.to_owned()),
})
}
}
// Auth Struct
pub struct BluesnapAuthType {
pub(super) api_key: Secret<String>,
pub(super) key1: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BluesnapAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
api_key: api_key.to_owned(),
key1: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BluesnapTxnType {
AuthOnly,
AuthCapture,
AuthReversal,
Capture,
Refund,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum BluesnapProcessingStatus {
#[serde(alias = "success")]
Success,
#[default]
#[serde(alias = "pending")]
Pending,
#[serde(alias = "fail")]
Fail,
#[serde(alias = "pending_merchant_review")]
PendingMerchantReview,
}
impl ForeignTryFrom<(BluesnapTxnType, BluesnapProcessingStatus)> for enums::AttemptStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
item: (BluesnapTxnType, BluesnapProcessingStatus),
) -> Result<Self, Self::Error> {
let (item_txn_status, item_processing_status) = item;
Ok(match item_processing_status {
BluesnapProcessingStatus::Success => match item_txn_status {
BluesnapTxnType::AuthOnly => Self::Authorized,
BluesnapTxnType::AuthReversal => Self::Voided,
BluesnapTxnType::AuthCapture | BluesnapTxnType::Capture => Self::Charged,
BluesnapTxnType::Refund => Self::Charged,
},
BluesnapProcessingStatus::Pending | BluesnapProcessingStatus::PendingMerchantReview => {
Self::Pending
}
BluesnapProcessingStatus::Fail => Self::Failure,
})
}
}
impl From<BluesnapProcessingStatus> for enums::RefundStatus {
fn from(item: BluesnapProcessingStatus) -> Self {
match item {
BluesnapProcessingStatus::Success => Self::Success,
BluesnapProcessingStatus::Pending => Self::Pending,
BluesnapProcessingStatus::PendingMerchantReview => Self::ManualReview,
BluesnapProcessingStatus::Fail => Self::Failure,
}
}
}
impl From<BluesnapRefundStatus> for enums::RefundStatus {
fn from(item: BluesnapRefundStatus) -> Self {
match item {
BluesnapRefundStatus::Success => Self::Success,
BluesnapRefundStatus::Pending => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapPaymentsResponse {
pub processing_info: ProcessingInfoResponse,
pub transaction_id: String,
pub card_transaction_type: BluesnapTxnType,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapWalletTokenResponse {
wallet_type: String,
wallet_token: Secret<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Refund {
refund_transaction_id: String,
amount: StringMajorUnit,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingInfoResponse {
pub processing_status: BluesnapProcessingStatus,
pub authorization_code: Option<String>,
pub network_transaction_id: Option<Secret<String>>,
}
impl<F, T> TryFrom<ResponseRouterData<F, BluesnapPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BluesnapPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::foreign_try_from((
item.response.card_transaction_type,
item.response.processing_info.processing_status,
))?,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct BluesnapRefundRequest {
amount: Option<StringMajorUnit>,
reason: Option<String>,
}
impl<F> TryFrom<&BluesnapRouterData<&types::RefundsRouterData<F>>> for BluesnapRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BluesnapRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
reason: item.router_data.request.reason.clone(),
amount: Some(item.amount.to_owned()),
})
}
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum BluesnapRefundStatus {
Success,
#[default]
Pending,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
refund_transaction_id: i32,
refund_status: BluesnapRefundStatus,
}
impl TryFrom<RefundsResponseRouterData<RSync, BluesnapPaymentsResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, BluesnapPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id.clone(),
refund_status: enums::RefundStatus::from(
item.response.processing_info.processing_status,
),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund_transaction_id.to_string(),
refund_status: enums::RefundStatus::from(item.response.refund_status),
}),
..item.data
})
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapWebhookBody {
pub merchant_transaction_id: String,
pub reference_number: String,
pub transaction_type: BluesnapWebhookEvents,
pub reversal_ref_num: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapWebhookObjectEventType {
transaction_type: BluesnapWebhookEvents,
cb_status: Option<BluesnapChargebackStatus>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BluesnapChargebackStatus {
#[serde(alias = "New")]
New,
#[serde(alias = "Working")]
Working,
#[serde(alias = "Closed")]
Closed,
#[serde(alias = "Completed_Lost")]
CompletedLost,
#[serde(alias = "Completed_Pending")]
CompletedPending,
#[serde(alias = "Completed_Won")]
CompletedWon,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BluesnapWebhookEvents {
Decline,
CcChargeFailed,
Charge,
Refund,
Chargeback,
ChargebackStatusChanged,
#[serde(other)]
Unknown,
}
impl TryFrom<BluesnapWebhookObjectEventType> for IncomingWebhookEvent {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(details: BluesnapWebhookObjectEventType) -> Result<Self, Self::Error> {
match details.transaction_type {
BluesnapWebhookEvents::Decline | BluesnapWebhookEvents::CcChargeFailed => {
Ok(Self::PaymentIntentFailure)
}
BluesnapWebhookEvents::Charge => Ok(Self::PaymentIntentSuccess),
BluesnapWebhookEvents::Refund => Ok(Self::RefundSuccess),
BluesnapWebhookEvents::Chargeback | BluesnapWebhookEvents::ChargebackStatusChanged => {
match details
.cb_status
.ok_or(errors::ConnectorError::WebhookEventTypeNotFound)?
{
BluesnapChargebackStatus::New | BluesnapChargebackStatus::Working => {
Ok(Self::DisputeOpened)
}
BluesnapChargebackStatus::Closed => Ok(Self::DisputeExpired),
BluesnapChargebackStatus::CompletedLost => Ok(Self::DisputeLost),
BluesnapChargebackStatus::CompletedPending => Ok(Self::DisputeChallenged),
BluesnapChargebackStatus::CompletedWon => Ok(Self::DisputeWon),
}
}
BluesnapWebhookEvents::Unknown => Ok(Self::EventNotSupported),
}
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapDisputeWebhookBody {
pub invoice_charge_amount: FloatMajorUnit,
pub currency: enums::Currency,
pub reversal_reason: Option<String>,
pub reversal_ref_num: String,
pub cb_status: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapWebhookObjectResource {
reference_number: String,
transaction_type: BluesnapWebhookEvents,
reversal_ref_num: Option<String>,
}
impl TryFrom<BluesnapWebhookObjectResource> for Value {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(details: BluesnapWebhookObjectResource) -> Result<Self, Self::Error> {
let (card_transaction_type, processing_status, transaction_id) = match details
.transaction_type
{
BluesnapWebhookEvents::Decline | BluesnapWebhookEvents::CcChargeFailed => Ok((
BluesnapTxnType::Capture,
BluesnapProcessingStatus::Fail,
details.reference_number,
)),
BluesnapWebhookEvents::Charge => Ok((
BluesnapTxnType::Capture,
BluesnapProcessingStatus::Success,
details.reference_number,
)),
BluesnapWebhookEvents::Chargeback | BluesnapWebhookEvents::ChargebackStatusChanged => {
//It won't be consumed in dispute flow, so currently does not hold any significance
return serde_json::to_value(details)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed);
}
BluesnapWebhookEvents::Refund => Ok((
BluesnapTxnType::Refund,
BluesnapProcessingStatus::Success,
details
.reversal_ref_num
.ok_or(errors::ConnectorError::WebhookResourceObjectNotFound)?,
)),
BluesnapWebhookEvents::Unknown => {
Err(errors::ConnectorError::WebhookResourceObjectNotFound)
}
}?;
let sync_struct = BluesnapPaymentsResponse {
processing_info: ProcessingInfoResponse {
processing_status,
authorization_code: None,
network_transaction_id: None,
},
transaction_id,
card_transaction_type,
};
serde_json::to_value(sync_struct)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorDetails {
pub code: String,
pub description: String,
pub error_name: Option<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapErrorResponse {
pub message: Vec<ErrorDetails>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapAuthErrorResponse {
pub error_code: String,
pub error_description: String,
pub error_name: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BluesnapErrors {
Payment(BluesnapErrorResponse),
Auth(BluesnapAuthErrorResponse),
General(String),
}
fn get_card_holder_info(
address: &AddressDetails,
email: Email,
) -> CustomResult<Option<BluesnapCardHolderInfo>, errors::ConnectorError> {
let first_name = address.get_first_name()?;
Ok(Some(BluesnapCardHolderInfo {
first_name: first_name.clone(),
last_name: address.get_last_name().unwrap_or(first_name).clone(),
email,
}))
}
impl From<ErrorDetails> for utils::ErrorCodeAndMessage {
fn from(error: ErrorDetails) -> Self {
Self {
error_code: error.code.to_string(),
error_message: error.error_name.unwrap_or(error.code),
}
}
}
fn convert_metadata_to_request_metadata(metadata: Value) -> Vec<RequestMetadata> {
let hashmap: HashMap<Option<String>, Option<Value>> =
serde_json::from_str(&metadata.to_string()).unwrap_or(HashMap::new());
let mut vector = Vec::<RequestMetadata>::new();
for (key, value) in hashmap {
vector.push(RequestMetadata {
meta_key: key,
meta_value: value.map(|field_value| field_value.to_string()),
is_visible: Some(DISPLAY_METADATA.to_string()),
});
}
vector
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 8700
}
|
large_file_3195467061621160500
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/wise/transformers.rs
</path>
<file>
#[cfg(feature = "payouts")]
use api_models::payouts::Bank;
#[cfg(feature = "payouts")]
use api_models::payouts::PayoutMethodData;
#[cfg(feature = "payouts")]
use common_enums::PayoutEntityType;
#[cfg(feature = "payouts")]
use common_enums::{CountryAlpha2, PayoutStatus, PayoutType};
#[cfg(feature = "payouts")]
use common_utils::pii::Email;
use common_utils::types::FloatMajorUnit;
use hyperswitch_domain_models::router_data::ConnectorAuthType;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::types::{PayoutsResponseData, PayoutsRouterData};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::Secret;
use serde::{Deserialize, Serialize};
#[cfg(feature = "payouts")]
use crate::types::PayoutsResponseRouterData;
#[cfg(feature = "payouts")]
use crate::utils::get_unimplemented_payment_method_error_message;
#[cfg(feature = "payouts")]
use crate::utils::{PayoutsData as _, RouterData as _};
type Error = error_stack::Report<ConnectorError>;
#[derive(Debug, Serialize)]
pub struct WiseRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for WiseRouterData<T> {
fn from((amount, router_data): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
pub struct WiseAuthType {
pub(super) api_key: Secret<String>,
#[allow(dead_code)]
pub(super) profile_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for WiseAuthType {
type Error = Error;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
profile_id: key1.to_owned(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType)?,
}
}
}
// Wise error response
#[derive(Debug, Deserialize, Serialize)]
pub struct ErrorResponse {
pub timestamp: Option<String>,
pub errors: Option<Vec<SubError>>,
pub status: Option<WiseHttpStatus>,
pub error: Option<String>,
pub error_description: Option<String>,
pub message: Option<String>,
pub path: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum WiseHttpStatus {
String(String),
Number(u16),
}
impl Default for WiseHttpStatus {
fn default() -> Self {
Self::String("".to_string())
}
}
impl WiseHttpStatus {
pub fn get_status(&self) -> String {
match self {
Self::String(val) => val.clone(),
Self::Number(val) => val.to_string(),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct SubError {
pub code: String,
pub message: String,
pub path: Option<String>,
pub field: Option<String>,
}
// Payouts
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WiseRecipientCreateRequest {
currency: String,
#[serde(rename = "type")]
recipient_type: RecipientType,
profile: Secret<String>,
account_holder_name: Secret<String>,
details: WiseBankDetails,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
#[allow(dead_code)]
pub enum RecipientType {
Aba,
Iban,
SortCode,
SwiftCode,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum AccountType {
Checking,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WiseBankDetails {
legal_type: LegalType,
account_type: Option<AccountType>,
address: Option<WiseAddressDetails>,
post_code: Option<String>,
nationality: Option<String>,
account_holder_name: Option<Secret<String>>,
email: Option<Email>,
account_number: Option<Secret<String>>,
city: Option<String>,
sort_code: Option<Secret<String>>,
iban: Option<Secret<String>>,
bic: Option<Secret<String>>,
transit_number: Option<Secret<String>>,
routing_number: Option<Secret<String>>,
abartn: Option<Secret<String>>,
swift_code: Option<Secret<String>>,
payin_reference: Option<String>,
psp_reference: Option<String>,
tax_id: Option<String>,
order_id: Option<String>,
job: Option<String>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum LegalType {
Business,
#[default]
Private,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WiseAddressDetails {
country: Option<CountryAlpha2>,
country_code: Option<CountryAlpha2>,
first_line: Option<Secret<String>>,
post_code: Option<Secret<String>>,
city: Option<String>,
state: Option<Secret<String>>,
}
#[allow(dead_code)]
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WiseRecipientCreateResponse {
id: i64,
business: Option<i64>,
profile: Option<i64>,
account_holder_name: Secret<String>,
currency: String,
country: String,
#[serde(rename = "type")]
request_type: String,
details: Option<WiseBankDetails>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WisePayoutQuoteRequest {
source_currency: String,
target_currency: String,
source_amount: Option<FloatMajorUnit>,
target_amount: Option<FloatMajorUnit>,
pay_out: WisePayOutOption,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum WisePayOutOption {
Balance,
#[default]
BankTransfer,
Swift,
SwiftOur,
Interac,
}
#[allow(dead_code)]
#[cfg(feature = "payouts")]
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WisePayoutQuoteResponse {
source_amount: f64,
client_id: String,
id: String,
status: WiseStatus,
profile: i64,
rate: Option<i8>,
source_currency: Option<String>,
target_currency: Option<String>,
user: Option<i64>,
rate_type: Option<WiseRateType>,
pay_out: Option<WisePayOutOption>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum WiseRateType {
#[default]
Fixed,
Floating,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WisePayoutCreateRequest {
target_account: i64,
quote_uuid: String,
customer_transaction_id: String,
details: WiseTransferDetails,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WiseTransferDetails {
transfer_purpose: Option<String>,
source_of_funds: Option<String>,
transfer_purpose_sub_transfer_purpose: Option<String>,
}
#[allow(dead_code)]
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WisePayoutResponse {
id: i64,
user: i64,
target_account: i64,
source_account: Option<i64>,
quote_uuid: String,
status: WiseStatus,
reference: Option<String>,
rate: Option<f32>,
business: Option<i64>,
details: Option<WiseTransferDetails>,
has_active_issues: Option<bool>,
source_currency: Option<String>,
source_value: Option<f64>,
target_currency: Option<String>,
target_value: Option<f64>,
customer_transaction_id: Option<String>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WisePayoutFulfillRequest {
#[serde(rename = "type")]
fund_type: FundType,
}
// NOTE - Only balance is allowed as time of incorporating this field - https://api-docs.transferwise.com/api-reference/transfer#fund
#[cfg(feature = "payouts")]
#[derive(Debug, Default, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FundType {
#[default]
Balance,
}
#[allow(dead_code)]
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WiseFulfillResponse {
status: WiseStatus,
error_code: Option<String>,
error_message: Option<String>,
balance_transaction_id: Option<i64>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum WiseStatus {
Completed,
Pending,
Rejected,
#[serde(rename = "cancelled")]
Cancelled,
#[serde(rename = "processing")]
#[default]
Processing,
#[serde(rename = "incoming_payment_waiting")]
IncomingPaymentWaiting,
}
#[cfg(feature = "payouts")]
fn get_payout_address_details(
address: Option<&hyperswitch_domain_models::address::Address>,
) -> Option<WiseAddressDetails> {
address.and_then(|add| {
add.address.as_ref().map(|a| WiseAddressDetails {
country: a.country,
country_code: a.country,
first_line: a.line1.clone(),
post_code: a.zip.clone(),
city: a.city.clone(),
state: a.state.clone(),
})
})
}
#[cfg(feature = "payouts")]
fn get_payout_bank_details(
payout_method_data: PayoutMethodData,
address: Option<&hyperswitch_domain_models::address::Address>,
entity_type: PayoutEntityType,
) -> Result<WiseBankDetails, ConnectorError> {
let wise_address_details = match get_payout_address_details(address) {
Some(a) => Ok(a),
None => Err(ConnectorError::MissingRequiredField {
field_name: "address",
}),
}?;
match payout_method_data {
PayoutMethodData::Bank(Bank::Ach(b)) => Ok(WiseBankDetails {
legal_type: LegalType::from(entity_type),
address: Some(wise_address_details),
account_number: Some(b.bank_account_number.to_owned()),
abartn: Some(b.bank_routing_number),
account_type: Some(AccountType::Checking),
..WiseBankDetails::default()
}),
PayoutMethodData::Bank(Bank::Bacs(b)) => Ok(WiseBankDetails {
legal_type: LegalType::from(entity_type),
address: Some(wise_address_details),
account_number: Some(b.bank_account_number.to_owned()),
sort_code: Some(b.bank_sort_code),
..WiseBankDetails::default()
}),
PayoutMethodData::Bank(Bank::Sepa(b)) => Ok(WiseBankDetails {
legal_type: LegalType::from(entity_type),
address: Some(wise_address_details),
iban: Some(b.iban.to_owned()),
bic: b.bic,
..WiseBankDetails::default()
}),
_ => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Wise"),
))?,
}
}
// Payouts recipient create request transform
#[cfg(feature = "payouts")]
impl<F> TryFrom<&WiseRouterData<&PayoutsRouterData<F>>> for WiseRecipientCreateRequest {
type Error = Error;
fn try_from(item_data: &WiseRouterData<&PayoutsRouterData<F>>) -> Result<Self, Self::Error> {
let item = item_data.router_data;
let request = item.request.to_owned();
let customer_details = request.customer_details.to_owned();
let payout_method_data = item.get_payout_method_data()?;
let bank_details = get_payout_bank_details(
payout_method_data.to_owned(),
item.get_optional_billing(),
item.request.entity_type,
)?;
let source_id = match item.connector_auth_type.to_owned() {
ConnectorAuthType::BodyKey { api_key: _, key1 } => Ok(key1),
_ => Err(ConnectorError::MissingRequiredField {
field_name: "source_id for PayoutRecipient creation",
}),
}?;
let payout_type = request.get_payout_type()?;
match payout_type {
PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => {
Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Wise"),
))?
}
PayoutType::Bank => {
let account_holder_name = customer_details
.ok_or(ConnectorError::MissingRequiredField {
field_name: "customer_details for PayoutRecipient creation",
})?
.name
.ok_or(ConnectorError::MissingRequiredField {
field_name: "customer_details.name for PayoutRecipient creation",
})?;
Ok(Self {
profile: source_id,
currency: request.destination_currency.to_string(),
recipient_type: RecipientType::try_from(payout_method_data)?,
account_holder_name,
details: bank_details,
})
}
}
}
}
// Payouts recipient fulfill response transform
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, WiseRecipientCreateResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, WiseRecipientCreateResponse>,
) -> Result<Self, Self::Error> {
let response: WiseRecipientCreateResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::RequiresCreation),
connector_payout_id: Some(response.id.to_string()),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
// Payouts quote request transform
#[cfg(feature = "payouts")]
impl<F> TryFrom<&WiseRouterData<&PayoutsRouterData<F>>> for WisePayoutQuoteRequest {
type Error = Error;
fn try_from(item_data: &WiseRouterData<&PayoutsRouterData<F>>) -> Result<Self, Self::Error> {
let item = item_data.router_data;
let request = item.request.to_owned();
let payout_type = request.get_payout_type()?;
match payout_type {
PayoutType::Bank => Ok(Self {
source_amount: Some(item_data.amount),
source_currency: request.source_currency.to_string(),
target_amount: None,
target_currency: request.destination_currency.to_string(),
pay_out: WisePayOutOption::default(),
}),
PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => {
Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Wise"),
))?
}
}
}
}
// Payouts quote response transform
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, WisePayoutQuoteResponse>> for PayoutsRouterData<F> {
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, WisePayoutQuoteResponse>,
) -> Result<Self, Self::Error> {
let response: WisePayoutQuoteResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::RequiresCreation),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
// Payouts transfer creation request
#[cfg(feature = "payouts")]
impl<F> TryFrom<&PayoutsRouterData<F>> for WisePayoutCreateRequest {
type Error = Error;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
let payout_type = request.get_payout_type()?;
match payout_type {
PayoutType::Bank => {
let connector_customer_id = item.get_connector_customer_id()?;
let quote_uuid = item.get_quote_id()?;
let wise_transfer_details = WiseTransferDetails {
transfer_purpose: None,
source_of_funds: None,
transfer_purpose_sub_transfer_purpose: None,
};
let target_account: i64 = connector_customer_id.trim().parse().map_err(|_| {
ConnectorError::MissingRequiredField {
field_name: "profile",
}
})?;
Ok(Self {
target_account,
quote_uuid,
customer_transaction_id: uuid::Uuid::new_v4().to_string(),
details: wise_transfer_details,
})
}
PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => {
Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Wise"),
))?
}
}
}
}
// Payouts transfer creation response
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, WisePayoutResponse>> for PayoutsRouterData<F> {
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, WisePayoutResponse>,
) -> Result<Self, Self::Error> {
let response: WisePayoutResponse = item.response;
let status = match PayoutStatus::from(response.status) {
PayoutStatus::Cancelled => PayoutStatus::Cancelled,
_ => PayoutStatus::RequiresFulfillment,
};
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(status),
connector_payout_id: Some(response.id.to_string()),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
// Payouts fulfill request transform
#[cfg(feature = "payouts")]
impl<F> TryFrom<&PayoutsRouterData<F>> for WisePayoutFulfillRequest {
type Error = Error;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let payout_type = item.request.get_payout_type()?;
match payout_type {
PayoutType::Bank => Ok(Self {
fund_type: FundType::default(),
}),
PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => {
Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Wise"),
))?
}
}
}
}
// Payouts fulfill response transform
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, WiseFulfillResponse>> for PayoutsRouterData<F> {
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, WiseFulfillResponse>,
) -> Result<Self, Self::Error> {
let response: WiseFulfillResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::from(response.status)),
connector_payout_id: Some(
item.data
.request
.connector_payout_id
.clone()
.ok_or(ConnectorError::MissingConnectorTransactionID)?,
),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
#[cfg(feature = "payouts")]
impl From<WiseStatus> for PayoutStatus {
fn from(wise_status: WiseStatus) -> Self {
match wise_status {
WiseStatus::Completed => Self::Initiated,
WiseStatus::Rejected => Self::Failed,
WiseStatus::Cancelled => Self::Cancelled,
WiseStatus::Pending | WiseStatus::Processing | WiseStatus::IncomingPaymentWaiting => {
Self::Pending
}
}
}
}
#[cfg(feature = "payouts")]
impl From<PayoutEntityType> for LegalType {
fn from(entity_type: PayoutEntityType) -> Self {
match entity_type {
PayoutEntityType::Individual
| PayoutEntityType::Personal
| PayoutEntityType::NonProfit
| PayoutEntityType::NaturalPerson => Self::Private,
PayoutEntityType::Company
| PayoutEntityType::PublicSector
| PayoutEntityType::Business => Self::Business,
}
}
}
#[cfg(feature = "payouts")]
impl TryFrom<PayoutMethodData> for RecipientType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(payout_method_type: PayoutMethodData) -> Result<Self, Self::Error> {
match payout_method_type {
PayoutMethodData::Bank(Bank::Ach(_)) => Ok(Self::Aba),
PayoutMethodData::Bank(Bank::Bacs(_)) => Ok(Self::SortCode),
PayoutMethodData::Bank(Bank::Sepa(_)) => Ok(Self::Iban),
_ => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Wise"),
)
.into()),
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
pub struct WisePayoutSyncResponse {
id: u64,
status: WiseSyncStatus,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum WiseSyncStatus {
IncomingPaymentWaiting,
IncomingPaymentInitiated,
Processing,
FundsConverted,
OutgoingPaymentSent,
Cancelled,
FundsRefunded,
BouncedBack,
ChargedBack,
Unknown,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, WisePayoutSyncResponse>> for PayoutsRouterData<F> {
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, WisePayoutSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::from(item.response.status)),
connector_payout_id: Some(item.response.id.to_string()),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
#[cfg(feature = "payouts")]
impl From<WiseSyncStatus> for PayoutStatus {
fn from(status: WiseSyncStatus) -> Self {
match status {
WiseSyncStatus::IncomingPaymentWaiting => Self::Pending,
WiseSyncStatus::IncomingPaymentInitiated => Self::Pending,
WiseSyncStatus::Processing => Self::Pending,
WiseSyncStatus::FundsConverted => Self::Pending,
WiseSyncStatus::OutgoingPaymentSent => Self::Success,
WiseSyncStatus::Cancelled => Self::Cancelled,
WiseSyncStatus::FundsRefunded => Self::Reversed,
WiseSyncStatus::BouncedBack => Self::Pending,
WiseSyncStatus::ChargedBack => Self::Reversed,
WiseSyncStatus::Unknown => Self::Ineligible,
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
pub struct WisePayoutsWebhookBody {
pub data: WisePayoutsWebhookData,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
pub struct WisePayoutsWebhookData {
pub resource: WisePayoutsWebhookResource,
pub current_state: WiseSyncStatus,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
pub struct WisePayoutsWebhookResource {
pub id: u64,
}
#[cfg(feature = "payouts")]
impl From<WisePayoutsWebhookData> for WisePayoutSyncResponse {
fn from(data: WisePayoutsWebhookData) -> Self {
Self {
id: data.resource.id,
status: data.current_state,
}
}
}
#[cfg(feature = "payouts")]
pub fn get_wise_webhooks_event(
state: WiseSyncStatus,
) -> api_models::webhooks::IncomingWebhookEvent {
match state {
WiseSyncStatus::IncomingPaymentWaiting => {
api_models::webhooks::IncomingWebhookEvent::PayoutProcessing
}
WiseSyncStatus::IncomingPaymentInitiated => {
api_models::webhooks::IncomingWebhookEvent::PayoutProcessing
}
WiseSyncStatus::Processing => api_models::webhooks::IncomingWebhookEvent::PayoutProcessing,
WiseSyncStatus::FundsConverted => {
api_models::webhooks::IncomingWebhookEvent::PayoutProcessing
}
WiseSyncStatus::OutgoingPaymentSent => {
api_models::webhooks::IncomingWebhookEvent::PayoutSuccess
}
WiseSyncStatus::Cancelled => api_models::webhooks::IncomingWebhookEvent::PayoutCancelled,
WiseSyncStatus::FundsRefunded => api_models::webhooks::IncomingWebhookEvent::PayoutReversed,
WiseSyncStatus::BouncedBack => api_models::webhooks::IncomingWebhookEvent::PayoutProcessing,
WiseSyncStatus::ChargedBack => api_models::webhooks::IncomingWebhookEvent::PayoutReversed,
WiseSyncStatus::Unknown => api_models::webhooks::IncomingWebhookEvent::EventNotSupported,
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/wise/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5833
}
|
large_file_-3169646897068668394
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/placetopay/transformers.rs
</path>
<file>
use common_enums::{enums, Currency};
use common_utils::{consts::BASE64_ENGINE, date_time, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use ring::digest;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, generate_random_bytes, BrowserInformationData, CardData as _,
PaymentsAuthorizeRequestData, PaymentsSyncRequestData, RouterData as _,
},
};
pub struct PlacetopayRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for PlacetopayRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayPaymentsRequest {
auth: PlacetopayAuth,
payment: PlacetopayPayment,
instrument: PlacetopayInstrument,
ip_address: Secret<String, common_utils::pii::IpAddress>,
user_agent: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum PlacetopayAuthorizeAction {
Checkin,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayAuthType {
login: Secret<String>,
tran_key: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayAuth {
login: Secret<String>,
tran_key: Secret<String>,
nonce: Secret<String>,
seed: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayPayment {
reference: String,
description: String,
amount: PlacetopayAmount,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayAmount {
currency: Currency,
total: MinorUnit,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayInstrument {
card: PlacetopayCard,
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayCard {
number: cards::CardNumber,
expiration: Secret<String>,
cvv: Secret<String>,
}
impl TryFrom<&PlacetopayRouterData<&types::PaymentsAuthorizeRouterData>>
for PlacetopayPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PlacetopayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let browser_info = item.router_data.request.get_browser_info()?;
let ip_address = browser_info.get_ip_address()?;
let user_agent = browser_info.get_user_agent()?;
let auth = PlacetopayAuth::try_from(&item.router_data.connector_auth_type)?;
let payment = PlacetopayPayment {
reference: item.router_data.connector_request_reference_id.clone(),
description: item.router_data.get_description()?,
amount: PlacetopayAmount {
currency: item.router_data.request.currency,
total: item.amount,
},
};
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = PlacetopayCard {
number: req_card.card_number.clone(),
expiration: req_card
.clone()
.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?,
cvv: req_card.card_cvc.clone(),
};
Ok(Self {
ip_address,
user_agent,
auth,
payment,
instrument: PlacetopayInstrument {
card: card.to_owned(),
},
})
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Placetopay"),
)
.into())
}
}
}
}
impl TryFrom<&ConnectorAuthType> for PlacetopayAuth {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
let placetopay_auth = PlacetopayAuthType::try_from(auth_type)?;
let nonce_bytes = generate_random_bytes(16);
let now = date_time::date_as_yyyymmddthhmmssmmmz()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let seed = format!("{}+00:00", now.split_at(now.len() - 5).0);
let mut context = digest::Context::new(&digest::SHA256);
context.update(&nonce_bytes);
context.update(seed.as_bytes());
context.update(placetopay_auth.tran_key.peek().as_bytes());
let encoded_digest = base64::Engine::encode(&BASE64_ENGINE, context.finish());
let nonce = Secret::new(base64::Engine::encode(&BASE64_ENGINE, &nonce_bytes));
Ok(Self {
login: placetopay_auth.login,
tran_key: encoded_digest.into(),
nonce,
seed,
})
}
}
impl TryFrom<&ConnectorAuthType> for PlacetopayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
login: api_key.to_owned(),
tran_key: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PlacetopayTransactionStatus {
Ok,
Failed,
Approved,
// ApprovedPartial,
// PartialExpired,
Rejected,
Pending,
PendingValidation,
PendingProcess,
// Refunded,
// Reversed,
Error,
// Unknown,
// Manual,
// Dispute,
//The statuses that are commented out are awaiting clarification on the connector.
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayStatusResponse {
status: PlacetopayTransactionStatus,
}
impl From<PlacetopayTransactionStatus> for enums::AttemptStatus {
fn from(item: PlacetopayTransactionStatus) -> Self {
match item {
PlacetopayTransactionStatus::Approved | PlacetopayTransactionStatus::Ok => {
Self::Charged
}
PlacetopayTransactionStatus::Failed
| PlacetopayTransactionStatus::Rejected
| PlacetopayTransactionStatus::Error => Self::Failure,
PlacetopayTransactionStatus::Pending
| PlacetopayTransactionStatus::PendingValidation
| PlacetopayTransactionStatus::PendingProcess => Self::Pending,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayPaymentsResponse {
status: PlacetopayStatusResponse,
internal_reference: u64,
authorization: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, PlacetopayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PlacetopayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.internal_reference.to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: item
.response
.authorization
.clone()
.map(|authorization| serde_json::json!(authorization)),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayRefundRequest {
auth: PlacetopayAuth,
internal_reference: u64,
action: PlacetopayNextAction,
authorization: Option<String>,
}
impl<F> TryFrom<&types::RefundsRouterData<F>> for PlacetopayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
if item.request.minor_refund_amount == item.request.minor_payment_amount {
let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?;
let internal_reference = item
.request
.connector_transaction_id
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let action = PlacetopayNextAction::Reverse;
let authorization = match item.request.connector_metadata.clone() {
Some(metadata) => metadata.as_str().map(|auth| auth.to_string()),
None => None,
};
Ok(Self {
auth,
internal_reference,
action,
authorization,
})
} else {
Err(errors::ConnectorError::NotSupported {
message: "Partial Refund".to_string(),
connector: "placetopay",
}
.into())
}
}
}
impl From<PlacetopayRefundStatus> for enums::RefundStatus {
fn from(item: PlacetopayRefundStatus) -> Self {
match item {
PlacetopayRefundStatus::Ok
| PlacetopayRefundStatus::Approved
| PlacetopayRefundStatus::Refunded => Self::Success,
PlacetopayRefundStatus::Failed
| PlacetopayRefundStatus::Rejected
| PlacetopayRefundStatus::Error => Self::Failure,
PlacetopayRefundStatus::Pending
| PlacetopayRefundStatus::PendingProcess
| PlacetopayRefundStatus::PendingValidation => Self::Pending,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PlacetopayRefundStatus {
Ok,
Failed,
Approved,
// ApprovedPartial,
// PartialExpired,
Rejected,
Pending,
PendingValidation,
PendingProcess,
Refunded,
// Reversed,
Error,
// Unknown,
// Manual,
// Dispute,
//The statuses that are commented out are awaiting clarification on the connector.
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayRefundStatusResponse {
status: PlacetopayRefundStatus,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayRefundResponse {
status: PlacetopayRefundStatusResponse,
internal_reference: u64,
}
impl TryFrom<RefundsResponseRouterData<Execute, PlacetopayRefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, PlacetopayRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.internal_reference.to_string(),
refund_status: enums::RefundStatus::from(item.response.status.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayRsyncRequest {
auth: PlacetopayAuth,
internal_reference: u64,
}
impl TryFrom<&types::RefundsRouterData<RSync>> for PlacetopayRsyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundsRouterData<RSync>) -> Result<Self, Self::Error> {
let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?;
let internal_reference = item
.request
.connector_transaction_id
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
auth,
internal_reference,
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, PlacetopayRefundResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, PlacetopayRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.internal_reference.to_string(),
refund_status: enums::RefundStatus::from(item.response.status.status),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayErrorResponse {
pub status: PlacetopayError,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayError {
pub status: PlacetopayErrorStatus,
pub message: String,
pub reason: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PlacetopayErrorStatus {
Failed,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayPsyncRequest {
auth: PlacetopayAuth,
internal_reference: u64,
}
impl TryFrom<&types::PaymentsSyncRouterData> for PlacetopayPsyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?;
let internal_reference = item
.request
.get_connector_transaction_id()?
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
auth,
internal_reference,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayNextActionRequest {
auth: PlacetopayAuth,
internal_reference: u64,
action: PlacetopayNextAction,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum PlacetopayNextAction {
Refund,
Reverse,
Void,
Process,
Checkout,
}
impl TryFrom<&types::PaymentsCaptureRouterData> for PlacetopayNextActionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?;
let internal_reference = item
.request
.connector_transaction_id
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let action = PlacetopayNextAction::Checkout;
Ok(Self {
auth,
internal_reference,
action,
})
}
}
impl TryFrom<&types::PaymentsCancelRouterData> for PlacetopayNextActionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?;
let internal_reference = item
.request
.connector_transaction_id
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let action = PlacetopayNextAction::Void;
Ok(Self {
auth,
internal_reference,
action,
})
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/placetopay/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3905
}
|
large_file_5543283613129423372
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
</path>
<file>
use common_enums::enums::{AttemptStatus, BankNames, CaptureMethod, CountryAlpha2, Currency};
use common_utils::{pii::Email, request::Method};
use hyperswitch_domain_models::{
payment_method_data::{BankRedirectData, PaymentMethodData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::{
payments::Authorize,
refunds::{Execute, RSync},
},
router_request_types::{PaymentsAuthorizeData, ResponseId},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::{api::CurrencyUnit, errors};
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, CardData, RouterData as RouterDataUtils},
};
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Card {
pub card_number: cards::CardNumber,
pub cardholder_name: Secret<String>,
pub cvv: Secret<String>,
pub expiry_date: Secret<String>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CardPaymentMethod {
pub card: Card,
pub requires_approval: bool,
pub payment_product_id: u16,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmountOfMoney {
pub amount: i64,
pub currency_code: String,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct References {
pub merchant_reference: String,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Order {
pub amount_of_money: AmountOfMoney,
pub customer: Customer,
pub references: References,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct BillingAddress {
pub city: Option<String>,
pub country_code: Option<CountryAlpha2>,
pub house_number: Option<Secret<String>>,
pub state: Option<Secret<String>>,
pub state_code: Option<Secret<String>>,
pub street: Option<Secret<String>>,
pub zip: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ContactDetails {
pub email_address: Option<Email>,
pub mobile_phone_number: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Customer {
pub billing_address: BillingAddress,
pub contact_details: Option<ContactDetails>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Name {
pub first_name: Option<Secret<String>>,
pub surname: Option<Secret<String>>,
pub surname_prefix: Option<Secret<String>>,
pub title: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Shipping {
pub city: Option<String>,
pub country_code: Option<CountryAlpha2>,
pub house_number: Option<Secret<String>>,
pub name: Option<Name>,
pub state: Option<Secret<String>>,
pub state_code: Option<String>,
pub street: Option<Secret<String>>,
pub zip: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum WorldlinePaymentMethod {
CardPaymentMethodSpecificInput(Box<CardPaymentMethod>),
RedirectPaymentMethodSpecificInput(Box<RedirectPaymentMethod>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RedirectPaymentMethod {
pub payment_product_id: u16,
pub redirection_data: RedirectionData,
#[serde(flatten)]
pub payment_method_specific_data: PaymentMethodSpecificData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RedirectionData {
pub return_url: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum PaymentMethodSpecificData {
PaymentProduct816SpecificInput(Box<Giropay>),
PaymentProduct809SpecificInput(Box<Ideal>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Giropay {
pub bank_account_iban: BankAccountIban,
}
#[derive(Debug, Serialize)]
pub struct Ideal {
#[serde(rename = "issuerId")]
pub issuer_id: Option<WorldlineBic>,
}
#[derive(Debug, Serialize)]
pub enum WorldlineBic {
#[serde(rename = "ABNANL2A")]
Abnamro,
#[serde(rename = "ASNBNL21")]
Asn,
#[serde(rename = "FRBKNL2L")]
Friesland,
#[serde(rename = "KNABNL2H")]
Knab,
#[serde(rename = "RABONL2U")]
Rabobank,
#[serde(rename = "RBRBNL21")]
Regiobank,
#[serde(rename = "SNSBNL2A")]
Sns,
#[serde(rename = "TRIONL2U")]
Triodos,
#[serde(rename = "FVLBNL22")]
Vanlanschot,
#[serde(rename = "INGBNL2A")]
Ing,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankAccountIban {
pub account_holder_name: Secret<String>,
pub iban: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentsRequest {
#[serde(flatten)]
pub payment_data: WorldlinePaymentMethod,
pub order: Order,
pub shipping: Option<Shipping>,
}
#[derive(Debug, Serialize)]
pub struct WorldlineRouterData<T> {
amount: i64,
router_data: T,
}
impl<T> TryFrom<(&CurrencyUnit, Currency, i64, T)> for WorldlineRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(_currency_unit, _currency, amount, item): (&CurrencyUnit, Currency, i64, T),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
impl
TryFrom<
&WorldlineRouterData<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>>,
> for PaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &WorldlineRouterData<
&RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
>,
) -> Result<Self, Self::Error> {
let payment_data =
match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(card) => {
let card_holder_name = item.router_data.get_optional_billing_full_name();
WorldlinePaymentMethod::CardPaymentMethodSpecificInput(Box::new(
make_card_request(&item.router_data.request, card, card_holder_name)?,
))
}
PaymentMethodData::BankRedirect(bank_redirect) => {
WorldlinePaymentMethod::RedirectPaymentMethodSpecificInput(Box::new(
make_bank_redirect_request(item.router_data, bank_redirect)?,
))
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("worldline"),
))?
}
};
let billing_address = item.router_data.get_billing()?;
let customer = build_customer_info(billing_address, &item.router_data.request.email)?;
let order = Order {
amount_of_money: AmountOfMoney {
amount: item.amount,
currency_code: item.router_data.request.currency.to_string().to_uppercase(),
},
customer,
references: References {
merchant_reference: item.router_data.connector_request_reference_id.clone(),
},
};
let shipping = item
.router_data
.get_optional_shipping()
.and_then(|shipping| shipping.address.clone())
.map(Shipping::from);
Ok(Self {
payment_data,
order,
shipping,
})
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
pub enum Gateway {
Amex = 2,
Discover = 128,
MasterCard = 3,
Visa = 1,
}
impl TryFrom<utils::CardIssuer> for Gateway {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(issuer: utils::CardIssuer) -> Result<Self, Self::Error> {
match issuer {
utils::CardIssuer::AmericanExpress => Ok(Self::Amex),
utils::CardIssuer::Master => Ok(Self::MasterCard),
utils::CardIssuer::Discover => Ok(Self::Discover),
utils::CardIssuer::Visa => Ok(Self::Visa),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("worldline"),
)
.into()),
}
}
}
impl TryFrom<&BankNames> for WorldlineBic {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(bank: &BankNames) -> Result<Self, Self::Error> {
match bank {
BankNames::AbnAmro => Ok(Self::Abnamro),
BankNames::AsnBank => Ok(Self::Asn),
BankNames::Ing => Ok(Self::Ing),
BankNames::Knab => Ok(Self::Knab),
BankNames::Rabobank => Ok(Self::Rabobank),
BankNames::Regiobank => Ok(Self::Regiobank),
BankNames::SnsBank => Ok(Self::Sns),
BankNames::TriodosBank => Ok(Self::Triodos),
BankNames::VanLanschot => Ok(Self::Vanlanschot),
BankNames::FrieslandBank => Ok(Self::Friesland),
_ => Err(errors::ConnectorError::FlowNotSupported {
flow: bank.to_string(),
connector: "Worldline".to_string(),
}
.into()),
}
}
}
fn make_card_request(
req: &PaymentsAuthorizeData,
ccard: &hyperswitch_domain_models::payment_method_data::Card,
card_holder_name: Option<Secret<String>>,
) -> Result<CardPaymentMethod, error_stack::Report<errors::ConnectorError>> {
let expiry_year = ccard.card_exp_year.peek();
let secret_value = format!(
"{}{}",
ccard.card_exp_month.peek(),
&expiry_year
.get(expiry_year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
);
let expiry_date: Secret<String> = Secret::new(secret_value);
let card = Card {
card_number: ccard.card_number.clone(),
cardholder_name: card_holder_name.unwrap_or(Secret::new("".to_string())),
cvv: ccard.card_cvc.clone(),
expiry_date,
};
#[allow(clippy::as_conversions)]
let payment_product_id = Gateway::try_from(ccard.get_card_issuer()?)? as u16;
let card_payment_method_specific_input = CardPaymentMethod {
card,
requires_approval: matches!(req.capture_method, Some(CaptureMethod::Manual)),
payment_product_id,
};
Ok(card_payment_method_specific_input)
}
fn make_bank_redirect_request(
req: &PaymentsAuthorizeRouterData,
bank_redirect: &BankRedirectData,
) -> Result<RedirectPaymentMethod, error_stack::Report<errors::ConnectorError>> {
let return_url = req.request.router_return_url.clone();
let redirection_data = RedirectionData { return_url };
let (payment_method_specific_data, payment_product_id) = match bank_redirect {
BankRedirectData::Giropay {
bank_account_iban, ..
} => (
{
PaymentMethodSpecificData::PaymentProduct816SpecificInput(Box::new(Giropay {
bank_account_iban: BankAccountIban {
account_holder_name: req.get_billing_full_name()?.to_owned(),
iban: bank_account_iban.clone(),
},
}))
},
816,
),
BankRedirectData::Ideal { bank_name, .. } => (
{
PaymentMethodSpecificData::PaymentProduct809SpecificInput(Box::new(Ideal {
issuer_id: bank_name
.map(|bank_name| WorldlineBic::try_from(&bank_name))
.transpose()?,
}))
},
809,
),
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Bizum {}
| BankRedirectData::Blik { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Eps { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::Sofort { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {} => {
return Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("worldline"),
)
.into())
}
};
Ok(RedirectPaymentMethod {
payment_product_id,
redirection_data,
payment_method_specific_data,
})
}
fn get_address(
billing: &hyperswitch_domain_models::address::Address,
) -> Option<(
&hyperswitch_domain_models::address::Address,
&hyperswitch_domain_models::address::AddressDetails,
)> {
let address = billing.address.as_ref()?;
address.country.as_ref()?;
Some((billing, address))
}
fn build_customer_info(
billing_address: &hyperswitch_domain_models::address::Address,
email: &Option<Email>,
) -> Result<Customer, error_stack::Report<errors::ConnectorError>> {
let (billing, address) =
get_address(billing_address).ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "billing.address.country",
})?;
let number_with_country_code = billing.phone.as_ref().and_then(|phone| {
phone.number.as_ref().and_then(|number| {
phone
.country_code
.as_ref()
.map(|cc| Secret::new(format!("{}{}", cc, number.peek())))
})
});
Ok(Customer {
billing_address: BillingAddress {
..address.clone().into()
},
contact_details: Some(ContactDetails {
mobile_phone_number: number_with_country_code,
email_address: email.clone(),
}),
})
}
impl From<hyperswitch_domain_models::address::AddressDetails> for BillingAddress {
fn from(value: hyperswitch_domain_models::address::AddressDetails) -> Self {
Self {
city: value.city,
country_code: value.country,
state: value.state,
zip: value.zip,
..Default::default()
}
}
}
impl From<hyperswitch_domain_models::address::AddressDetails> for Shipping {
fn from(value: hyperswitch_domain_models::address::AddressDetails) -> Self {
Self {
city: value.city,
country_code: value.country,
name: Some(Name {
first_name: value.first_name,
surname: value.last_name,
..Default::default()
}),
state: value.state,
zip: value.zip,
..Default::default()
}
}
}
pub struct WorldlineAuthType {
pub api_key: Secret<String>,
pub api_secret: Secret<String>,
pub merchant_account_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for WorldlineAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = auth_type
{
Ok(Self {
api_key: api_key.to_owned(),
api_secret: api_secret.to_owned(),
merchant_account_id: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentStatus {
Captured,
Paid,
ChargebackNotification,
Cancelled,
Rejected,
RejectedCapture,
PendingApproval,
CaptureRequested,
#[default]
Processing,
Created,
Redirected,
}
fn get_status(item: (PaymentStatus, CaptureMethod)) -> AttemptStatus {
let (status, capture_method) = item;
match status {
PaymentStatus::Captured | PaymentStatus::Paid | PaymentStatus::ChargebackNotification => {
AttemptStatus::Charged
}
PaymentStatus::Cancelled => AttemptStatus::Voided,
PaymentStatus::Rejected => AttemptStatus::Failure,
PaymentStatus::RejectedCapture => AttemptStatus::CaptureFailed,
PaymentStatus::CaptureRequested => {
if matches!(
capture_method,
CaptureMethod::Automatic | CaptureMethod::SequentialAutomatic
) {
AttemptStatus::Pending
} else {
AttemptStatus::CaptureInitiated
}
}
PaymentStatus::PendingApproval => AttemptStatus::Authorized,
PaymentStatus::Created => AttemptStatus::Started,
PaymentStatus::Redirected => AttemptStatus::AuthenticationPending,
_ => AttemptStatus::Pending,
}
}
/// capture_method is not part of response from connector.
/// This is used to decide payment status while converting connector response to RouterData.
/// To keep this try_from logic generic in case of AUTHORIZE, SYNC and CAPTURE flows capture_method will be set from RouterData request.
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct Payment {
pub id: String,
pub status: PaymentStatus,
#[serde(skip_deserializing)]
pub capture_method: CaptureMethod,
}
impl<F, T> TryFrom<ResponseRouterData<F, Payment, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, Payment, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: get_status((item.response.status, item.response.capture_method)),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentResponse {
pub payment: Payment,
pub merchant_action: Option<MerchantAction>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantAction {
pub redirect_data: RedirectData,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RedirectData {
#[serde(rename = "redirectURL")]
pub redirect_url: Url,
}
impl<F, T> TryFrom<ResponseRouterData<F, PaymentResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaymentResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.merchant_action
.map(|action| action.redirect_data.redirect_url)
.map(|redirect_url| RedirectForm::from((redirect_url, Method::Get)));
Ok(Self {
status: get_status((
item.response.payment.status,
item.response.payment.capture_method,
)),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.payment.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.payment.id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct ApproveRequest {}
impl TryFrom<&PaymentsCaptureRouterData> for ApproveRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(_item: &PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
Ok(Self {})
}
}
#[derive(Default, Debug, Serialize)]
pub struct WorldlineRefundRequest {
amount_of_money: AmountOfMoney,
}
impl<F> TryFrom<&RefundsRouterData<F>> for WorldlineRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> {
Ok(Self {
amount_of_money: AmountOfMoney {
amount: item.request.refund_amount,
currency_code: item.request.currency.to_string(),
},
})
}
}
#[allow(dead_code)]
#[derive(Debug, Default, Deserialize, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Cancelled,
Rejected,
Refunded,
#[default]
Processing,
}
impl From<RefundStatus> for common_enums::enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Refunded => Self::Success,
RefundStatus::Cancelled | RefundStatus::Rejected => Self::Failure,
RefundStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = common_enums::enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.clone(),
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = common_enums::enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.clone(),
refund_status,
}),
..item.data
})
}
}
#[derive(Default, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Error {
pub code: Option<String>,
pub property_name: Option<String>,
pub message: Option<String>,
}
#[derive(Default, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorResponse {
pub error_id: Option<String>,
pub errors: Vec<Error>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WebhookBody {
pub api_version: Option<String>,
pub id: String,
pub created: String,
pub merchant_id: common_utils::id_type::MerchantId,
#[serde(rename = "type")]
pub event_type: WebhookEvent,
pub payment: Option<serde_json::Value>,
pub refund: Option<serde_json::Value>,
pub payout: Option<serde_json::Value>,
pub token: Option<serde_json::Value>,
}
#[derive(Debug, Deserialize)]
pub enum WebhookEvent {
#[serde(rename = "payment.rejected")]
Rejected,
#[serde(rename = "payment.rejected_capture")]
RejectedCapture,
#[serde(rename = "payment.paid")]
Paid,
#[serde(other)]
Unknown,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5672
}
|
large_file_6243029454725425195
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
</path>
<file>
use std::collections::HashMap;
use cards::CardNumber;
use common_enums::{enums, PaymentMethod};
use common_utils::{ext_traits::ValueExt, pii::Email, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankDebitData, PaymentMethodData},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
payments::{Authorize, Capture, CompleteAuthorize, PSync},
refunds::{Execute, RSync},
},
router_request_types::{
CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCaptureData, PaymentsSyncData,
ResponseId,
},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{PaymentsCancelResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, RefundsRequestData, RouterData as OtherRouterData,
},
};
pub struct DeutschebankRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for DeutschebankRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub struct DeutschebankAuthType {
pub(super) client_id: Secret<String>,
pub(super) merchant_id: Secret<String>,
pub(super) client_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for DeutschebankAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
client_id: api_key.to_owned(),
merchant_id: key1.to_owned(),
client_key: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct DeutschebankAccessTokenRequest {
pub grant_type: String,
pub client_id: Secret<String>,
pub client_secret: Secret<String>,
pub scope: String,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct DeutschebankAccessTokenResponse {
pub access_token: Secret<String>,
pub expires_in: i64,
pub expires_on: i64,
pub scope: String,
pub token_type: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, DeutschebankAccessTokenResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DeutschebankAccessTokenResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum DeutschebankSEPAApproval {
Click,
Email,
Sms,
Dynamic,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankMandatePostRequest {
approval_by: DeutschebankSEPAApproval,
email_address: Email,
iban: Secret<String>,
first_name: Secret<String>,
last_name: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum DeutschebankPaymentsRequest {
MandatePost(DeutschebankMandatePostRequest),
DirectDebit(DeutschebankDirectDebitRequest),
CreditCard(Box<DeutschebankThreeDSInitializeRequest>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequest {
means_of_payment: DeutschebankThreeDSInitializeRequestMeansOfPayment,
tds_20_data: DeutschebankThreeDSInitializeRequestTds20Data,
amount_total: DeutschebankThreeDSInitializeRequestAmountTotal,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestMeansOfPayment {
credit_card: DeutschebankThreeDSInitializeRequestCreditCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCreditCard {
number: CardNumber,
expiry_date: DeutschebankThreeDSInitializeRequestCreditCardExpiry,
code: Secret<String>,
cardholder: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCreditCardExpiry {
year: Secret<String>,
month: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestAmountTotal {
amount: MinorUnit,
currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestTds20Data {
communication_data: DeutschebankThreeDSInitializeRequestCommunicationData,
customer_data: DeutschebankThreeDSInitializeRequestCustomerData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCommunicationData {
method_notification_url: String,
cres_notification_url: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCustomerData {
billing_address: DeutschebankThreeDSInitializeRequestCustomerBillingData,
cardholder_email: Email,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCustomerBillingData {
street: Secret<String>,
postal_code: Secret<String>,
city: String,
state: Secret<String>,
country: String,
}
impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>>
for DeutschebankPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DeutschebankRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item
.router_data
.request
.mandate_id
.clone()
.and_then(|mandate_id| mandate_id.mandate_reference_id)
{
None => {
// To facilitate one-off payments via SEPA with Deutsche Bank, we are considering not storing the connector mandate ID in our system if future usage is on-session.
// We will only check for customer acceptance to make a one-off payment. we will be storing the connector mandate details only when setup future usage is off-session.
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => {
if item.router_data.request.customer_acceptance.is_some() {
let billing_address = item.router_data.get_billing_address()?;
Ok(Self::MandatePost(DeutschebankMandatePostRequest {
approval_by: DeutschebankSEPAApproval::Click,
email_address: item.router_data.request.get_email()?,
iban: Secret::from(iban.peek().replace(" ", "")),
first_name: billing_address.get_first_name()?.clone(),
last_name: billing_address.get_last_name()?.clone(),
}))
} else {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "customer_acceptance",
}
.into())
}
}
PaymentMethodData::Card(ccard) => {
if !item.router_data.clone().is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Non-ThreeDs".to_owned(),
connector: "deutschebank",
}
.into())
} else {
let billing_address = item.router_data.get_billing_address()?;
Ok(Self::CreditCard(Box::new(DeutschebankThreeDSInitializeRequest {
means_of_payment: DeutschebankThreeDSInitializeRequestMeansOfPayment {
credit_card: DeutschebankThreeDSInitializeRequestCreditCard {
number: ccard.clone().card_number,
expiry_date: DeutschebankThreeDSInitializeRequestCreditCardExpiry {
year: ccard.get_expiry_year_4_digit(),
month: ccard.card_exp_month,
},
code: ccard.card_cvc,
cardholder: item.router_data.get_billing_full_name()?,
}},
amount_total: DeutschebankThreeDSInitializeRequestAmountTotal {
amount: item.amount,
currency: item.router_data.request.currency,
},
tds_20_data: DeutschebankThreeDSInitializeRequestTds20Data {
communication_data: DeutschebankThreeDSInitializeRequestCommunicationData {
method_notification_url: item.router_data.request.get_complete_authorize_url()?,
cres_notification_url: item.router_data.request.get_complete_authorize_url()?,
},
customer_data: DeutschebankThreeDSInitializeRequestCustomerData {
billing_address: DeutschebankThreeDSInitializeRequestCustomerBillingData {
street: billing_address.get_line1()?.clone(),
postal_code: billing_address.get_zip()?.clone(),
city: billing_address.get_city()?.to_string(),
state: billing_address.get_state()?.clone(),
country: item.router_data.get_billing_country()?.to_string(),
},
cardholder_email: item.router_data.request.get_email()?,
}
}
})))
}
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("deutschebank"),
)
.into()),
}
}
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(mandate_data)) => {
let mandate_metadata: DeutschebankMandateMetadata = mandate_data
.get_mandate_metadata()
.ok_or(errors::ConnectorError::MissingConnectorMandateMetadata)?
.clone()
.parse_value("DeutschebankMandateMetadata")
.change_context(errors::ConnectorError::ParsingFailed)?;
Ok(Self::DirectDebit(DeutschebankDirectDebitRequest {
amount_total: DeutschebankAmount {
amount: item.amount,
currency: item.router_data.request.currency,
},
means_of_payment: DeutschebankMeansOfPayment {
bank_account: DeutschebankBankAccount {
account_holder: mandate_metadata.account_holder,
iban: mandate_metadata.iban,
},
},
mandate: DeutschebankMandate {
reference: mandate_metadata.reference,
signed_on: mandate_metadata.signed_on,
},
}))
}
Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_))
| Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("deutschebank"),
)
.into())
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankThreeDSInitializeResponse {
outcome: DeutschebankThreeDSInitializeResponseOutcome,
challenge_required: Option<DeutschebankThreeDSInitializeResponseChallengeRequired>,
processed: Option<DeutschebankThreeDSInitializeResponseProcessed>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankThreeDSInitializeResponseProcessed {
rc: String,
message: String,
tx_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DeutschebankThreeDSInitializeResponseOutcome {
Processed,
ChallengeRequired,
MethodRequired,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankThreeDSInitializeResponseChallengeRequired {
acs_url: String,
creq: String,
}
impl
TryFrom<
ResponseRouterData<
Authorize,
DeutschebankThreeDSInitializeResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
Authorize,
DeutschebankThreeDSInitializeResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.outcome {
DeutschebankThreeDSInitializeResponseOutcome::Processed => {
match item.response.processed {
Some(processed) => Ok(Self {
status: if is_response_success(&processed.rc) {
match item.data.request.is_auto_capture()? {
true => common_enums::AttemptStatus::Charged,
false => common_enums::AttemptStatus::Authorized,
}
} else {
common_enums::AttemptStatus::AuthenticationFailed
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
processed.tx_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(processed.tx_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
None => {
let response_string = format!("{:?}", item.response);
Err(
errors::ConnectorError::UnexpectedResponseError(bytes::Bytes::from(
response_string,
))
.into(),
)
}
}
}
DeutschebankThreeDSInitializeResponseOutcome::ChallengeRequired => {
match item.response.challenge_required {
Some(challenge) => Ok(Self {
status: common_enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(
RedirectForm::DeutschebankThreeDSChallengeFlow {
acs_url: challenge.acs_url,
creq: challenge.creq,
},
)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
None => {
let response_string = format!("{:?}", item.response);
Err(
errors::ConnectorError::UnexpectedResponseError(bytes::Bytes::from(
response_string,
))
.into(),
)
}
}
}
DeutschebankThreeDSInitializeResponseOutcome::MethodRequired => Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "METHOD_REQUIRED Flow not supported for deutschebank 3ds payments".to_owned(),
reason: Some("METHOD_REQUIRED Flow is not currently supported for deutschebank 3ds payments".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DeutschebankSEPAMandateStatus {
Created,
PendingApproval,
PendingSecondaryApproval,
PendingReview,
PendingSubmission,
Submitted,
Active,
Failed,
Discarded,
Expired,
Replaced,
}
impl From<DeutschebankSEPAMandateStatus> for common_enums::AttemptStatus {
fn from(item: DeutschebankSEPAMandateStatus) -> Self {
match item {
DeutschebankSEPAMandateStatus::Active
| DeutschebankSEPAMandateStatus::Created
| DeutschebankSEPAMandateStatus::PendingApproval
| DeutschebankSEPAMandateStatus::PendingSecondaryApproval
| DeutschebankSEPAMandateStatus::PendingReview
| DeutschebankSEPAMandateStatus::PendingSubmission
| DeutschebankSEPAMandateStatus::Submitted => Self::AuthenticationPending,
DeutschebankSEPAMandateStatus::Failed
| DeutschebankSEPAMandateStatus::Discarded
| DeutschebankSEPAMandateStatus::Expired
| DeutschebankSEPAMandateStatus::Replaced => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankMandateMetadata {
account_holder: Secret<String>,
iban: Secret<String>,
reference: Secret<String>,
signed_on: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankMandatePostResponse {
rc: String,
message: String,
mandate_id: Option<String>,
reference: Option<String>,
approval_date: Option<String>,
language: Option<String>,
approval_by: Option<DeutschebankSEPAApproval>,
state: Option<DeutschebankSEPAMandateStatus>,
}
fn get_error_response(error_code: String, error_reason: String, status_code: u16) -> ErrorResponse {
ErrorResponse {
code: error_code.to_string(),
message: error_reason.clone(),
reason: Some(error_reason),
status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
fn is_response_success(rc: &String) -> bool {
rc == "0"
}
impl
TryFrom<
ResponseRouterData<
Authorize,
DeutschebankMandatePostResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
Authorize,
DeutschebankMandatePostResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let signed_on = match item.response.approval_date.clone() {
Some(date) => date.chars().take(10).collect(),
None => time::OffsetDateTime::now_utc().date().to_string(),
};
let response_code = item.response.rc.clone();
let is_response_success = is_response_success(&response_code);
match (
item.response.reference.clone(),
item.response.state.clone(),
is_response_success,
) {
(Some(reference), Some(state), true) => Ok(Self {
status: common_enums::AttemptStatus::from(state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::Form {
endpoint: item.data.request.get_complete_authorize_url()?,
method: common_utils::request::Method::Get,
form_fields: HashMap::from([
("reference".to_string(), reference.clone()),
("signed_on".to_string(), signed_on.clone()),
]),
})),
mandate_reference: if item.data.request.is_mandate_payment() {
Box::new(Some(MandateReference {
connector_mandate_id: item.response.mandate_id,
payment_method_id: None,
mandate_metadata: Some(Secret::new(
serde_json::json!(DeutschebankMandateMetadata {
account_holder: item.data.get_billing_address()?.get_full_name()?,
iban: match item.data.request.payment_method_data.clone() {
PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit {
iban,
..
}) => Ok(Secret::from(iban.peek().replace(" ", ""))),
_ => Err(errors::ConnectorError::MissingRequiredField {
field_name:
"payment_method_data.bank_debit.sepa_bank_debit.iban"
}),
}?,
reference: Secret::from(reference.clone()),
signed_on,
}),
)),
connector_mandate_request_reference_id: None,
}))
} else {
Box::new(None)
},
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
_ => Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
}),
}
}
}
impl
TryFrom<
ResponseRouterData<
Authorize,
DeutschebankPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
Authorize,
DeutschebankPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_code = item.response.rc.clone();
if is_response_success(&response_code) {
Ok(Self {
status: match item.data.request.is_auto_capture()? {
true => common_enums::AttemptStatus::Charged,
false => common_enums::AttemptStatus::Authorized,
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
})
}
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankAmount {
amount: MinorUnit,
currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankMeansOfPayment {
bank_account: DeutschebankBankAccount,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankBankAccount {
account_holder: Secret<String>,
iban: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankMandate {
reference: Secret<String>,
signed_on: String,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankDirectDebitRequest {
amount_total: DeutschebankAmount,
means_of_payment: DeutschebankMeansOfPayment,
mandate: DeutschebankMandate,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum DeutschebankCompleteAuthorizeRequest {
DeutschebankDirectDebitRequest(DeutschebankDirectDebitRequest),
DeutschebankThreeDSCompleteAuthorizeRequest(DeutschebankThreeDSCompleteAuthorizeRequest),
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankThreeDSCompleteAuthorizeRequest {
cres: String,
}
impl TryFrom<&DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>>
for DeutschebankCompleteAuthorizeRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if matches!(item.router_data.payment_method, PaymentMethod::Card) {
let redirect_response_payload = item
.router_data
.request
.get_redirect_response_payload()?
.expose();
let cres = redirect_response_payload
.get("cres")
.and_then(|v| v.as_str())
.map(String::from)
.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "cres" })?;
Ok(Self::DeutschebankThreeDSCompleteAuthorizeRequest(
DeutschebankThreeDSCompleteAuthorizeRequest { cres },
))
} else {
match item.router_data.request.payment_method_data.clone() {
Some(PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit {
iban, ..
})) => {
let account_holder = item.router_data.get_billing_address()?.get_full_name()?;
let redirect_response =
item.router_data.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let queries_params = redirect_response
.params
.map(|param| {
let mut queries = HashMap::<String, String>::new();
let values = param.peek().split('&').collect::<Vec<&str>>();
for value in values {
let pair = value.split('=').collect::<Vec<&str>>();
queries.insert(
pair.first()
.ok_or(
errors::ConnectorError::ResponseDeserializationFailed,
)?
.to_string(),
pair.get(1)
.ok_or(
errors::ConnectorError::ResponseDeserializationFailed,
)?
.to_string(),
);
}
Ok::<_, errors::ConnectorError>(queries)
})
.transpose()?
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let reference = Secret::from(
queries_params
.get("reference")
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "reference",
})?
.to_owned(),
);
let signed_on = queries_params
.get("signed_on")
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "signed_on",
})?
.to_owned();
Ok(Self::DeutschebankDirectDebitRequest(
DeutschebankDirectDebitRequest {
amount_total: DeutschebankAmount {
amount: item.amount,
currency: item.router_data.request.currency,
},
means_of_payment: DeutschebankMeansOfPayment {
bank_account: DeutschebankBankAccount {
account_holder,
iban: Secret::from(iban.peek().replace(" ", "")),
},
},
mandate: {
DeutschebankMandate {
reference,
signed_on,
}
},
},
))
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("deutschebank"),
)
.into()),
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum DeutschebankTXAction {
Authorization,
Capture,
Credit,
Preauthorization,
Refund,
Reversal,
RiskCheck,
#[serde(rename = "verify-mop")]
VerifyMop,
Payment,
AccountInformation,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub struct BankAccount {
account_holder: Option<Secret<String>>,
bank_name: Option<Secret<String>>,
bic: Option<Secret<String>>,
iban: Option<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub struct TransactionBankAccountInfo {
bank_account: Option<BankAccount>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub struct DeutschebankTransactionInfo {
back_state: Option<String>,
ip_address: Option<Secret<String>>,
#[serde(rename = "type")]
pm_type: Option<String>,
transaction_bankaccount_info: Option<TransactionBankAccountInfo>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub struct DeutschebankPaymentsResponse {
rc: String,
message: String,
timestamp: String,
back_ext_id: Option<String>,
back_rc: Option<String>,
event_id: Option<String>,
kind: Option<String>,
tx_action: Option<DeutschebankTXAction>,
tx_id: String,
amount_total: Option<DeutschebankAmount>,
transaction_info: Option<DeutschebankTransactionInfo>,
}
impl
TryFrom<
ResponseRouterData<
CompleteAuthorize,
DeutschebankPaymentsResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
CompleteAuthorize,
DeutschebankPaymentsResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_code = item.response.rc.clone();
if is_response_success(&response_code) {
Ok(Self {
status: match item.data.request.is_auto_capture()? {
true => common_enums::AttemptStatus::Charged,
false => common_enums::AttemptStatus::Authorized,
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
})
}
}
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum DeutschebankTransactionKind {
Directdebit,
#[serde(rename = "CREDITCARD_3DS20")]
Creditcard3ds20,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankCaptureRequest {
changed_amount: MinorUnit,
kind: DeutschebankTransactionKind,
}
impl TryFrom<&DeutschebankRouterData<&PaymentsCaptureRouterData>> for DeutschebankCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DeutschebankRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
if matches!(item.router_data.payment_method, PaymentMethod::BankDebit) {
Ok(Self {
changed_amount: item.amount,
kind: DeutschebankTransactionKind::Directdebit,
})
} else if item.router_data.is_three_ds()
&& matches!(item.router_data.payment_method, PaymentMethod::Card)
{
Ok(Self {
changed_amount: item.amount,
kind: DeutschebankTransactionKind::Creditcard3ds20,
})
} else {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("deutschebank"),
)
.into())
}
}
}
impl
TryFrom<
ResponseRouterData<
Capture,
DeutschebankPaymentsResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
> for RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
Capture,
DeutschebankPaymentsResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_code = item.response.rc.clone();
if is_response_success(&response_code) {
Ok(Self {
status: common_enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
})
}
}
}
impl
TryFrom<
ResponseRouterData<
PSync,
DeutschebankPaymentsResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
> for RouterData<PSync, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
PSync,
DeutschebankPaymentsResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_code = item.response.rc.clone();
let status = if is_response_success(&response_code) {
item.response
.tx_action
.and_then(|tx_action| match tx_action {
DeutschebankTXAction::Preauthorization => {
Some(common_enums::AttemptStatus::Authorized)
}
DeutschebankTXAction::Authorization | DeutschebankTXAction::Capture => {
Some(common_enums::AttemptStatus::Charged)
}
DeutschebankTXAction::Credit
| DeutschebankTXAction::Refund
| DeutschebankTXAction::Reversal
| DeutschebankTXAction::RiskCheck
| DeutschebankTXAction::VerifyMop
| DeutschebankTXAction::Payment
| DeutschebankTXAction::AccountInformation => None,
})
} else {
Some(common_enums::AttemptStatus::Failure)
};
match status {
Some(common_enums::AttemptStatus::Failure) => Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
}),
Some(status) => Ok(Self {
status,
..item.data
}),
None => Ok(Self { ..item.data }),
}
}
}
#[derive(Debug, Serialize)]
pub struct DeutschebankReversalRequest {
kind: DeutschebankTransactionKind,
}
impl TryFrom<&PaymentsCancelRouterData> for DeutschebankReversalRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
if matches!(item.payment_method, PaymentMethod::BankDebit) {
Ok(Self {
kind: DeutschebankTransactionKind::Directdebit,
})
} else if item.is_three_ds() && matches!(item.payment_method, PaymentMethod::Card) {
Ok(Self {
kind: DeutschebankTransactionKind::Creditcard3ds20,
})
} else {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("deutschebank"),
)
.into())
}
}
}
impl TryFrom<PaymentsCancelResponseRouterData<DeutschebankPaymentsResponse>>
for PaymentsCancelRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<DeutschebankPaymentsResponse>,
) -> Result<Self, Self::Error> {
let response_code = item.response.rc.clone();
if is_response_success(&response_code) {
Ok(Self {
status: common_enums::AttemptStatus::Voided,
..item.data
})
} else {
Ok(Self {
status: common_enums::AttemptStatus::VoidFailed,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
})
}
}
}
#[derive(Debug, Serialize)]
pub struct DeutschebankRefundRequest {
changed_amount: MinorUnit,
kind: DeutschebankTransactionKind,
}
impl<F> TryFrom<&DeutschebankRouterData<&RefundsRouterData<F>>> for DeutschebankRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &DeutschebankRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
if matches!(item.router_data.payment_method, PaymentMethod::BankDebit) {
Ok(Self {
changed_amount: item.amount,
kind: DeutschebankTransactionKind::Directdebit,
})
} else if item.router_data.is_three_ds()
&& matches!(item.router_data.payment_method, PaymentMethod::Card)
{
Ok(Self {
changed_amount: item.amount,
kind: DeutschebankTransactionKind::Creditcard3ds20,
})
} else {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("deutschebank"),
)
.into())
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, DeutschebankPaymentsResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, DeutschebankPaymentsResponse>,
) -> Result<Self, Self::Error> {
let response_code = item.response.rc.clone();
if is_response_success(&response_code) {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.tx_id,
refund_status: enums::RefundStatus::Success,
}),
..item.data
})
} else {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
})
}
}
}
impl TryFrom<RefundsResponseRouterData<RSync, DeutschebankPaymentsResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, DeutschebankPaymentsResponse>,
) -> Result<Self, Self::Error> {
let response_code = item.response.rc.clone();
let status = if is_response_success(&response_code) {
item.response
.tx_action
.and_then(|tx_action| match tx_action {
DeutschebankTXAction::Credit | DeutschebankTXAction::Refund => {
Some(enums::RefundStatus::Success)
}
DeutschebankTXAction::Preauthorization
| DeutschebankTXAction::Authorization
| DeutschebankTXAction::Capture
| DeutschebankTXAction::Reversal
| DeutschebankTXAction::RiskCheck
| DeutschebankTXAction::VerifyMop
| DeutschebankTXAction::Payment
| DeutschebankTXAction::AccountInformation => None,
})
} else {
Some(enums::RefundStatus::Failure)
};
match status {
Some(enums::RefundStatus::Failure) => Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
}),
Some(refund_status) => Ok(Self {
response: Ok(RefundsResponseData {
refund_status,
connector_refund_id: item.data.request.get_connector_refund_id()?,
}),
..item.data
}),
None => Ok(Self { ..item.data }),
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct PaymentsErrorResponse {
pub rc: String,
pub message: String,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct AccessTokenErrorResponse {
pub cause: String,
pub description: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum DeutschebankError {
PaymentsErrorResponse(PaymentsErrorResponse),
AccessTokenErrorResponse(AccessTokenErrorResponse),
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 8737
}
|
large_file_-3997960402958195318
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs
</path>
<file>
use std::collections::HashMap;
use api_models::payments::PollConfig;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
pii::{self, Email, IpAddress},
types::MinorUnit,
};
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, UpiData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{PaymentsAuthorizeData, ResponseId},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::{Duration, OffsetDateTime};
use crate::{
types::{CreateOrderResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
get_unimplemented_payment_method_error_message, missing_field_err,
PaymentsAuthorizeRequestData, RouterData as OtherRouterData,
},
};
pub struct RazorpayRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for RazorpayRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
pub const VERSION: i32 = 1;
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayOrderRequest {
pub amount: MinorUnit,
pub currency: enums::Currency,
pub receipt: String,
pub partial_payment: Option<bool>,
pub first_payment_min_amount: Option<MinorUnit>,
pub notes: Option<RazorpayNotes>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum RazorpayNotes {
Map(HashMap<String, String>),
EmptyMap(HashMap<String, String>),
}
impl TryFrom<&RazorpayRouterData<&types::CreateOrderRouterData>> for RazorpayOrderRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RazorpayRouterData<&types::CreateOrderRouterData>,
) -> Result<Self, Self::Error> {
let currency = item.router_data.request.currency;
let receipt = item.router_data.connector_request_reference_id.clone();
Ok(Self {
amount: item.amount,
currency,
receipt,
partial_payment: None,
first_payment_min_amount: None,
notes: None,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RazorpayMetaData {
pub order_id: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayOrderResponse {
pub id: String,
}
impl TryFrom<CreateOrderResponseRouterData<RazorpayOrderResponse>>
for types::CreateOrderRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: CreateOrderResponseRouterData<RazorpayOrderResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::PaymentsCreateOrderResponse {
order_id: item.response.id.clone(),
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct UpiDetails {
flow: UpiFlow,
vpa: Secret<String, pii::UpiVpaMaskingStrategy>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UpiFlow {
Collect,
Intent,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayPaymentsRequest {
amount: MinorUnit,
currency: enums::Currency,
order_id: String,
email: Email,
contact: Secret<String>,
method: RazorpayPaymentMethod,
upi: UpiDetails,
#[serde(skip_serializing_if = "Option::is_none")]
ip: Option<Secret<String, IpAddress>>,
#[serde(skip_serializing_if = "Option::is_none")]
user_agent: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RazorpayPaymentMethod {
Upi,
}
impl TryFrom<&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>> for RazorpayPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RazorpayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payment_router_data = item.router_data;
let router_request = &payment_router_data.request;
let payment_method_data = &router_request.payment_method_data;
let (razorpay_payment_method, upi_details) = match payment_method_data {
PaymentMethodData::Upi(upi_type_data) => match upi_type_data {
UpiData::UpiCollect(upi_collect_data) => {
let vpa_secret = upi_collect_data
.vpa_id
.clone()
.ok_or_else(missing_field_err("payment_method_data.upi.collect.vpa_id"))?;
(
RazorpayPaymentMethod::Upi,
UpiDetails {
flow: UpiFlow::Collect,
vpa: vpa_secret,
},
)
}
UpiData::UpiIntent(_) | UpiData::UpiQr(_) => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("razorpay"),
))?
}
},
_ => Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("razorpay"),
))?,
};
let contact_number = item.router_data.get_billing_phone_number()?;
let order_id = router_request.get_order_id()?;
let email = item.router_data.get_billing_email()?;
let ip = router_request.get_ip_address_as_optional();
let user_agent = router_request.get_optional_user_agent();
Ok(Self {
amount: item.amount,
currency: router_request.currency,
order_id,
email,
contact: contact_number,
method: razorpay_payment_method,
upi: upi_details,
ip,
user_agent,
})
}
}
pub struct RazorpayAuthType {
pub(super) razorpay_id: Secret<String>,
pub(super) razorpay_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for RazorpayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
razorpay_id: api_key.to_owned(),
razorpay_secret: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NextAction {
pub action: String,
pub url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RazorpayPaymentsResponse {
pub razorpay_payment_id: String,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
RazorpayPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
RazorpayPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let connector_metadata = get_wait_screen_metadata()?;
let order_id = item.data.request.get_order_id()?;
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.razorpay_payment_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(order_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WaitScreenData {
display_from_timestamp: i128,
display_to_timestamp: Option<i128>,
poll_config: Option<PollConfig>,
}
pub fn get_wait_screen_metadata() -> CustomResult<Option<serde_json::Value>, errors::ConnectorError>
{
let current_time = OffsetDateTime::now_utc().unix_timestamp_nanos();
Ok(Some(serde_json::json!(WaitScreenData {
display_from_timestamp: current_time,
display_to_timestamp: Some(current_time + Duration::minutes(5).whole_nanoseconds()),
poll_config: Some(PollConfig {
delay_in_secs: 5,
frequency: 5,
}),
})))
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RazorpaySyncResponse {
items: Vec<RazorpaySyncItem>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RazorpaySyncItem {
id: String,
status: RazorpayStatus,
}
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RazorpayStatus {
Created,
Authorized,
Captured,
Refunded,
Failed,
}
fn get_psync_razorpay_payment_status(razorpay_status: RazorpayStatus) -> enums::AttemptStatus {
match razorpay_status {
RazorpayStatus::Created => enums::AttemptStatus::Pending,
RazorpayStatus::Authorized => enums::AttemptStatus::Authorized,
RazorpayStatus::Captured | RazorpayStatus::Refunded => enums::AttemptStatus::Charged,
RazorpayStatus::Failed => enums::AttemptStatus::Failure,
}
}
impl<F, T> TryFrom<ResponseRouterData<F, RazorpaySyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, RazorpaySyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = match item.response.items.last() {
Some(last_item) => {
let razorpay_status = last_item.status;
get_psync_razorpay_payment_status(razorpay_status)
}
None => item.data.status,
};
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayRefundRequest {
pub amount: MinorUnit,
}
impl<F> TryFrom<&RazorpayRouterData<&types::RefundsRouterData<F>>> for RazorpayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RazorpayRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayRefundResponse {
pub id: String,
pub status: RazorpayRefundStatus,
}
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RazorpayRefundStatus {
Created,
Processed,
Failed,
Pending,
}
impl From<RazorpayRefundStatus> for enums::RefundStatus {
fn from(item: RazorpayRefundStatus) -> Self {
match item {
RazorpayRefundStatus::Processed => Self::Success,
RazorpayRefundStatus::Pending | RazorpayRefundStatus::Created => Self::Pending,
RazorpayRefundStatus::Failed => Self::Failure,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, RazorpayRefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RazorpayRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
// This code can be used later when Razorpay webhooks are implemented
// #[derive(Debug, Deserialize, Serialize)]
// #[serde(untagged)]
// pub enum RazorpayPaymentsResponseData {
// PsyncResponse(RazorpaySyncResponse),
// WebhookResponse(WebhookPaymentEntity),
// }
// impl From<RazorpayWebhookPaymentStatus> for enums::AttemptStatus {
// fn from(status: RazorpayWebhookPaymentStatus) -> Self {
// match status {
// RazorpayWebhookPaymentStatus::Authorized => Self::Authorized,
// RazorpayWebhookPaymentStatus::Captured => Self::Charged,
// RazorpayWebhookPaymentStatus::Failed => Self::Failure,
// }
// }
// }
// impl<F, T> TryFrom<ResponseRouterData<F, RazorpayPaymentsResponseData, T, PaymentsResponseData>>
// for RouterData<F, T, PaymentsResponseData>
// {
// type Error = error_stack::Report<errors::ConnectorError>;
// fn try_from(
// item: ResponseRouterData<F, RazorpayPaymentsResponseData, T, PaymentsResponseData>,
// ) -> Result<Self, Self::Error> {
// match item.response {
// RazorpayPaymentsResponseData::PsyncResponse(sync_response) => {
// let status = get_psync_razorpay_payment_status(sync_response.status.clone());
// Ok(Self {
// status,
// response: if is_payment_failure(status) {
// Err(RouterErrorResponse {
// code: sync_response.status.clone().to_string(),
// message: sync_response.status.clone().to_string(),
// reason: Some(sync_response.status.to_string()),
// status_code: item.http_code,
// attempt_status: Some(status),
// connector_transaction_id: None,
// network_advice_code: None,
// network_decline_code: None,
// network_error_message: None,
// })
// } else {
// Ok(PaymentsResponseData::TransactionResponse {
// resource_id: ResponseId::NoResponseId,
// redirection_data: Box::new(None),
// mandate_reference: Box::new(None),
// connector_metadata: None,
// network_txn_id: None,
// connector_response_reference_id: None,
// incremental_authorization_allowed: None,
// charges: None,
// })
// },
// ..item.data
// })
// }
// RazorpayPaymentsResponseData::WebhookResponse(webhook_payment_entity) => {
// let razorpay_status = webhook_payment_entity.status;
// let status = enums::AttemptStatus::from(razorpay_status.clone());
// Ok(Self {
// status,
// response: if is_payment_failure(status) {
// Err(RouterErrorResponse {
// code: razorpay_status.clone().to_string(),
// message: razorpay_status.clone().to_string(),
// reason: Some(razorpay_status.to_string()),
// status_code: item.http_code,
// attempt_status: Some(status),
// connector_transaction_id: Some(webhook_payment_entity.id.clone()),
// network_advice_code: None,
// network_decline_code: None,
// network_error_message: None,
// })
// } else {
// Ok(PaymentsResponseData::TransactionResponse {
// resource_id: ResponseId::ConnectorTransactionId(
// webhook_payment_entity.id.clone(),
// ),
// redirection_data: Box::new(None),
// mandate_reference: Box::new(None),
// connector_metadata: None,
// network_txn_id: None,
// connector_response_reference_id: Some(webhook_payment_entity.id),
// incremental_authorization_allowed: None,
// charges: None,
// })
// },
// ..item.data
// })
// }
// }
// }
// }
impl TryFrom<RefundsResponseRouterData<RSync, RazorpayRefundResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RazorpayRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ErrorResponse {
RazorpayErrorResponse(RazorpayErrorResponse),
RazorpayStringError(String),
RazorpayError(RazorpayErrorMessage),
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayErrorMessage {
pub message: String,
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayErrorResponse {
pub error: RazorpayError,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayError {
pub code: String,
pub description: String,
pub source: Option<String>,
pub step: Option<String>,
pub reason: Option<String>,
pub metadata: Option<Metadata>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Metadata {
pub order_id: Option<String>,
}
// This code can be used later when Razorpay webhooks are implemented
// #[derive(Debug, Serialize, Deserialize)]
// pub struct RazorpayWebhookPayload {
// pub event: RazorpayWebhookEventType,
// pub payload: RazorpayWebhookPayloadBody,
// }
// #[derive(Debug, Serialize, Deserialize)]
// #[serde(untagged)]
// pub enum RazorpayWebhookEventType {
// Payments(RazorpayWebhookPaymentEvent),
// Refunds(RazorpayWebhookRefundEvent),
// }
// #[derive(Debug, Serialize, Deserialize)]
// pub struct RazorpayWebhookPayloadBody {
// pub refund: Option<RazorpayRefundWebhookPayload>,
// pub payment: RazorpayPaymentWebhookPayload,
// }
// #[derive(Debug, Serialize, Deserialize)]
// pub struct RazorpayPaymentWebhookPayload {
// pub entity: WebhookPaymentEntity,
// }
// #[derive(Debug, Serialize, Deserialize)]
// pub struct RazorpayRefundWebhookPayload {
// pub entity: WebhookRefundEntity,
// }
// #[derive(Debug, Serialize, Deserialize)]
// pub struct WebhookRefundEntity {
// pub id: String,
// pub status: RazorpayWebhookRefundEvent,
// }
// #[derive(Debug, Serialize, Eq, PartialEq, Deserialize)]
// pub enum RazorpayWebhookRefundEvent {
// #[serde(rename = "refund.created")]
// Created,
// #[serde(rename = "refund.processed")]
// Processed,
// #[serde(rename = "refund.failed")]
// Failed,
// #[serde(rename = "refund.speed_change")]
// SpeedChange,
// }
// #[derive(Debug, Serialize, Deserialize)]
// pub struct WebhookPaymentEntity {
// pub id: String,
// pub status: RazorpayWebhookPaymentStatus,
// }
// #[derive(Debug, Serialize, Eq, PartialEq, Clone, Deserialize)]
// #[serde(rename_all = "snake_case")]
// pub enum RazorpayWebhookPaymentStatus {
// Authorized,
// Captured,
// Failed,
// }
// #[derive(Debug, Serialize, Eq, PartialEq, Deserialize)]
// pub enum RazorpayWebhookPaymentEvent {
// #[serde(rename = "payment.authorized")]
// Authorized,
// #[serde(rename = "payment.captured")]
// Captured,
// #[serde(rename = "payment.failed")]
// Failed,
// }
// impl TryFrom<RazorpayWebhookEventType> for api_models::webhooks::IncomingWebhookEvent {
// type Error = errors::ConnectorError;
// fn try_from(event_type: RazorpayWebhookEventType) -> Result<Self, Self::Error> {
// match event_type {
// RazorpayWebhookEventType::Payments(payment_event) => match payment_event {
// RazorpayWebhookPaymentEvent::Authorized => {
// Ok(Self::PaymentIntentAuthorizationSuccess)
// }
// RazorpayWebhookPaymentEvent::Captured => Ok(Self::PaymentIntentSuccess),
// RazorpayWebhookPaymentEvent::Failed => Ok(Self::PaymentIntentFailure),
// },
// RazorpayWebhookEventType::Refunds(refund_event) => match refund_event {
// RazorpayWebhookRefundEvent::Processed => Ok(Self::RefundSuccess),
// RazorpayWebhookRefundEvent::Created => Ok(Self::RefundSuccess),
// RazorpayWebhookRefundEvent::Failed => Ok(Self::RefundFailure),
// RazorpayWebhookRefundEvent::SpeedChange => Ok(Self::EventNotSupported),
// },
// }
// }
// }
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4789
}
|
large_file_3661102376058913732
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/blackhawknetwork/transformers.rs
</path>
<file>
use common_enums::{enums, Currency};
use common_utils::types::{MinorUnit, StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{GiftCardData, PaymentMethodData},
router_data::{
AccessToken, ConnectorAuthType, ErrorResponse, PaymentMethodBalance, RouterData,
},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{PaymentsPreProcessingData, ResponseId},
router_response_types::{PaymentsResponseData, PreprocessingResponseId, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, PaymentsPreProcessingRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::{consts::NO_ERROR_MESSAGE, errors};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::types::{RefundsResponseRouterData, ResponseRouterData};
pub struct BlackhawknetworkRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for BlackhawknetworkRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Clone)]
pub struct BlackhawknetworkAuthType {
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
pub(super) product_line_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BlackhawknetworkAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
client_id: api_key.clone(),
client_secret: api_secret.clone(),
product_line_id: key1.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType)
.attach_printable("Unsupported authentication type for Blackhawk Network"),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BlackhawknetworkAccessTokenRequest {
pub grant_type: String,
pub client_id: Secret<String>,
pub client_secret: Secret<String>,
pub scope: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, BlackhawknetworkTokenResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BlackhawknetworkTokenResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BlackhawknetworkVerifyAccountRequest {
pub account_number: Secret<String>,
pub product_line_id: Secret<String>,
pub account_type: AccountType,
#[serde(skip_serializing_if = "Option::is_none")]
pub pin: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cvv2: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub expiration_date: Option<Secret<String>>,
}
impl TryFrom<&PaymentsPreProcessingRouterData> for BlackhawknetworkVerifyAccountRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> {
let auth = BlackhawknetworkAuthType::try_from(&item.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let gift_card_data = match &item.request.payment_method_data {
Some(PaymentMethodData::GiftCard(gc)) => match gc.as_ref() {
GiftCardData::BhnCardNetwork(data) => data,
_ => {
return Err(errors::ConnectorError::FlowNotSupported {
flow: "Balance".to_string(),
connector: "BlackHawkNetwork".to_string(),
}
.into())
}
},
_ => {
return Err(errors::ConnectorError::FlowNotSupported {
flow: "Balance".to_string(),
connector: "BlackHawkNetwork".to_string(),
}
.into())
}
};
Ok(Self {
account_number: gift_card_data.account_number.clone(),
product_line_id: auth.product_line_id,
account_type: AccountType::GiftCard,
pin: gift_card_data.pin.clone(),
cvv2: gift_card_data.cvv2.clone(),
expiration_date: gift_card_data.expiration_date.clone().map(Secret::new),
})
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BlackhawknetworkVerifyAccountResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BlackhawknetworkVerifyAccountResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::PreProcessingResponse {
pre_processing_id: PreprocessingResponseId::PreProcessingId(
item.response.account.entity_id,
),
connector_metadata: None,
session_token: None,
connector_response_reference_id: None,
}),
payment_method_balance: Some(PaymentMethodBalance {
currency: item.response.account.currency,
amount: item.response.account.balance,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BlackhawknetworkTokenResponse {
pub access_token: Secret<String>,
pub expires_in: i64,
}
#[derive(Serialize, Debug)]
pub struct BlackhawknetworkPaymentsRequest {
pub account_id: String,
pub amount: StringMajorUnit,
pub currency: Currency,
}
impl TryFrom<&BlackhawknetworkRouterData<&PaymentsAuthorizeRouterData>>
for BlackhawknetworkPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BlackhawknetworkRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match &item.router_data.request.payment_method_data {
PaymentMethodData::GiftCard(_gift_card) => {
let account_id = item
.router_data
.preprocessing_id
.to_owned()
.ok_or_else(|| {
errors::ConnectorError::MissingConnectorRelatedTransactionID {
id: "entity_id".to_string(),
}
})?;
Ok(Self {
account_id,
amount: item.amount.clone(),
currency: item.router_data.request.currency,
})
}
_ => Err(error_stack::Report::new(
errors::ConnectorError::NotImplemented("Non-gift card payment method".to_string()),
)),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BlackhawknetworkRedeemResponse {
Success(BlackhawknetworkPaymentsResponse),
Error(BlackhawknetworkErrorResponse),
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BlackhawknetworkPaymentsResponse {
pub id: String,
#[serde(rename = "transactionStatus")]
pub status: BlackhawknetworkAttemptStatus,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum BlackhawknetworkAttemptStatus {
Approved,
Declined,
Pending,
}
impl<F, T> TryFrom<ResponseRouterData<F, BlackhawknetworkRedeemResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BlackhawknetworkRedeemResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
BlackhawknetworkRedeemResponse::Success(response) => Ok(Self {
status: match response.status {
BlackhawknetworkAttemptStatus::Approved => enums::AttemptStatus::Charged,
BlackhawknetworkAttemptStatus::Declined => enums::AttemptStatus::Failure,
BlackhawknetworkAttemptStatus::Pending => enums::AttemptStatus::Pending,
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
BlackhawknetworkRedeemResponse::Error(error_response) => Ok(Self {
response: Err(ErrorResponse {
status_code: item.http_code,
code: error_response.error.clone(),
message: error_response
.error_description
.clone()
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: error_response.error_description,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct BlackhawknetworkRefundRequest {
pub amount: StringMajorUnit,
}
impl<F> TryFrom<&BlackhawknetworkRouterData<&RefundsRouterData<F>>>
for BlackhawknetworkRefundRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BlackhawknetworkRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AccountType {
CreditCard,
GiftCard,
LoyaltyCard,
PhoneCard,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AccountStatus {
New,
Activated,
Closed,
}
impl From<AccountStatus> for common_enums::AttemptStatus {
fn from(item: AccountStatus) -> Self {
match item {
AccountStatus::New | AccountStatus::Activated => Self::Pending,
AccountStatus::Closed => Self::Failure,
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct AccountInformation {
pub entity_id: String,
pub balance: MinorUnit,
pub currency: Currency,
pub status: AccountStatus,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct BlackhawknetworkVerifyAccountResponse {
account: AccountInformation,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BlackhawknetworkErrorResponse {
pub error: String,
pub error_description: Option<String>,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/blackhawknetwork/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2859
}
|
large_file_-5545457285286752383
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
</path>
<file>
use base64::Engine;
use cards::CardNumber;
use common_enums::{enums, AttemptStatus};
use common_utils::{consts, errors::CustomResult, request::Method};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{
ApplePayWalletData, BankRedirectData, Card, PaymentMethodData, WalletData,
},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, CardData, PaymentsAuthorizeRequestData, PaymentsCancelRequestData, WalletData as _,
},
};
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsPaymentsRequest {
initial_amount: i64,
currency: enums::Currency,
channel: NexinetsChannel,
product: NexinetsProduct,
payment: Option<NexinetsPaymentDetails>,
#[serde(rename = "async")]
nexinets_async: NexinetsAsyncDetails,
merchant_order_id: Option<String>,
}
#[derive(Debug, Serialize, Default)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexinetsChannel {
#[default]
Ecom,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum NexinetsProduct {
#[default]
Creditcard,
Paypal,
Giropay,
Sofort,
Eps,
Ideal,
Applepay,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum NexinetsPaymentDetails {
Card(Box<NexiCardDetails>),
Wallet(Box<NexinetsWalletDetails>),
BankRedirects(Box<NexinetsBankRedirects>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexiCardDetails {
#[serde(flatten)]
card_data: CardDataDetails,
cof_contract: Option<CofContract>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum CardDataDetails {
CardDetails(Box<CardDetails>),
PaymentInstrument(Box<PaymentInstrument>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardDetails {
card_number: CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
verification: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInstrument {
payment_instrument_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct CofContract {
#[serde(rename = "type")]
recurring_type: RecurringType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RecurringType {
Unscheduled,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsBankRedirects {
bic: Option<NexinetsBIC>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsAsyncDetails {
pub success_url: Option<String>,
pub cancel_url: Option<String>,
pub failure_url: Option<String>,
}
#[derive(Debug, Serialize)]
pub enum NexinetsBIC {
#[serde(rename = "ABNANL2A")]
AbnAmro,
#[serde(rename = "ASNBNL21")]
AsnBank,
#[serde(rename = "BUNQNL2A")]
Bunq,
#[serde(rename = "INGBNL2A")]
Ing,
#[serde(rename = "KNABNL2H")]
Knab,
#[serde(rename = "RABONL2U")]
Rabobank,
#[serde(rename = "RBRBNL21")]
Regiobank,
#[serde(rename = "SNSBNL2A")]
SnsBank,
#[serde(rename = "TRIONL2U")]
TriodosBank,
#[serde(rename = "FVLBNL22")]
VanLanschot,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum NexinetsWalletDetails {
ApplePayToken(Box<ApplePayDetails>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayDetails {
payment_data: serde_json::Value,
payment_method: ApplepayPaymentMethod,
transaction_identifier: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplepayPaymentMethod {
display_name: String,
network: String,
#[serde(rename = "type")]
token_type: String,
}
impl TryFrom<&PaymentsAuthorizeRouterData> for NexinetsPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let return_url = item.request.router_return_url.clone();
let nexinets_async = NexinetsAsyncDetails {
success_url: return_url.clone(),
cancel_url: return_url.clone(),
failure_url: return_url,
};
let (payment, product) = get_payment_details_and_product(item)?;
let merchant_order_id = match item.payment_method {
// Merchant order id is sent only in case of card payment
enums::PaymentMethod::Card => Some(item.connector_request_reference_id.clone()),
_ => None,
};
Ok(Self {
initial_amount: item.request.amount,
currency: item.request.currency,
channel: NexinetsChannel::Ecom,
product,
payment,
nexinets_async,
merchant_order_id,
})
}
}
// Auth Struct
pub struct NexinetsAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for NexinetsAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => {
let auth_key = format!("{}:{}", key1.peek(), api_key.peek());
let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key));
Ok(Self {
api_key: Secret::new(auth_header),
})
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
}
// PaymentsResponse
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexinetsPaymentStatus {
Success,
Pending,
Ok,
Failure,
Declined,
InProgress,
Expired,
Aborted,
}
fn get_status(status: NexinetsPaymentStatus, method: NexinetsTransactionType) -> AttemptStatus {
match status {
NexinetsPaymentStatus::Success => match method {
NexinetsTransactionType::Preauth => AttemptStatus::Authorized,
NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => {
AttemptStatus::Charged
}
NexinetsTransactionType::Cancel => AttemptStatus::Voided,
},
NexinetsPaymentStatus::Declined
| NexinetsPaymentStatus::Failure
| NexinetsPaymentStatus::Expired
| NexinetsPaymentStatus::Aborted => match method {
NexinetsTransactionType::Preauth => AttemptStatus::AuthorizationFailed,
NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => {
AttemptStatus::CaptureFailed
}
NexinetsTransactionType::Cancel => AttemptStatus::VoidFailed,
},
NexinetsPaymentStatus::Ok => match method {
NexinetsTransactionType::Preauth => AttemptStatus::Authorized,
_ => AttemptStatus::Pending,
},
NexinetsPaymentStatus::Pending => AttemptStatus::AuthenticationPending,
NexinetsPaymentStatus::InProgress => AttemptStatus::Pending,
}
}
impl TryFrom<&enums::BankNames> for NexinetsBIC {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(bank: &enums::BankNames) -> Result<Self, Self::Error> {
match bank {
enums::BankNames::AbnAmro => Ok(Self::AbnAmro),
enums::BankNames::AsnBank => Ok(Self::AsnBank),
enums::BankNames::Bunq => Ok(Self::Bunq),
enums::BankNames::Ing => Ok(Self::Ing),
enums::BankNames::Knab => Ok(Self::Knab),
enums::BankNames::Rabobank => Ok(Self::Rabobank),
enums::BankNames::Regiobank => Ok(Self::Regiobank),
enums::BankNames::SnsBank => Ok(Self::SnsBank),
enums::BankNames::TriodosBank => Ok(Self::TriodosBank),
enums::BankNames::VanLanschot => Ok(Self::VanLanschot),
_ => Err(errors::ConnectorError::FlowNotSupported {
flow: bank.to_string(),
connector: "Nexinets".to_string(),
}
.into()),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsPreAuthOrDebitResponse {
order_id: String,
transaction_type: NexinetsTransactionType,
transactions: Vec<NexinetsTransaction>,
payment_instrument: PaymentInstrument,
redirect_url: Option<Url>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsTransaction {
pub transaction_id: String,
#[serde(rename = "type")]
pub transaction_type: NexinetsTransactionType,
pub currency: enums::Currency,
pub status: NexinetsPaymentStatus,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexinetsTransactionType {
Preauth,
Debit,
Capture,
Cancel,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NexinetsPaymentsMetadata {
pub transaction_id: Option<String>,
pub order_id: Option<String>,
pub psync_flow: NexinetsTransactionType,
}
impl<F, T> TryFrom<ResponseRouterData<F, NexinetsPreAuthOrDebitResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, NexinetsPreAuthOrDebitResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction = match item.response.transactions.first() {
Some(order) => order,
_ => Err(errors::ConnectorError::ResponseHandlingFailed)?,
};
let connector_metadata = serde_json::to_value(NexinetsPaymentsMetadata {
transaction_id: Some(transaction.transaction_id.clone()),
order_id: Some(item.response.order_id.clone()),
psync_flow: item.response.transaction_type.clone(),
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let redirection_data = item
.response
.redirect_url
.map(|url| RedirectForm::from((url, Method::Get)));
let resource_id = match item.response.transaction_type.clone() {
NexinetsTransactionType::Preauth => ResponseId::NoResponseId,
NexinetsTransactionType::Debit => {
ResponseId::ConnectorTransactionId(transaction.transaction_id.clone())
}
_ => Err(errors::ConnectorError::ResponseHandlingFailed)?,
};
let mandate_reference = item
.response
.payment_instrument
.payment_instrument_id
.map(|id| MandateReference {
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
Ok(Self {
status: get_status(transaction.status.clone(), item.response.transaction_type),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: Some(connector_metadata),
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsCaptureOrVoidRequest {
pub initial_amount: i64,
pub currency: enums::Currency,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsOrder {
pub order_id: String,
}
impl TryFrom<&PaymentsCaptureRouterData> for NexinetsCaptureOrVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
Ok(Self {
initial_amount: item.request.amount_to_capture,
currency: item.request.currency,
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for NexinetsCaptureOrVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Ok(Self {
initial_amount: item.request.get_amount()?,
currency: item.request.get_currency()?,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsPaymentResponse {
pub transaction_id: String,
pub status: NexinetsPaymentStatus,
pub order: NexinetsOrder,
#[serde(rename = "type")]
pub transaction_type: NexinetsTransactionType,
}
impl<F, T> TryFrom<ResponseRouterData<F, NexinetsPaymentResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, NexinetsPaymentResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction_id = Some(item.response.transaction_id.clone());
let connector_metadata = serde_json::to_value(NexinetsPaymentsMetadata {
transaction_id,
order_id: Some(item.response.order.order_id.clone()),
psync_flow: item.response.transaction_type.clone(),
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let resource_id = match item.response.transaction_type.clone() {
NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => {
ResponseId::ConnectorTransactionId(item.response.transaction_id)
}
_ => ResponseId::NoResponseId,
};
Ok(Self {
status: get_status(item.response.status, item.response.transaction_type),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(connector_metadata),
network_txn_id: None,
connector_response_reference_id: Some(item.response.order.order_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsRefundRequest {
pub initial_amount: i64,
pub currency: enums::Currency,
}
impl<F> TryFrom<&RefundsRouterData<F>> for NexinetsRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> {
Ok(Self {
initial_amount: item.request.refund_amount,
currency: item.request.currency,
})
}
}
// Type definition for Refund Response
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsRefundResponse {
pub transaction_id: String,
pub status: RefundStatus,
pub order: NexinetsOrder,
#[serde(rename = "type")]
pub transaction_type: RefundType,
}
#[allow(dead_code)]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundStatus {
Success,
Ok,
Failure,
Declined,
InProgress,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundType {
Refund,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Success => Self::Success,
RefundStatus::Failure | RefundStatus::Declined => Self::Failure,
RefundStatus::InProgress | RefundStatus::Ok => Self::Pending,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, NexinetsRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, NexinetsRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, NexinetsRefundResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, NexinetsRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NexinetsErrorResponse {
pub status: u16,
pub code: u16,
pub message: String,
pub errors: Vec<OrderErrorDetails>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct OrderErrorDetails {
pub code: u16,
pub message: String,
pub field: Option<String>,
}
fn get_payment_details_and_product(
item: &PaymentsAuthorizeRouterData,
) -> Result<
(Option<NexinetsPaymentDetails>, NexinetsProduct),
error_stack::Report<errors::ConnectorError>,
> {
match &item.request.payment_method_data {
PaymentMethodData::Card(card) => Ok((
Some(get_card_data(item, card)?),
NexinetsProduct::Creditcard,
)),
PaymentMethodData::Wallet(wallet) => Ok(get_wallet_details(wallet)?),
PaymentMethodData::BankRedirect(bank_redirect) => match bank_redirect {
BankRedirectData::Eps { .. } => Ok((None, NexinetsProduct::Eps)),
BankRedirectData::Giropay { .. } => Ok((None, NexinetsProduct::Giropay)),
BankRedirectData::Ideal { bank_name, .. } => Ok((
Some(NexinetsPaymentDetails::BankRedirects(Box::new(
NexinetsBankRedirects {
bic: bank_name
.map(|bank_name| NexinetsBIC::try_from(&bank_name))
.transpose()?,
},
))),
NexinetsProduct::Ideal,
)),
BankRedirectData::Sofort { .. } => Ok((None, NexinetsProduct::Sofort)),
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::Bizum { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nexinets"),
))?
}
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nexinets"),
))?
}
}
}
fn get_card_data(
item: &PaymentsAuthorizeRouterData,
card: &Card,
) -> Result<NexinetsPaymentDetails, errors::ConnectorError> {
let (card_data, cof_contract) = match item.request.is_mandate_payment() {
true => {
let card_data = match item.request.off_session {
Some(true) => CardDataDetails::PaymentInstrument(Box::new(PaymentInstrument {
payment_instrument_id: item.request.connector_mandate_id().map(Secret::new),
})),
_ => CardDataDetails::CardDetails(Box::new(get_card_details(card)?)),
};
let cof_contract = Some(CofContract {
recurring_type: RecurringType::Unscheduled,
});
(card_data, cof_contract)
}
false => (
CardDataDetails::CardDetails(Box::new(get_card_details(card)?)),
None,
),
};
Ok(NexinetsPaymentDetails::Card(Box::new(NexiCardDetails {
card_data,
cof_contract,
})))
}
fn get_applepay_details(
wallet_data: &WalletData,
applepay_data: &ApplePayWalletData,
) -> CustomResult<ApplePayDetails, errors::ConnectorError> {
let payment_data = WalletData::get_wallet_token_as_json(wallet_data, "Apple Pay".to_string())?;
Ok(ApplePayDetails {
payment_data,
payment_method: ApplepayPaymentMethod {
display_name: applepay_data.payment_method.display_name.to_owned(),
network: applepay_data.payment_method.network.to_owned(),
token_type: applepay_data.payment_method.pm_type.to_owned(),
},
transaction_identifier: applepay_data.transaction_identifier.to_owned(),
})
}
fn get_card_details(req_card: &Card) -> Result<CardDetails, errors::ConnectorError> {
Ok(CardDetails {
card_number: req_card.card_number.clone(),
expiry_month: req_card.card_exp_month.clone(),
expiry_year: req_card.get_card_expiry_year_2_digit()?,
verification: req_card.card_cvc.clone(),
})
}
fn get_wallet_details(
wallet: &WalletData,
) -> Result<
(Option<NexinetsPaymentDetails>, NexinetsProduct),
error_stack::Report<errors::ConnectorError>,
> {
match wallet {
WalletData::PaypalRedirect(_) => Ok((None, NexinetsProduct::Paypal)),
WalletData::ApplePay(applepay_data) => Ok((
Some(NexinetsPaymentDetails::Wallet(Box::new(
NexinetsWalletDetails::ApplePayToken(Box::new(get_applepay_details(
wallet,
applepay_data,
)?)),
))),
NexinetsProduct::Applepay,
)),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect { .. }
| WalletData::GooglePay(_)
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect { .. }
| WalletData::VippsRedirect { .. }
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nexinets"),
))?,
}
}
pub fn get_order_id(
meta: &NexinetsPaymentsMetadata,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
let order_id = meta.order_id.clone().ok_or(
errors::ConnectorError::MissingConnectorRelatedTransactionID {
id: "order_id".to_string(),
},
)?;
Ok(order_id)
}
pub fn get_transaction_id(
meta: &NexinetsPaymentsMetadata,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
let transaction_id = meta.transaction_id.clone().ok_or(
errors::ConnectorError::MissingConnectorRelatedTransactionID {
id: "transaction_id".to_string(),
},
)?;
Ok(transaction_id)
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5980
}
|
large_file_-5026740598051488166
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/plaid/transformers.rs
</path>
<file>
use api_models::payments::OpenBankingSessionToken;
use common_enums::{AttemptStatus, Currency};
use common_utils::types::FloatMajorUnit;
use hyperswitch_domain_models::{
payment_method_data::{OpenBankingData, PaymentMethodData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::ResponseId,
router_response_types::PaymentsResponseData,
types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData},
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{PaymentsPostProcessingRouterData, ResponseRouterData},
utils::is_payment_failure,
};
pub struct PlaidRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for PlaidRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct PlaidPaymentsRequest {
amount: PlaidAmount,
recipient_id: String,
reference: String,
#[serde(skip_serializing_if = "Option::is_none")]
schedule: Option<PlaidSchedule>,
#[serde(skip_serializing_if = "Option::is_none")]
options: Option<PlaidOptions>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct PlaidAmount {
currency: Currency,
value: FloatMajorUnit,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct PlaidSchedule {
interval: String,
interval_execution_day: String,
start_date: String,
end_date: Option<String>,
adjusted_start_date: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct PlaidOptions {
request_refund_details: bool,
iban: Option<Secret<String>>,
bacs: Option<PlaidBacs>,
scheme: String,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct PlaidBacs {
account: Secret<String>,
sort_code: Secret<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct PlaidLinkTokenRequest {
client_name: String,
country_codes: Vec<String>,
language: String,
products: Vec<String>,
user: User,
payment_initiation: PlaidPaymentInitiation,
redirect_uri: Option<String>,
android_package_name: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct User {
pub client_user_id: String,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct PlaidPaymentInitiation {
payment_id: String,
}
impl TryFrom<&PlaidRouterData<&PaymentsAuthorizeRouterData>> for PlaidPaymentsRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PlaidRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::OpenBanking(ref data) => match data {
OpenBankingData::OpenBankingPIS { .. } => {
let amount = item.amount;
let currency = item.router_data.request.currency;
let payment_id = item.router_data.payment_id.clone();
let id_len = payment_id.len();
let reference = if id_len > 18 {
payment_id.get(id_len - 18..id_len).map(|id| id.to_string())
} else {
Some(payment_id)
}
.ok_or(ConnectorError::MissingRequiredField {
field_name: "payment_id",
})?;
let recipient_type = item
.router_data
.additional_merchant_data
.as_ref()
.map(|merchant_data| match merchant_data {
api_models::admin::AdditionalMerchantData::OpenBankingRecipientData(
data,
) => data.clone(),
})
.ok_or(ConnectorError::MissingRequiredField {
field_name: "additional_merchant_data",
})?;
let recipient_id = match recipient_type {
api_models::admin::MerchantRecipientData::ConnectorRecipientId(id) => {
Ok(id.peek().to_string())
}
_ => Err(ConnectorError::MissingRequiredField {
field_name: "ConnectorRecipientId",
}),
}?;
Ok(Self {
amount: PlaidAmount {
currency,
value: amount,
},
reference,
recipient_id,
schedule: None,
options: None,
})
}
},
_ => Err(ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
impl TryFrom<&PaymentsSyncRouterData> for PlaidSyncRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
match item.request.connector_transaction_id {
ResponseId::ConnectorTransactionId(ref id) => Ok(Self {
payment_id: id.clone(),
}),
_ => Err((ConnectorError::MissingConnectorTransactionID).into()),
}
}
}
impl TryFrom<&PaymentsPostProcessingRouterData> for PlaidLinkTokenRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PaymentsPostProcessingRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data {
PaymentMethodData::OpenBanking(ref data) => match data {
OpenBankingData::OpenBankingPIS { .. } => {
let headers = item.header_payload.clone();
let platform = headers
.as_ref()
.and_then(|headers| headers.x_client_platform.clone());
let (is_android, is_ios) = match platform {
Some(common_enums::ClientPlatform::Android) => (true, false),
Some(common_enums::ClientPlatform::Ios) => (false, true),
_ => (false, false),
};
Ok(Self {
client_name: "Hyperswitch".to_string(),
country_codes: item
.request
.country
.map(|code| vec![code.to_string()])
.ok_or(ConnectorError::MissingRequiredField {
field_name: "billing.address.country",
})?,
language: "en".to_string(),
products: vec!["payment_initiation".to_string()],
user: User {
client_user_id: item
.request
.customer_id
.clone()
.map(|id| id.get_string_repr().to_string())
.unwrap_or("default cust".to_string()),
},
payment_initiation: PlaidPaymentInitiation {
payment_id: item
.request
.connector_transaction_id
.clone()
.ok_or(ConnectorError::MissingConnectorTransactionID)?,
},
android_package_name: if is_android {
headers
.as_ref()
.and_then(|headers| headers.x_app_id.clone())
} else {
None
},
redirect_uri: if is_ios {
headers
.as_ref()
.and_then(|headers| headers.x_redirect_uri.clone())
} else {
None
},
})
}
},
_ => Err(ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
pub struct PlaidAuthType {
pub client_id: Secret<String>,
pub secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PlaidAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
client_id: api_key.to_owned(),
secret: key1.to_owned(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(strum::Display)]
pub enum PlaidPaymentStatus {
PaymentStatusInputNeeded,
PaymentStatusInitiated,
PaymentStatusInsufficientFunds,
PaymentStatusFailed,
PaymentStatusBlocked,
PaymentStatusCancelled,
PaymentStatusExecuted,
PaymentStatusSettled,
PaymentStatusEstablished,
PaymentStatusRejected,
PaymentStatusAuthorising,
}
impl From<PlaidPaymentStatus> for AttemptStatus {
fn from(item: PlaidPaymentStatus) -> Self {
match item {
PlaidPaymentStatus::PaymentStatusAuthorising => Self::Authorizing,
PlaidPaymentStatus::PaymentStatusBlocked
| PlaidPaymentStatus::PaymentStatusInsufficientFunds
| PlaidPaymentStatus::PaymentStatusRejected => Self::AuthorizationFailed,
PlaidPaymentStatus::PaymentStatusCancelled => Self::Voided,
PlaidPaymentStatus::PaymentStatusEstablished => Self::Authorized,
PlaidPaymentStatus::PaymentStatusExecuted
| PlaidPaymentStatus::PaymentStatusSettled
| PlaidPaymentStatus::PaymentStatusInitiated => Self::Charged,
PlaidPaymentStatus::PaymentStatusFailed => Self::Failure,
PlaidPaymentStatus::PaymentStatusInputNeeded => Self::AuthenticationPending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PlaidPaymentsResponse {
status: PlaidPaymentStatus,
payment_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PlaidPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PlaidPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = AttemptStatus::from(item.response.status.clone());
Ok(Self {
status,
response: if is_payment_failure(status) {
Err(ErrorResponse {
// populating status everywhere as plaid only sends back a status
code: item.response.status.clone().to_string(),
message: item.response.status.clone().to_string(),
reason: Some(item.response.status.to_string()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.payment_id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.payment_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.payment_id),
incremental_authorization_allowed: None,
charges: None,
})
},
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct PlaidLinkTokenResponse {
link_token: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PlaidLinkTokenResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PlaidLinkTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let session_token = Some(OpenBankingSessionToken {
open_banking_session_token: item.response.link_token,
});
Ok(Self {
status: AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::PostProcessingResponse { session_token }),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct PlaidSyncRequest {
payment_id: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PlaidSyncResponse {
payment_id: String,
amount: PlaidAmount,
status: PlaidPaymentStatus,
recipient_id: String,
reference: String,
last_status_update: String,
adjusted_reference: Option<String>,
schedule: Option<PlaidSchedule>,
iban: Option<Secret<String>>,
bacs: Option<PlaidBacs>,
scheme: Option<String>,
adjusted_scheme: Option<String>,
request_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PlaidSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PlaidSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = AttemptStatus::from(item.response.status.clone());
Ok(Self {
status,
response: if is_payment_failure(status) {
Err(ErrorResponse {
// populating status everywhere as plaid only sends back a status
code: item.response.status.clone().to_string(),
message: item.response.status.clone().to_string(),
reason: Some(item.response.status.to_string()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.payment_id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.payment_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.payment_id),
incremental_authorization_allowed: None,
charges: None,
})
},
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidErrorResponse {
pub display_message: Option<String>,
pub error_code: Option<String>,
pub error_message: String,
pub error_type: Option<String>,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/plaid/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3081
}
|
large_file_409106934563734576
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs
</path>
<file>
use common_enums::{enums, CountryAlpha2, Currency};
use common_utils::{pii, request::Method, types::MinorUnit};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::{PayLaterData, PaymentMethodData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{PaymentsCancelData, PaymentsCaptureData, ResponseId},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
pub struct AffirmRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for AffirmRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize)]
pub struct AffirmPaymentsRequest {
pub merchant: Merchant,
pub items: Vec<Item>,
pub shipping: Option<Shipping>,
pub billing: Option<Billing>,
pub total: MinorUnit,
pub currency: Currency,
pub order_id: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct AffirmCompleteAuthorizeRequest {
pub order_id: Option<String>,
pub reference_id: Option<String>,
pub transaction_id: String,
}
impl TryFrom<&PaymentsCompleteAuthorizeRouterData> for AffirmCompleteAuthorizeRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> {
let transaction_id = item.request.connector_transaction_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_transaction_id",
},
)?;
let reference_id = item.reference_id.clone();
let order_id = item.connector_request_reference_id.clone();
Ok(Self {
transaction_id,
order_id: Some(order_id),
reference_id,
})
}
}
#[derive(Debug, Serialize)]
pub struct Merchant {
pub public_api_key: Secret<String>,
pub user_confirmation_url: String,
pub user_cancel_url: String,
pub user_confirmation_url_action: Option<String>,
pub use_vcn: Option<String>,
pub name: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct Item {
pub display_name: String,
pub sku: String,
pub unit_price: MinorUnit,
pub qty: i64,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Shipping {
pub name: Name,
pub address: Address,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone_number: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<pii::Email>,
}
#[derive(Debug, Serialize)]
pub struct Billing {
pub name: Name,
pub address: Address,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone_number: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<pii::Email>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Name {
pub first: Option<Secret<String>>,
pub last: Option<Secret<String>>,
pub full: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Address {
pub line1: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub line2: Option<Secret<String>>,
pub city: Option<String>,
pub state: Option<Secret<String>>,
pub zipcode: Option<Secret<String>>,
pub country: Option<CountryAlpha2>,
}
#[derive(Debug, Serialize)]
pub struct Metadata {
#[serde(skip_serializing_if = "Option::is_none")]
pub shipping_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub entity_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub platform_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub platform_version: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub platform_affirm: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub webhook_session_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mode: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub itinerary: Option<Vec<Value>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub checkout_channel_type: Option<String>,
#[serde(rename = "BOPIS", skip_serializing_if = "Option::is_none")]
pub bopis: Option<bool>,
}
#[derive(Debug, Serialize)]
pub struct Discount {
pub discount_amount: MinorUnit,
pub discount_display_name: String,
pub discount_code: Option<String>,
}
impl TryFrom<&AffirmRouterData<&PaymentsAuthorizeRouterData>> for AffirmPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AffirmRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let router_data = &item.router_data;
let request = &router_data.request;
let billing = Some(Billing {
name: Name {
first: item.router_data.get_optional_billing_first_name(),
last: item.router_data.get_optional_billing_last_name(),
full: item.router_data.get_optional_billing_full_name(),
},
address: Address {
line1: item.router_data.get_optional_billing_line1(),
line2: item.router_data.get_optional_billing_line2(),
city: item.router_data.get_optional_billing_city(),
state: item.router_data.get_optional_billing_state(),
zipcode: item.router_data.get_optional_billing_zip(),
country: item.router_data.get_optional_billing_country(),
},
phone_number: item.router_data.get_optional_billing_phone_number(),
email: item.router_data.get_optional_billing_email(),
});
let shipping = Some(Shipping {
name: Name {
first: item.router_data.get_optional_shipping_first_name(),
last: item.router_data.get_optional_shipping_last_name(),
full: item.router_data.get_optional_shipping_full_name(),
},
address: Address {
line1: item.router_data.get_optional_shipping_line1(),
line2: item.router_data.get_optional_shipping_line2(),
city: item.router_data.get_optional_shipping_city(),
state: item.router_data.get_optional_shipping_state(),
zipcode: item.router_data.get_optional_shipping_zip(),
country: item.router_data.get_optional_shipping_country(),
},
phone_number: item.router_data.get_optional_shipping_phone_number(),
email: item.router_data.get_optional_shipping_email(),
});
match request.payment_method_data.clone() {
PaymentMethodData::PayLater(PayLaterData::AffirmRedirect {}) => {
let items = match request.order_details.clone() {
Some(order_details) => order_details
.iter()
.map(|data| {
Ok(Item {
display_name: data.product_name.clone(),
sku: data.product_id.clone().unwrap_or_default(),
unit_price: data.amount,
qty: data.quantity.into(),
})
})
.collect::<Result<Vec<_>, _>>(),
None => Err(report!(errors::ConnectorError::MissingRequiredField {
field_name: "order_details",
})),
}?;
let auth_type = AffirmAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let public_api_key = auth_type.public_key;
let merchant = Merchant {
public_api_key,
user_confirmation_url: request.get_complete_authorize_url()?,
user_cancel_url: request.get_router_return_url()?,
user_confirmation_url_action: None,
use_vcn: None,
name: None,
};
Ok(Self {
merchant,
items,
shipping,
billing,
total: item.amount,
currency: request.currency,
order_id: Some(item.router_data.connector_request_reference_id.clone()),
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
pub struct AffirmAuthType {
pub public_key: Secret<String>,
pub private_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AffirmAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
public_key: api_key.to_owned(),
private_key: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl From<AffirmTransactionStatus> for common_enums::AttemptStatus {
fn from(item: AffirmTransactionStatus) -> Self {
match item {
AffirmTransactionStatus::Authorized => Self::Authorized,
AffirmTransactionStatus::AuthExpired => Self::Failure,
AffirmTransactionStatus::Canceled => Self::Voided,
AffirmTransactionStatus::Captured => Self::Charged,
AffirmTransactionStatus::ConfirmationExpired => Self::Failure,
AffirmTransactionStatus::Confirmed => Self::Authorized,
AffirmTransactionStatus::Created => Self::Pending,
AffirmTransactionStatus::Declined => Self::Failure,
AffirmTransactionStatus::Disputed => Self::Unresolved,
AffirmTransactionStatus::DisputeRefunded => Self::Unresolved,
AffirmTransactionStatus::ExpiredAuthorization => Self::Failure,
AffirmTransactionStatus::ExpiredConfirmation => Self::Failure,
AffirmTransactionStatus::PartiallyCaptured => Self::Charged,
AffirmTransactionStatus::Voided => Self::Voided,
AffirmTransactionStatus::PartiallyVoided => Self::Voided,
}
}
}
impl From<AffirmRefundStatus> for common_enums::RefundStatus {
fn from(item: AffirmRefundStatus) -> Self {
match item {
AffirmRefundStatus::PartiallyRefunded => Self::Success,
AffirmRefundStatus::Refunded => Self::Success,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AffirmPaymentsResponse {
checkout_id: String,
redirect_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmCompleteAuthorizeResponse {
pub id: String,
pub status: AffirmTransactionStatus,
pub amount: MinorUnit,
pub amount_refunded: MinorUnit,
pub authorization_expiration: String,
pub checkout_id: String,
pub created: String,
pub currency: Currency,
pub events: Vec<TransactionEvent>,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
pub provider_id: Option<i64>,
pub remove_tax: Option<bool>,
pub checkout: Option<Value>,
pub refund_expires: Option<String>,
pub remaining_capturable_amount: Option<i64>,
pub loan_information: Option<LoanInformation>,
pub user_id: Option<String>,
pub platform: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct TransactionEvent {
pub id: String,
pub amount: MinorUnit,
pub created: String,
pub currency: Currency,
pub fee: Option<i64>,
pub fee_refunded: Option<MinorUnit>,
pub reference_id: Option<String>,
#[serde(rename = "type")]
pub event_type: AffirmEventType,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct LoanInformation {
pub fees: Option<LoanFees>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct LoanFees {
pub amount: Option<MinorUnit>,
pub description: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AffirmTransactionStatus {
Authorized,
AuthExpired,
Canceled,
Captured,
ConfirmationExpired,
Confirmed,
Created,
Declined,
Disputed,
DisputeRefunded,
ExpiredAuthorization,
ExpiredConfirmation,
PartiallyCaptured,
Voided,
PartiallyVoided,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AffirmRefundStatus {
PartiallyRefunded,
Refunded,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmPSyncResponse {
pub amount: MinorUnit,
pub amount_refunded: MinorUnit,
pub authorization_expiration: Option<String>,
pub checkout_id: String,
pub created: String,
pub currency: Currency,
pub events: Vec<TransactionEvent>,
pub id: String,
pub order_id: String,
pub provider_id: Option<i64>,
pub remove_tax: Option<bool>,
pub status: AffirmTransactionStatus,
pub checkout: Option<Value>,
pub refund_expires: Option<String>,
pub remaining_capturable_amount: Option<MinorUnit>,
pub loan_information: Option<LoanInformation>,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub merchant_transaction_id: Option<String>,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmRsyncResponse {
pub amount: MinorUnit,
pub amount_refunded: MinorUnit,
pub authorization_expiration: String,
pub checkout_id: String,
pub created: String,
pub currency: Currency,
pub events: Vec<TransactionEvent>,
pub id: String,
pub order_id: String,
pub status: AffirmRefundStatus,
pub refund_expires: Option<String>,
pub remaining_capturable_amount: Option<MinorUnit>,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub merchant_transaction_id: Option<String>,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AffirmResponseWrapper {
Authorize(AffirmPaymentsResponse),
Psync(Box<AffirmPSyncResponse>),
}
impl<F, T> TryFrom<ResponseRouterData<F, AffirmResponseWrapper, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AffirmResponseWrapper, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match &item.response {
AffirmResponseWrapper::Authorize(resp) => {
let redirection_data = url::Url::parse(&resp.redirect_url)
.ok()
.map(|url| RedirectForm::from((url, Method::Get)));
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(resp.checkout_id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
charges: None,
incremental_authorization_allowed: None,
}),
..item.data
})
}
AffirmResponseWrapper::Psync(resp) => {
let status = enums::AttemptStatus::from(resp.status);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(resp.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
charges: None,
incremental_authorization_allowed: None,
}),
..item.data
})
}
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AffirmCompleteAuthorizeResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AffirmCompleteAuthorizeResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct AffirmRefundRequest {
pub amount: MinorUnit,
#[serde(skip_serializing_if = "Option::is_none")]
pub reference_id: Option<String>,
}
impl<F> TryFrom<&AffirmRouterData<&RefundsRouterData<F>>> for AffirmRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AffirmRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let reference_id = item.router_data.request.connector_transaction_id.clone();
Ok(Self {
amount: item.amount.to_owned(),
reference_id: Some(reference_id),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmRefundResponse {
pub id: String,
pub amount: MinorUnit,
pub created: String,
pub currency: Currency,
pub fee: Option<MinorUnit>,
pub fee_refunded: Option<MinorUnit>,
pub reference_id: Option<String>,
#[serde(rename = "type")]
pub event_type: AffirmEventType,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
}
impl From<AffirmEventType> for enums::RefundStatus {
fn from(event_type: AffirmEventType) -> Self {
match event_type {
AffirmEventType::Refund => Self::Success,
_ => Self::Pending,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, AffirmRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, AffirmRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.event_type),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, AffirmRsyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, AffirmRsyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct AffirmErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
#[serde(rename = "type")]
pub error_type: String,
}
#[derive(Debug, Serialize)]
pub struct AffirmCaptureRequest {
pub order_id: Option<String>,
pub reference_id: Option<String>,
pub amount: MinorUnit,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
}
impl TryFrom<&AffirmRouterData<&PaymentsCaptureRouterData>> for AffirmCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AffirmRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let reference_id = match item.router_data.connector_request_reference_id.clone() {
ref_id if ref_id.is_empty() => None,
ref_id => Some(ref_id),
};
let amount = item.amount;
Ok(Self {
reference_id,
amount,
order_id: None,
shipping_carrier: None,
shipping_confirmation: None,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmCaptureResponse {
pub id: String,
pub amount: MinorUnit,
pub created: String,
pub currency: Currency,
pub fee: Option<MinorUnit>,
pub fee_refunded: Option<MinorUnit>,
pub reference_id: Option<String>,
#[serde(rename = "type")]
pub event_type: AffirmEventType,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AffirmEventType {
Auth,
AuthExpired,
Capture,
ChargeOff,
Confirm,
ConfirmationExpired,
ExpireAuthorization,
ExpireConfirmation,
Refund,
SplitCapture,
Update,
Void,
PartialVoid,
RefundVoided,
}
impl From<AffirmEventType> for enums::AttemptStatus {
fn from(event_type: AffirmEventType) -> Self {
match event_type {
AffirmEventType::Auth => Self::Authorized,
AffirmEventType::Capture | AffirmEventType::SplitCapture | AffirmEventType::Confirm => {
Self::Charged
}
AffirmEventType::AuthExpired
| AffirmEventType::ChargeOff
| AffirmEventType::ConfirmationExpired
| AffirmEventType::ExpireAuthorization
| AffirmEventType::ExpireConfirmation => Self::Failure,
AffirmEventType::Refund | AffirmEventType::RefundVoided => Self::AutoRefunded,
AffirmEventType::Update => Self::Pending,
AffirmEventType::Void | AffirmEventType::PartialVoid => Self::Voided,
}
}
}
impl<F>
TryFrom<ResponseRouterData<F, AffirmCaptureResponse, PaymentsCaptureData, PaymentsResponseData>>
for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
AffirmCaptureResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.event_type.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for AffirmCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let request = &item.request;
let reference_id = request.connector_transaction_id.clone();
let amount = item
.request
.amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "amount",
})?;
Ok(Self {
reference_id: Some(reference_id),
amount,
merchant_transaction_id: None,
})
}
}
#[derive(Debug, Serialize)]
pub struct AffirmCancelRequest {
pub reference_id: Option<String>,
pub amount: i64,
pub merchant_transaction_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmCancelResponse {
pub id: String,
pub amount: MinorUnit,
pub created: String,
pub currency: Currency,
pub fee: Option<MinorUnit>,
pub fee_refunded: Option<MinorUnit>,
pub reference_id: Option<String>,
#[serde(rename = "type")]
pub event_type: AffirmEventType,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
}
impl<F>
TryFrom<ResponseRouterData<F, AffirmCancelResponse, PaymentsCancelData, PaymentsResponseData>>
for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AffirmCancelResponse, PaymentsCancelData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.event_type.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6073
}
|
large_file_-3394474623675883387
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
</path>
<file>
use cards;
use common_enums::enums;
use common_utils::types::StringMinorUnit;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, CardData, RefundsRequestData, RouterData as RouterDataExt},
};
const TRUSTPAYMENTS_API_VERSION: &str = "1.00";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum TrustpaymentsSettleStatus {
#[serde(rename = "0")]
PendingSettlement,
#[serde(rename = "1")]
Settled,
#[serde(rename = "2")]
ManualCapture,
#[serde(rename = "3")]
Voided,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum TrustpaymentsCredentialsOnFile {
#[serde(rename = "0")]
NoStoredCredentials,
#[serde(rename = "1")]
CardholderInitiatedTransaction,
#[serde(rename = "2")]
MerchantInitiatedTransaction,
}
impl TrustpaymentsCredentialsOnFile {
pub fn as_str(&self) -> &'static str {
match self {
Self::NoStoredCredentials => "0",
Self::CardholderInitiatedTransaction => "1",
Self::MerchantInitiatedTransaction => "2",
}
}
}
impl std::fmt::Display for TrustpaymentsCredentialsOnFile {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl TrustpaymentsSettleStatus {
pub fn as_str(&self) -> &'static str {
match self {
Self::PendingSettlement => "0",
Self::Settled => "1",
Self::ManualCapture => "2",
Self::Voided => "3",
}
}
}
impl std::fmt::Display for TrustpaymentsSettleStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_str())
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum TrustpaymentsErrorCode {
#[serde(rename = "0")]
Success,
#[serde(rename = "30000")]
InvalidCredentials,
#[serde(rename = "30001")]
AuthenticationFailed,
#[serde(rename = "30002")]
InvalidSiteReference,
#[serde(rename = "30003")]
AccessDenied,
#[serde(rename = "30004")]
InvalidUsernameOrPassword,
#[serde(rename = "30005")]
AccountSuspended,
#[serde(rename = "50000")]
MissingRequiredField,
#[serde(rename = "50001")]
InvalidFieldFormat,
#[serde(rename = "50002")]
InvalidFieldValue,
#[serde(rename = "50003")]
FieldTooLong,
#[serde(rename = "50004")]
FieldTooShort,
#[serde(rename = "50005")]
InvalidCurrency,
#[serde(rename = "50006")]
InvalidAmount,
#[serde(rename = "60000")]
GeneralProcessingError,
#[serde(rename = "60001")]
SystemError,
#[serde(rename = "60002")]
CommunicationError,
#[serde(rename = "60003")]
Timeout,
#[serde(rename = "60004")]
Processing,
#[serde(rename = "60005")]
InvalidRequest,
#[serde(rename = "60019")]
NoSearchableFilter,
#[serde(rename = "70000")]
InvalidCardNumber,
#[serde(rename = "70001")]
InvalidExpiryDate,
#[serde(rename = "70002")]
InvalidSecurityCode,
#[serde(rename = "70003")]
InvalidCardType,
#[serde(rename = "70004")]
CardExpired,
#[serde(rename = "70005")]
InsufficientFunds,
#[serde(rename = "70006")]
CardDeclined,
#[serde(rename = "70007")]
CardRestricted,
#[serde(rename = "70008")]
InvalidMerchant,
#[serde(rename = "70009")]
TransactionNotPermitted,
#[serde(rename = "70010")]
ExceedsWithdrawalLimit,
#[serde(rename = "70011")]
SecurityViolation,
#[serde(rename = "70012")]
LostOrStolenCard,
#[serde(rename = "70013")]
SuspectedFraud,
#[serde(rename = "70014")]
ContactCardIssuer,
#[serde(rename = "70015")]
InvalidAmountValue,
#[serde(untagged)]
Unknown(String),
}
impl TrustpaymentsErrorCode {
pub fn as_str(&self) -> &str {
match self {
Self::Success => "0",
Self::InvalidCredentials => "30000",
Self::AuthenticationFailed => "30001",
Self::InvalidSiteReference => "30002",
Self::AccessDenied => "30003",
Self::InvalidUsernameOrPassword => "30004",
Self::AccountSuspended => "30005",
Self::MissingRequiredField => "50000",
Self::InvalidFieldFormat => "50001",
Self::InvalidFieldValue => "50002",
Self::FieldTooLong => "50003",
Self::FieldTooShort => "50004",
Self::InvalidCurrency => "50005",
Self::InvalidAmount => "50006",
Self::GeneralProcessingError => "60000",
Self::SystemError => "60001",
Self::CommunicationError => "60002",
Self::Timeout => "60003",
Self::Processing => "60004",
Self::InvalidRequest => "60005",
Self::NoSearchableFilter => "60019",
Self::InvalidCardNumber => "70000",
Self::InvalidExpiryDate => "70001",
Self::InvalidSecurityCode => "70002",
Self::InvalidCardType => "70003",
Self::CardExpired => "70004",
Self::InsufficientFunds => "70005",
Self::CardDeclined => "70006",
Self::CardRestricted => "70007",
Self::InvalidMerchant => "70008",
Self::TransactionNotPermitted => "70009",
Self::ExceedsWithdrawalLimit => "70010",
Self::SecurityViolation => "70011",
Self::LostOrStolenCard => "70012",
Self::SuspectedFraud => "70013",
Self::ContactCardIssuer => "70014",
Self::InvalidAmountValue => "70015",
Self::Unknown(code) => code,
}
}
pub fn is_success(&self) -> bool {
matches!(self, Self::Success)
}
pub fn get_attempt_status(&self) -> common_enums::AttemptStatus {
match self {
// Success cases should be handled by get_payment_status() with settlestatus logic
Self::Success => common_enums::AttemptStatus::Authorized,
// Authentication and configuration errors
Self::InvalidCredentials
| Self::AuthenticationFailed
| Self::InvalidSiteReference
| Self::AccessDenied
| Self::InvalidUsernameOrPassword
| Self::AccountSuspended => common_enums::AttemptStatus::Failure,
// Card-related and payment errors that should be treated as failures
Self::InvalidCardNumber
| Self::InvalidExpiryDate
| Self::InvalidSecurityCode
| Self::InvalidCardType
| Self::CardExpired
| Self::InsufficientFunds
| Self::CardDeclined
| Self::CardRestricted
| Self::TransactionNotPermitted
| Self::ExceedsWithdrawalLimit
| Self::InvalidAmountValue => common_enums::AttemptStatus::Failure,
// Processing states that should remain pending
Self::Processing => common_enums::AttemptStatus::Pending,
// Default fallback for unknown errors
_ => common_enums::AttemptStatus::Pending,
}
}
pub fn get_description(&self) -> &'static str {
match self {
Self::Success => "Success",
Self::InvalidCredentials => "Invalid credentials",
Self::AuthenticationFailed => "Authentication failed",
Self::InvalidSiteReference => "Invalid site reference",
Self::AccessDenied => "Access denied",
Self::InvalidUsernameOrPassword => "Invalid username or password",
Self::AccountSuspended => "Account suspended",
Self::MissingRequiredField => "Missing required field",
Self::InvalidFieldFormat => "Invalid field format",
Self::InvalidFieldValue => "Invalid field value",
Self::FieldTooLong => "Field value too long",
Self::FieldTooShort => "Field value too short",
Self::InvalidCurrency => "Invalid currency code",
Self::InvalidAmount => "Invalid amount format",
Self::GeneralProcessingError => "General processing error",
Self::SystemError => "System error",
Self::CommunicationError => "Communication error",
Self::Timeout => "Request timeout",
Self::Processing => "Transaction processing",
Self::InvalidRequest => "Invalid request format",
Self::NoSearchableFilter => "No searchable filter specified",
Self::InvalidCardNumber => "Invalid card number",
Self::InvalidExpiryDate => "Invalid expiry date",
Self::InvalidSecurityCode => "Invalid security code",
Self::InvalidCardType => "Invalid card type",
Self::CardExpired => "Card expired",
Self::InsufficientFunds => "Insufficient funds",
Self::CardDeclined => "Card declined by issuer",
Self::CardRestricted => "Card restricted",
Self::InvalidMerchant => "Invalid merchant",
Self::TransactionNotPermitted => "Transaction not permitted",
Self::ExceedsWithdrawalLimit => "Exceeds withdrawal limit",
Self::SecurityViolation => "Security violation",
Self::LostOrStolenCard => "Lost or stolen card",
Self::SuspectedFraud => "Suspected fraud",
Self::ContactCardIssuer => "Contact card issuer",
Self::InvalidAmountValue => "Invalid amount",
Self::Unknown(_) => "Unknown error",
}
}
}
impl std::fmt::Display for TrustpaymentsErrorCode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_str())
}
}
pub struct TrustpaymentsRouterData<T> {
pub amount: StringMinorUnit,
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for TrustpaymentsRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsPaymentsRequest {
pub alias: String,
pub version: String,
pub request: Vec<TrustpaymentsPaymentRequestData>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsPaymentRequestData {
pub accounttypedescription: String,
pub baseamount: StringMinorUnit,
pub billingfirstname: Option<String>,
pub billinglastname: Option<String>,
pub currencyiso3a: String,
pub expirydate: Secret<String>,
pub orderreference: String,
pub pan: cards::CardNumber,
pub requesttypedescriptions: Vec<String>,
pub securitycode: Secret<String>,
pub sitereference: String,
pub credentialsonfile: String,
pub settlestatus: String,
}
impl TryFrom<&TrustpaymentsRouterData<&PaymentsAuthorizeRouterData>>
for TrustpaymentsPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &TrustpaymentsRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let auth = TrustpaymentsAuthType::try_from(&item.router_data.connector_auth_type)?;
if matches!(
item.router_data.auth_type,
enums::AuthenticationType::ThreeDs
) {
return Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("trustpayments"),
)
.into());
}
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = req_card.clone();
let request_types = match item.router_data.request.capture_method {
Some(common_enums::CaptureMethod::Automatic) | None => vec!["AUTH".to_string()],
Some(common_enums::CaptureMethod::Manual) => vec!["AUTH".to_string()],
Some(common_enums::CaptureMethod::ManualMultiple)
| Some(common_enums::CaptureMethod::Scheduled)
| Some(common_enums::CaptureMethod::SequentialAutomatic) => {
return Err(errors::ConnectorError::NotSupported {
message: "Capture method not supported by TrustPayments".to_string(),
connector: "TrustPayments",
}
.into());
}
};
Ok(Self {
alias: auth.username.expose(),
version: TRUSTPAYMENTS_API_VERSION.to_string(),
request: vec![TrustpaymentsPaymentRequestData {
accounttypedescription: "ECOM".to_string(),
baseamount: item.amount.clone(),
billingfirstname: item
.router_data
.get_optional_billing_first_name()
.map(|name| name.expose()),
billinglastname: item
.router_data
.get_optional_billing_last_name()
.map(|name| name.expose()),
currencyiso3a: item.router_data.request.currency.to_string(),
expirydate: card
.get_card_expiry_month_year_2_digit_with_delimiter("/".to_string())?,
orderreference: item.router_data.connector_request_reference_id.clone(),
pan: card.card_number.clone(),
requesttypedescriptions: request_types,
securitycode: card.card_cvc.clone(),
sitereference: auth.site_reference.expose(),
credentialsonfile:
TrustpaymentsCredentialsOnFile::CardholderInitiatedTransaction
.to_string(),
settlestatus: match item.router_data.request.capture_method {
Some(common_enums::CaptureMethod::Manual) => {
TrustpaymentsSettleStatus::ManualCapture
.as_str()
.to_string()
}
Some(common_enums::CaptureMethod::Automatic) | None => {
TrustpaymentsSettleStatus::PendingSettlement
.as_str()
.to_string()
}
_ => TrustpaymentsSettleStatus::PendingSettlement
.as_str()
.to_string(),
},
}],
})
}
_ => Err(errors::ConnectorError::NotImplemented(
"Payment method not supported".to_string(),
)
.into()),
}
}
}
pub struct TrustpaymentsAuthType {
pub(super) username: Secret<String>,
pub(super) password: Secret<String>,
pub(super) site_reference: Secret<String>,
}
impl TrustpaymentsAuthType {
pub fn get_basic_auth_header(&self) -> String {
use base64::Engine;
let credentials = format!(
"{}:{}",
self.username.clone().expose(),
self.password.clone().expose()
);
let encoded = base64::engine::general_purpose::STANDARD.encode(credentials.as_bytes());
format!("Basic {encoded}")
}
}
impl TryFrom<&ConnectorAuthType> for TrustpaymentsAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
username: api_key.to_owned(),
password: key1.to_owned(),
site_reference: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TrustpaymentsPaymentsResponse {
#[serde(alias = "response")]
pub responses: Vec<TrustpaymentsPaymentResponseData>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TrustpaymentsPaymentResponseData {
pub errorcode: TrustpaymentsErrorCode,
pub errormessage: String,
pub authcode: Option<String>,
pub baseamount: Option<StringMinorUnit>,
pub currencyiso3a: Option<String>,
pub transactionreference: Option<String>,
pub settlestatus: Option<TrustpaymentsSettleStatus>,
pub requesttypedescription: String,
pub securityresponsesecuritycode: Option<String>,
}
impl TrustpaymentsPaymentResponseData {
pub fn get_payment_status(&self) -> common_enums::AttemptStatus {
match self.errorcode {
TrustpaymentsErrorCode::Success => {
if self.authcode.is_some() {
match &self.settlestatus {
Some(TrustpaymentsSettleStatus::PendingSettlement) => {
// settlestatus "0" = automatic capture, scheduled to settle
common_enums::AttemptStatus::Charged
}
Some(TrustpaymentsSettleStatus::Settled) => {
// settlestatus "1" or "100" = transaction has been settled
common_enums::AttemptStatus::Charged
}
Some(TrustpaymentsSettleStatus::ManualCapture) => {
// settlestatus "2" = suspended, manual capture needed
common_enums::AttemptStatus::Authorized
}
Some(TrustpaymentsSettleStatus::Voided) => {
// settlestatus "3" = transaction has been cancelled
common_enums::AttemptStatus::Voided
}
None => common_enums::AttemptStatus::Authorized,
}
} else {
common_enums::AttemptStatus::Failure
}
}
_ => self.errorcode.get_attempt_status(),
}
}
pub fn get_payment_status_for_sync(&self) -> common_enums::AttemptStatus {
match self.errorcode {
TrustpaymentsErrorCode::Success => {
if self.requesttypedescription == "TRANSACTIONQUERY"
&& self.authcode.is_none()
&& self.settlestatus.is_none()
&& self.transactionreference.is_none()
{
common_enums::AttemptStatus::Authorized
} else if self.authcode.is_some() {
match &self.settlestatus {
Some(TrustpaymentsSettleStatus::PendingSettlement) => {
common_enums::AttemptStatus::Authorized
}
Some(TrustpaymentsSettleStatus::Settled) => {
common_enums::AttemptStatus::Charged
}
Some(TrustpaymentsSettleStatus::ManualCapture) => {
common_enums::AttemptStatus::Authorized
}
Some(TrustpaymentsSettleStatus::Voided) => {
common_enums::AttemptStatus::Voided
}
None => common_enums::AttemptStatus::Authorized,
}
} else {
common_enums::AttemptStatus::Pending
}
}
_ => self.errorcode.get_attempt_status(),
}
}
pub fn get_error_message(&self) -> String {
if self.errorcode.is_success() {
"Success".to_string()
} else {
format!("Error {}: {}", self.errorcode, self.errormessage)
}
}
pub fn get_error_reason(&self) -> Option<String> {
if !self.errorcode.is_success() {
Some(self.errorcode.get_description().to_string())
} else {
None
}
}
}
impl
TryFrom<
ResponseRouterData<
hyperswitch_domain_models::router_flow_types::payments::Authorize,
TrustpaymentsPaymentsResponse,
hyperswitch_domain_models::router_request_types::PaymentsAuthorizeData,
PaymentsResponseData,
>,
>
for RouterData<
hyperswitch_domain_models::router_flow_types::payments::Authorize,
hyperswitch_domain_models::router_request_types::PaymentsAuthorizeData,
PaymentsResponseData,
>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
hyperswitch_domain_models::router_flow_types::payments::Authorize,
TrustpaymentsPaymentsResponse,
hyperswitch_domain_models::router_request_types::PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_data = item
.response
.responses
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let status = response_data.get_payment_status();
let transaction_id = response_data
.transactionreference
.clone()
.unwrap_or_else(|| "unknown".to_string());
if !response_data.errorcode.is_success() {
let _error_response = TrustpaymentsErrorResponse::from(response_data.clone());
return Ok(Self {
status,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: response_data.errorcode.to_string(),
message: response_data.errormessage.clone(),
reason: response_data.get_error_reason(),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: response_data.transactionreference.clone(),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
});
}
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(transaction_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl
TryFrom<
ResponseRouterData<
hyperswitch_domain_models::router_flow_types::payments::PSync,
TrustpaymentsPaymentsResponse,
hyperswitch_domain_models::router_request_types::PaymentsSyncData,
PaymentsResponseData,
>,
>
for RouterData<
hyperswitch_domain_models::router_flow_types::payments::PSync,
hyperswitch_domain_models::router_request_types::PaymentsSyncData,
PaymentsResponseData,
>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
hyperswitch_domain_models::router_flow_types::payments::PSync,
TrustpaymentsPaymentsResponse,
hyperswitch_domain_models::router_request_types::PaymentsSyncData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_data = item
.response
.responses
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let status = response_data.get_payment_status_for_sync();
let transaction_id = item
.data
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
if !response_data.errorcode.is_success() {
return Ok(Self {
status,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: response_data.errorcode.to_string(),
message: response_data.errormessage.clone(),
reason: response_data.get_error_reason(),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
});
}
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(transaction_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl
TryFrom<
ResponseRouterData<
hyperswitch_domain_models::router_flow_types::payments::Capture,
TrustpaymentsPaymentsResponse,
hyperswitch_domain_models::router_request_types::PaymentsCaptureData,
PaymentsResponseData,
>,
>
for RouterData<
hyperswitch_domain_models::router_flow_types::payments::Capture,
hyperswitch_domain_models::router_request_types::PaymentsCaptureData,
PaymentsResponseData,
>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
hyperswitch_domain_models::router_flow_types::payments::Capture,
TrustpaymentsPaymentsResponse,
hyperswitch_domain_models::router_request_types::PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_data = item
.response
.responses
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let transaction_id = item.data.request.connector_transaction_id.clone();
let status = if response_data.errorcode.is_success() {
common_enums::AttemptStatus::Charged
} else {
response_data.get_payment_status()
};
if !response_data.errorcode.is_success() {
return Ok(Self {
status,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: response_data.errorcode.to_string(),
message: response_data.errormessage.clone(),
reason: response_data.get_error_reason(),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
});
}
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(transaction_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl
TryFrom<
ResponseRouterData<
hyperswitch_domain_models::router_flow_types::payments::Void,
TrustpaymentsPaymentsResponse,
hyperswitch_domain_models::router_request_types::PaymentsCancelData,
PaymentsResponseData,
>,
>
for RouterData<
hyperswitch_domain_models::router_flow_types::payments::Void,
hyperswitch_domain_models::router_request_types::PaymentsCancelData,
PaymentsResponseData,
>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
hyperswitch_domain_models::router_flow_types::payments::Void,
TrustpaymentsPaymentsResponse,
hyperswitch_domain_models::router_request_types::PaymentsCancelData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_data = item
.response
.responses
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let transaction_id = item.data.request.connector_transaction_id.clone();
let status = if response_data.errorcode.is_success() {
common_enums::AttemptStatus::Voided
} else {
response_data.get_payment_status()
};
if !response_data.errorcode.is_success() {
return Ok(Self {
status,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: response_data.errorcode.to_string(),
message: response_data.errormessage.clone(),
reason: response_data.get_error_reason(),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
});
}
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(transaction_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsCaptureRequest {
pub alias: String,
pub version: String,
pub request: Vec<TrustpaymentsCaptureRequestData>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsCaptureRequestData {
pub requesttypedescriptions: Vec<String>,
pub filter: TrustpaymentsFilter,
pub updates: TrustpaymentsCaptureUpdates,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsCaptureUpdates {
pub settlestatus: TrustpaymentsSettleStatus,
}
impl TryFrom<&TrustpaymentsRouterData<&PaymentsCaptureRouterData>> for TrustpaymentsCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &TrustpaymentsRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let auth = TrustpaymentsAuthType::try_from(&item.router_data.connector_auth_type)?;
let transaction_reference = item.router_data.request.connector_transaction_id.clone();
Ok(Self {
alias: auth.username.expose(),
version: TRUSTPAYMENTS_API_VERSION.to_string(),
request: vec![TrustpaymentsCaptureRequestData {
requesttypedescriptions: vec!["TRANSACTIONUPDATE".to_string()],
filter: TrustpaymentsFilter {
sitereference: vec![TrustpaymentsFilterValue {
value: auth.site_reference.expose(),
}],
transactionreference: vec![TrustpaymentsFilterValue {
value: transaction_reference,
}],
},
updates: TrustpaymentsCaptureUpdates {
settlestatus: TrustpaymentsSettleStatus::PendingSettlement,
},
}],
})
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsVoidRequest {
pub alias: String,
pub version: String,
pub request: Vec<TrustpaymentsVoidRequestData>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsVoidRequestData {
pub requesttypedescriptions: Vec<String>,
pub filter: TrustpaymentsFilter,
pub updates: TrustpaymentsVoidUpdates,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsVoidUpdates {
pub settlestatus: TrustpaymentsSettleStatus,
}
impl TryFrom<&PaymentsCancelRouterData> for TrustpaymentsVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let auth = TrustpaymentsAuthType::try_from(&item.connector_auth_type)?;
let transaction_reference = item.request.connector_transaction_id.clone();
Ok(Self {
alias: auth.username.expose(),
version: TRUSTPAYMENTS_API_VERSION.to_string(),
request: vec![TrustpaymentsVoidRequestData {
requesttypedescriptions: vec!["TRANSACTIONUPDATE".to_string()],
filter: TrustpaymentsFilter {
sitereference: vec![TrustpaymentsFilterValue {
value: auth.site_reference.expose(),
}],
transactionreference: vec![TrustpaymentsFilterValue {
value: transaction_reference,
}],
},
updates: TrustpaymentsVoidUpdates {
settlestatus: TrustpaymentsSettleStatus::Voided,
},
}],
})
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsRefundRequest {
pub alias: String,
pub version: String,
pub request: Vec<TrustpaymentsRefundRequestData>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsRefundRequestData {
pub requesttypedescriptions: Vec<String>,
pub sitereference: String,
pub parenttransactionreference: String,
pub baseamount: StringMinorUnit,
pub currencyiso3a: String,
}
impl<F> TryFrom<&TrustpaymentsRouterData<&RefundsRouterData<F>>> for TrustpaymentsRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &TrustpaymentsRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let auth = TrustpaymentsAuthType::try_from(&item.router_data.connector_auth_type)?;
let parent_transaction_reference =
item.router_data.request.connector_transaction_id.clone();
Ok(Self {
alias: auth.username.expose(),
version: TRUSTPAYMENTS_API_VERSION.to_string(),
request: vec![TrustpaymentsRefundRequestData {
requesttypedescriptions: vec!["REFUND".to_string()],
sitereference: auth.site_reference.expose(),
parenttransactionreference: parent_transaction_reference,
baseamount: item.amount.clone(),
currencyiso3a: item.router_data.request.currency.to_string(),
}],
})
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsSyncRequest {
pub alias: String,
pub version: String,
pub request: Vec<TrustpaymentsSyncRequestData>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsSyncRequestData {
pub requesttypedescriptions: Vec<String>,
pub filter: TrustpaymentsFilter,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsFilter {
pub sitereference: Vec<TrustpaymentsFilterValue>,
pub transactionreference: Vec<TrustpaymentsFilterValue>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsFilterValue {
pub value: String,
}
impl TryFrom<&PaymentsSyncRouterData> for TrustpaymentsSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let auth = TrustpaymentsAuthType::try_from(&item.connector_auth_type)?;
let transaction_reference = item
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(Self {
alias: auth.username.expose(),
version: TRUSTPAYMENTS_API_VERSION.to_string(),
request: vec![TrustpaymentsSyncRequestData {
requesttypedescriptions: vec!["TRANSACTIONQUERY".to_string()],
filter: TrustpaymentsFilter {
sitereference: vec![TrustpaymentsFilterValue {
value: auth.site_reference.expose(),
}],
transactionreference: vec![TrustpaymentsFilterValue {
value: transaction_reference,
}],
},
}],
})
}
}
pub type TrustpaymentsRefundSyncRequest = TrustpaymentsSyncRequest;
impl TryFrom<&RefundSyncRouterData> for TrustpaymentsRefundSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> {
let auth = TrustpaymentsAuthType::try_from(&item.connector_auth_type)?;
let refund_transaction_reference = item
.request
.get_connector_refund_id()
.change_context(errors::ConnectorError::MissingConnectorRefundID)?;
Ok(Self {
alias: auth.username.expose(),
version: TRUSTPAYMENTS_API_VERSION.to_string(),
request: vec![TrustpaymentsSyncRequestData {
requesttypedescriptions: vec!["TRANSACTIONQUERY".to_string()],
filter: TrustpaymentsFilter {
sitereference: vec![TrustpaymentsFilterValue {
value: auth.site_reference.expose(),
}],
transactionreference: vec![TrustpaymentsFilterValue {
value: refund_transaction_reference,
}],
},
}],
})
}
}
pub type RefundResponse = TrustpaymentsPaymentsResponse;
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let response_data = item
.response
.responses
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let refund_id = response_data
.transactionreference
.clone()
.unwrap_or_else(|| "unknown".to_string());
let refund_status = response_data.get_refund_status();
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: refund_id,
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let response_data = item
.response
.responses
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let refund_id = response_data
.transactionreference
.clone()
.unwrap_or_else(|| "unknown".to_string());
let refund_status = response_data.get_refund_status();
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: refund_id,
refund_status,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsTokenizationRequest {
pub alias: String,
pub version: String,
pub request: Vec<TrustpaymentsTokenizationRequestData>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct TrustpaymentsTokenizationRequestData {
pub accounttypedescription: String,
pub requesttypedescriptions: Vec<String>,
pub sitereference: String,
pub pan: cards::CardNumber,
pub expirydate: Secret<String>,
pub securitycode: Secret<String>,
pub credentialsonfile: String,
}
impl
TryFrom<
&RouterData<
hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken,
hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData,
PaymentsResponseData,
>,
> for TrustpaymentsTokenizationRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RouterData<
hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken,
hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let auth = TrustpaymentsAuthType::try_from(&item.connector_auth_type)?;
match &item.request.payment_method_data {
PaymentMethodData::Card(card_data) => Ok(Self {
alias: auth.username.expose(),
version: TRUSTPAYMENTS_API_VERSION.to_string(),
request: vec![TrustpaymentsTokenizationRequestData {
accounttypedescription: "ECOM".to_string(),
requesttypedescriptions: vec!["ACCOUNTCHECK".to_string()],
sitereference: auth.site_reference.expose(),
pan: card_data.card_number.clone(),
expirydate: card_data
.get_card_expiry_month_year_2_digit_with_delimiter("/".to_string())?,
securitycode: card_data.card_cvc.clone(),
credentialsonfile:
TrustpaymentsCredentialsOnFile::CardholderInitiatedTransaction.to_string(),
}],
}),
_ => Err(errors::ConnectorError::NotImplemented(
"Payment method not supported for tokenization".to_string(),
)
.into()),
}
}
}
pub type TrustpaymentsTokenizationResponse = TrustpaymentsPaymentsResponse;
impl
TryFrom<
ResponseRouterData<
hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken,
TrustpaymentsTokenizationResponse,
hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData,
PaymentsResponseData,
>,
>
for RouterData<
hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken,
hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData,
PaymentsResponseData,
>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken,
TrustpaymentsTokenizationResponse,
hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_data = item
.response
.responses
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let status = response_data.get_payment_status();
let token = response_data
.transactionreference
.clone()
.unwrap_or_else(|| "unknown".to_string());
Ok(Self {
status,
response: Ok(PaymentsResponseData::TokenizationResponse { token }),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct TrustpaymentsErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
pub network_advice_code: Option<String>,
pub network_decline_code: Option<String>,
pub network_error_message: Option<String>,
}
impl TrustpaymentsErrorResponse {
pub fn get_connector_error_type(&self) -> errors::ConnectorError {
let error_code: TrustpaymentsErrorCode =
serde_json::from_str(&format!("\"{}\"", self.code))
.unwrap_or(TrustpaymentsErrorCode::Unknown(self.code.clone()));
match error_code {
TrustpaymentsErrorCode::InvalidCredentials
| TrustpaymentsErrorCode::AuthenticationFailed
| TrustpaymentsErrorCode::InvalidSiteReference
| TrustpaymentsErrorCode::AccessDenied
| TrustpaymentsErrorCode::InvalidUsernameOrPassword
| TrustpaymentsErrorCode::AccountSuspended => {
errors::ConnectorError::InvalidConnectorConfig {
config: "authentication",
}
}
TrustpaymentsErrorCode::InvalidCardNumber
| TrustpaymentsErrorCode::InvalidExpiryDate
| TrustpaymentsErrorCode::InvalidSecurityCode
| TrustpaymentsErrorCode::InvalidCardType
| TrustpaymentsErrorCode::CardExpired
| TrustpaymentsErrorCode::InvalidAmountValue => {
errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data",
}
}
TrustpaymentsErrorCode::InsufficientFunds
| TrustpaymentsErrorCode::CardDeclined
| TrustpaymentsErrorCode::CardRestricted
| TrustpaymentsErrorCode::InvalidMerchant
| TrustpaymentsErrorCode::TransactionNotPermitted
| TrustpaymentsErrorCode::ExceedsWithdrawalLimit
| TrustpaymentsErrorCode::SecurityViolation
| TrustpaymentsErrorCode::LostOrStolenCard
| TrustpaymentsErrorCode::SuspectedFraud
| TrustpaymentsErrorCode::ContactCardIssuer => {
errors::ConnectorError::FailedAtConnector {
message: self.message.clone(),
code: self.code.clone(),
}
}
TrustpaymentsErrorCode::GeneralProcessingError
| TrustpaymentsErrorCode::SystemError
| TrustpaymentsErrorCode::CommunicationError
| TrustpaymentsErrorCode::Timeout
| TrustpaymentsErrorCode::InvalidRequest => {
errors::ConnectorError::ProcessingStepFailed(None)
}
TrustpaymentsErrorCode::Processing => errors::ConnectorError::ProcessingStepFailed(
Some(bytes::Bytes::from("Transaction is being processed")),
),
TrustpaymentsErrorCode::MissingRequiredField
| TrustpaymentsErrorCode::InvalidFieldFormat
| TrustpaymentsErrorCode::InvalidFieldValue
| TrustpaymentsErrorCode::FieldTooLong
| TrustpaymentsErrorCode::FieldTooShort
| TrustpaymentsErrorCode::InvalidCurrency
| TrustpaymentsErrorCode::InvalidAmount
| TrustpaymentsErrorCode::NoSearchableFilter => {
errors::ConnectorError::MissingRequiredField {
field_name: "request_data",
}
}
TrustpaymentsErrorCode::Success => errors::ConnectorError::ProcessingStepFailed(Some(
bytes::Bytes::from("Unexpected success code in error response"),
)),
TrustpaymentsErrorCode::Unknown(_) => errors::ConnectorError::ProcessingStepFailed(
Some(bytes::Bytes::from(self.message.clone())),
),
}
}
}
impl From<TrustpaymentsPaymentResponseData> for TrustpaymentsErrorResponse {
fn from(response: TrustpaymentsPaymentResponseData) -> Self {
let error_reason = response.get_error_reason();
Self {
status_code: if response.errorcode.is_success() {
200
} else {
400
},
code: response.errorcode.to_string(),
message: response.errormessage,
reason: error_reason,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}
}
}
impl TrustpaymentsPaymentResponseData {
pub fn get_refund_status(&self) -> enums::RefundStatus {
match self.errorcode {
TrustpaymentsErrorCode::Success => match &self.settlestatus {
Some(TrustpaymentsSettleStatus::Settled) => enums::RefundStatus::Success,
Some(TrustpaymentsSettleStatus::PendingSettlement) => enums::RefundStatus::Pending,
Some(TrustpaymentsSettleStatus::ManualCapture) => enums::RefundStatus::Failure,
Some(TrustpaymentsSettleStatus::Voided) => enums::RefundStatus::Failure,
None => enums::RefundStatus::Success,
},
TrustpaymentsErrorCode::Processing => enums::RefundStatus::Pending,
_ => enums::RefundStatus::Failure,
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 10174
}
|
large_file_-1377527101646665663
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
</path>
<file>
use api_models::webhooks::IncomingWebhookEvent;
use cards::CardNumber;
use common_enums::{AttemptStatus, AuthenticationType, CountryAlpha2, Currency, RefundStatus};
use common_utils::{errors::CustomResult, ext_traits::XmlExt, pii::Email, types::FloatMajorUnit};
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::{
ApplePayWalletData, Card, GooglePayWalletData, PaymentMethodData, WalletData,
},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
Authorize, Capture, CompleteAuthorize, Execute, PreProcessing, RSync, SetupMandate, Void,
},
router_request_types::{
CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCaptureData,
PaymentsPreProcessingData, ResponseId,
},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{PaymentsResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
get_unimplemented_payment_method_error_message, to_currency_base_unit_asf64,
AddressDetailsData as _, CardData as _, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData as _, RouterData as _,
},
};
type Error = Report<ConnectorError>;
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum TransactionType {
Auth,
Capture,
Refund,
Sale,
Validate,
Void,
}
pub struct NmiAuthType {
pub(super) api_key: Secret<String>,
pub(super) public_key: Option<Secret<String>>,
}
impl TryFrom<&ConnectorAuthType> for NmiAuthType {
type Error = Error;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
public_key: None,
}),
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
public_key: Some(key1.to_owned()),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize)]
pub struct NmiRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for NmiRouterData<T> {
fn from((amount, router_data): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Serialize)]
pub struct NmiVaultRequest {
security_key: Secret<String>,
ccnumber: CardNumber,
ccexp: Secret<String>,
cvv: Secret<String>,
first_name: Secret<String>,
last_name: Secret<String>,
address1: Option<Secret<String>>,
address2: Option<Secret<String>>,
city: Option<String>,
state: Option<Secret<String>>,
zip: Option<Secret<String>>,
country: Option<CountryAlpha2>,
customer_vault: CustomerAction,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CustomerAction {
AddCustomer,
UpdateCustomer,
}
impl TryFrom<&PaymentsPreProcessingRouterData> for NmiVaultRequest {
type Error = Error;
fn try_from(item: &PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> {
let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?;
let (ccnumber, ccexp, cvv) = get_card_details(item.request.payment_method_data.clone())?;
let billing_details = item.get_billing_address()?;
let first_name = billing_details.get_first_name()?;
Ok(Self {
security_key: auth_type.api_key,
ccnumber,
ccexp,
cvv,
first_name: first_name.clone(),
last_name: billing_details
.get_last_name()
.unwrap_or(first_name)
.clone(),
address1: billing_details.line1.clone(),
address2: billing_details.line2.clone(),
city: billing_details.city.clone(),
state: billing_details.state.clone(),
country: billing_details.country,
zip: billing_details.zip.clone(),
customer_vault: CustomerAction::AddCustomer,
})
}
}
fn get_card_details(
payment_method_data: Option<PaymentMethodData>,
) -> CustomResult<(CardNumber, Secret<String>, Secret<String>), ConnectorError> {
match payment_method_data {
Some(PaymentMethodData::Card(ref card_details)) => Ok((
card_details.card_number.clone(),
card_details.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?,
card_details.card_cvc.clone(),
)),
_ => Err(
ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message("Nmi"))
.into(),
),
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NmiVaultResponse {
pub response: Response,
pub responsetext: String,
pub customer_vault_id: Option<Secret<String>>,
pub response_code: String,
pub transactionid: String,
}
impl
TryFrom<
ResponseRouterData<
PreProcessing,
NmiVaultResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
> for PaymentsPreProcessingRouterData
{
type Error = Error;
fn try_from(
item: ResponseRouterData<
PreProcessing,
NmiVaultResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let auth_type: NmiAuthType = (&item.data.connector_auth_type).try_into()?;
let amount_data = item
.data
.request
.amount
.ok_or(ConnectorError::MissingRequiredField {
field_name: "amount",
})?;
let currency_data =
item.data
.request
.currency
.ok_or(ConnectorError::MissingRequiredField {
field_name: "currency",
})?;
let (response, status) = match item.response.response {
Response::Approved => (
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::Nmi {
amount: to_currency_base_unit_asf64(amount_data, currency_data.to_owned())?
.to_string(),
currency: currency_data,
customer_vault_id: item
.response
.customer_vault_id
.ok_or(ConnectorError::MissingRequiredField {
field_name: "customer_vault_id",
})?
.peek()
.to_string(),
public_key: auth_type.public_key.ok_or(
ConnectorError::InvalidConnectorConfig {
config: "public_key",
},
)?,
order_id: item.data.connector_request_reference_id.clone(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transactionid),
incremental_authorization_allowed: None,
charges: None,
}),
AttemptStatus::AuthenticationPending,
),
Response::Declined | Response::Error => (
Err(ErrorResponse {
code: item.response.response_code,
message: item.response.responsetext.to_owned(),
reason: Some(item.response.responsetext),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.transactionid),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
AttemptStatus::Failure,
),
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct NmiCompleteRequest {
amount: FloatMajorUnit,
#[serde(rename = "type")]
transaction_type: TransactionType,
security_key: Secret<String>,
orderid: Option<String>,
customer_vault_id: Secret<String>,
email: Option<Email>,
cardholder_auth: Option<String>,
cavv: Option<String>,
xid: Option<String>,
eci: Option<String>,
cvv: Secret<String>,
three_ds_version: Option<String>,
directory_server_id: Option<Secret<String>>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum NmiRedirectResponse {
NmiRedirectResponseData(NmiRedirectResponseData),
NmiErrorResponseData(NmiErrorResponseData),
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NmiErrorResponseData {
pub code: String,
pub message: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NmiRedirectResponseData {
cavv: Option<String>,
xid: Option<String>,
eci: Option<String>,
card_holder_auth: Option<String>,
three_ds_version: Option<String>,
order_id: Option<String>,
directory_server_id: Option<Secret<String>>,
customer_vault_id: Secret<String>,
}
impl TryFrom<&NmiRouterData<&PaymentsCompleteAuthorizeRouterData>> for NmiCompleteRequest {
type Error = Error;
fn try_from(
item: &NmiRouterData<&PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let transaction_type = match item.router_data.request.is_auto_capture()? {
true => TransactionType::Sale,
false => TransactionType::Auth,
};
let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?;
let payload_data = item
.router_data
.request
.get_redirect_response_payload()?
.expose();
let three_ds_data: NmiRedirectResponseData = serde_json::from_value(payload_data)
.change_context(ConnectorError::MissingConnectorRedirectionPayload {
field_name: "three_ds_data",
})?;
let (_, _, cvv) = get_card_details(item.router_data.request.payment_method_data.clone())?;
Ok(Self {
amount: item.amount,
transaction_type,
security_key: auth_type.api_key,
orderid: three_ds_data.order_id,
customer_vault_id: three_ds_data.customer_vault_id,
email: item.router_data.request.email.clone(),
cvv,
cardholder_auth: three_ds_data.card_holder_auth,
cavv: three_ds_data.cavv,
xid: three_ds_data.xid,
eci: three_ds_data.eci,
three_ds_version: three_ds_data.three_ds_version,
directory_server_id: three_ds_data.directory_server_id,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NmiCompleteResponse {
pub response: Response,
pub responsetext: String,
pub authcode: Option<String>,
pub transactionid: String,
pub avsresponse: Option<String>,
pub cvvresponse: Option<String>,
pub orderid: String,
pub response_code: String,
customer_vault_id: Option<Secret<String>>,
}
impl
TryFrom<
ResponseRouterData<
CompleteAuthorize,
NmiCompleteResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
> for PaymentsCompleteAuthorizeRouterData
{
type Error = Error;
fn try_from(
item: ResponseRouterData<
CompleteAuthorize,
NmiCompleteResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let (response, status) = match item.response.response {
Response::Approved => (
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.transactionid),
redirection_data: Box::new(None),
mandate_reference: match item.response.customer_vault_id {
Some(vault_id) => Box::new(Some(
hyperswitch_domain_models::router_response_types::MandateReference {
connector_mandate_id: Some(vault_id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
},
)),
None => Box::new(None),
},
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
incremental_authorization_allowed: None,
charges: None,
}),
if item.data.request.is_auto_capture()? {
AttemptStatus::Charged
} else {
AttemptStatus::Authorized
},
),
Response::Declined | Response::Error => (
Err(get_nmi_error_response(item.response, item.http_code)),
AttemptStatus::Failure,
),
};
Ok(Self {
status,
response,
..item.data
})
}
}
fn get_nmi_error_response(response: NmiCompleteResponse, http_code: u16) -> ErrorResponse {
ErrorResponse {
code: response.response_code,
message: response.responsetext.to_owned(),
reason: Some(response.responsetext),
status_code: http_code,
attempt_status: None,
connector_transaction_id: Some(response.transactionid),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
#[derive(Debug, Serialize)]
pub struct NmiValidateRequest {
#[serde(rename = "type")]
transaction_type: TransactionType,
security_key: Secret<String>,
ccnumber: CardNumber,
ccexp: Secret<String>,
cvv: Secret<String>,
orderid: String,
customer_vault: CustomerAction,
}
#[derive(Debug, Serialize)]
pub struct NmiPaymentsRequest {
#[serde(rename = "type")]
transaction_type: TransactionType,
amount: FloatMajorUnit,
security_key: Secret<String>,
currency: Currency,
#[serde(flatten)]
payment_method: PaymentMethod,
#[serde(flatten)]
merchant_defined_field: Option<NmiMerchantDefinedField>,
orderid: String,
#[serde(skip_serializing_if = "Option::is_none")]
customer_vault: Option<CustomerAction>,
}
#[derive(Debug, Serialize)]
pub struct NmiMerchantDefinedField {
#[serde(flatten)]
inner: std::collections::BTreeMap<String, Secret<String>>,
}
impl NmiMerchantDefinedField {
pub fn new(metadata: &serde_json::Value) -> Self {
let metadata_as_string = metadata.to_string();
let hash_map: std::collections::BTreeMap<String, serde_json::Value> =
serde_json::from_str(&metadata_as_string).unwrap_or(std::collections::BTreeMap::new());
let inner = hash_map
.into_iter()
.enumerate()
.map(|(index, (hs_key, hs_value))| {
let nmi_key = format!("merchant_defined_field_{}", index + 1);
let nmi_value = format!("{hs_key}={hs_value}");
(nmi_key, Secret::new(nmi_value))
})
.collect();
Self { inner }
}
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymentMethod {
CardNonThreeDs(Box<CardData>),
CardThreeDs(Box<CardThreeDsData>),
GPay(Box<GooglePayData>),
ApplePay(Box<ApplePayData>),
MandatePayment(Box<MandatePayment>),
}
#[derive(Debug, Serialize)]
pub struct MandatePayment {
customer_vault_id: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct CardData {
ccnumber: CardNumber,
ccexp: Secret<String>,
cvv: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct CardThreeDsData {
ccnumber: CardNumber,
ccexp: Secret<String>,
email: Option<Email>,
cardholder_auth: Option<String>,
cavv: Option<Secret<String>>,
eci: Option<String>,
cvv: Secret<String>,
three_ds_version: Option<String>,
directory_server_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct GooglePayData {
googlepay_payment_data: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct ApplePayData {
applepay_payment_data: Secret<String>,
}
impl TryFrom<&NmiRouterData<&PaymentsAuthorizeRouterData>> for NmiPaymentsRequest {
type Error = Error;
fn try_from(item: &NmiRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
let transaction_type = match item.router_data.request.is_auto_capture()? {
true => TransactionType::Sale,
false => TransactionType::Auth,
};
let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?;
let amount = item.amount;
match item
.router_data
.request
.mandate_id
.clone()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id)
{
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_id,
)) => Ok(Self {
transaction_type,
security_key: auth_type.api_key,
amount,
currency: item.router_data.request.currency,
payment_method: PaymentMethod::MandatePayment(Box::new(MandatePayment {
customer_vault_id: Secret::new(
connector_mandate_id
.get_connector_mandate_id()
.ok_or(ConnectorError::MissingConnectorMandateID)?,
),
})),
merchant_defined_field: item
.router_data
.request
.metadata
.as_ref()
.map(NmiMerchantDefinedField::new),
orderid: item.router_data.connector_request_reference_id.clone(),
customer_vault: None,
}),
Some(api_models::payments::MandateReferenceId::NetworkMandateId(_))
| Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_)) => {
Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("nmi"),
))?
}
None => {
let payment_method = PaymentMethod::try_from((
&item.router_data.request.payment_method_data,
Some(item.router_data),
))?;
Ok(Self {
transaction_type,
security_key: auth_type.api_key,
amount,
currency: item.router_data.request.currency,
payment_method,
merchant_defined_field: item
.router_data
.request
.metadata
.as_ref()
.map(NmiMerchantDefinedField::new),
orderid: item.router_data.connector_request_reference_id.clone(),
customer_vault: item
.router_data
.request
.is_mandate_payment()
.then_some(CustomerAction::AddCustomer),
})
}
}
}
}
impl TryFrom<(&PaymentMethodData, Option<&PaymentsAuthorizeRouterData>)> for PaymentMethod {
type Error = Error;
fn try_from(
item: (&PaymentMethodData, Option<&PaymentsAuthorizeRouterData>),
) -> Result<Self, Self::Error> {
let (payment_method_data, router_data) = item;
match payment_method_data {
PaymentMethodData::Card(ref card) => match router_data {
Some(data) => match data.auth_type {
AuthenticationType::NoThreeDs => Ok(Self::try_from(card)?),
AuthenticationType::ThreeDs => Ok(Self::try_from((card, &data.request))?),
},
None => Ok(Self::try_from(card)?),
},
PaymentMethodData::Wallet(ref wallet_type) => match wallet_type {
WalletData::GooglePay(ref googlepay_data) => Ok(Self::try_from(googlepay_data)?),
WalletData::ApplePay(ref applepay_data) => Ok(Self::try_from(applepay_data)?),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::AmazonPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(report!(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("nmi"),
))),
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Err(
ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message(
"nmi",
))
.into(),
),
}
}
}
impl TryFrom<(&Card, &PaymentsAuthorizeData)> for PaymentMethod {
type Error = Error;
fn try_from(val: (&Card, &PaymentsAuthorizeData)) -> Result<Self, Self::Error> {
let (card_data, item) = val;
let auth_data = &item.get_authentication_data()?;
let ccexp = card_data.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?;
let card_3ds_details = CardThreeDsData {
ccnumber: card_data.card_number.clone(),
ccexp,
cvv: card_data.card_cvc.clone(),
email: item.email.clone(),
cavv: Some(auth_data.cavv.clone()),
eci: auth_data.eci.clone(),
cardholder_auth: None,
three_ds_version: auth_data
.message_version
.clone()
.map(|version| version.to_string()),
directory_server_id: auth_data
.threeds_server_transaction_id
.clone()
.map(Secret::new),
};
Ok(Self::CardThreeDs(Box::new(card_3ds_details)))
}
}
impl TryFrom<&Card> for PaymentMethod {
type Error = Error;
fn try_from(card: &Card) -> Result<Self, Self::Error> {
let ccexp = card.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?;
let card = CardData {
ccnumber: card.card_number.clone(),
ccexp,
cvv: card.card_cvc.clone(),
};
Ok(Self::CardNonThreeDs(Box::new(card)))
}
}
impl TryFrom<&GooglePayWalletData> for PaymentMethod {
type Error = Report<ConnectorError>;
fn try_from(wallet_data: &GooglePayWalletData) -> Result<Self, Self::Error> {
let gpay_data = GooglePayData {
googlepay_payment_data: Secret::new(
wallet_data
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?
.clone(),
),
};
Ok(Self::GPay(Box::new(gpay_data)))
}
}
impl TryFrom<&ApplePayWalletData> for PaymentMethod {
type Error = Error;
fn try_from(apple_pay_wallet_data: &ApplePayWalletData) -> Result<Self, Self::Error> {
let apple_pay_encrypted_data = apple_pay_wallet_data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
let apple_pay_data = ApplePayData {
applepay_payment_data: Secret::new(apple_pay_encrypted_data.clone()),
};
Ok(Self::ApplePay(Box::new(apple_pay_data)))
}
}
impl TryFrom<&SetupMandateRouterData> for NmiValidateRequest {
type Error = Error;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
match item.request.amount {
Some(amount) if amount > 0 => Err(ConnectorError::FlowNotSupported {
flow: "Setup Mandate with non zero amount".to_string(),
connector: "NMI".to_string(),
}
.into()),
_ => {
if let PaymentMethodData::Card(card_details) = &item.request.payment_method_data {
let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?;
Ok(Self {
transaction_type: TransactionType::Validate,
security_key: auth_type.api_key,
ccnumber: card_details.card_number.clone(),
ccexp: card_details
.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?,
cvv: card_details.card_cvc.clone(),
orderid: item.connector_request_reference_id.clone(),
customer_vault: CustomerAction::AddCustomer,
})
} else {
Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Nmi"),
)
.into())
}
}
}
}
}
#[derive(Debug, Serialize)]
pub struct NmiSyncRequest {
pub order_id: String,
pub security_key: Secret<String>,
}
impl TryFrom<&PaymentsSyncRouterData> for NmiSyncRequest {
type Error = Error;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let auth = NmiAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
security_key: auth.api_key,
order_id: item.attempt_id.clone(),
})
}
}
#[derive(Debug, Serialize)]
pub struct NmiCaptureRequest {
#[serde(rename = "type")]
pub transaction_type: TransactionType,
pub security_key: Secret<String>,
pub transactionid: String,
pub amount: Option<FloatMajorUnit>,
}
impl TryFrom<&NmiRouterData<&PaymentsCaptureRouterData>> for NmiCaptureRequest {
type Error = Error;
fn try_from(item: &NmiRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let auth = NmiAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
transaction_type: TransactionType::Capture,
security_key: auth.api_key,
transactionid: item.router_data.request.connector_transaction_id.clone(),
amount: Some(item.amount),
})
}
}
impl
TryFrom<
ResponseRouterData<Capture, StandardResponse, PaymentsCaptureData, PaymentsResponseData>,
> for RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<
Capture,
StandardResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let (response, status) = match item.response.response {
Response::Approved => (
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transactionid.to_owned(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
incremental_authorization_allowed: None,
charges: None,
}),
AttemptStatus::Charged,
),
Response::Declined | Response::Error => (
Err(get_standard_error_response(item.response, item.http_code)),
AttemptStatus::CaptureFailed,
),
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct NmiCancelRequest {
#[serde(rename = "type")]
pub transaction_type: TransactionType,
pub security_key: Secret<String>,
pub transactionid: String,
pub void_reason: NmiVoidReason,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum NmiVoidReason {
Fraud,
UserCancel,
IccRejected,
IccCardRemoved,
IccNoConfirmation,
PosTimeout,
}
impl TryFrom<&PaymentsCancelRouterData> for NmiCancelRequest {
type Error = Error;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let auth = NmiAuthType::try_from(&item.connector_auth_type)?;
match &item.request.cancellation_reason {
Some(cancellation_reason) => {
let void_reason: NmiVoidReason = serde_json::from_str(&format!("\"{cancellation_reason}\"", ))
.map_err(|_| ConnectorError::NotSupported {
message: format!("Json deserialise error: unknown variant `{cancellation_reason}` expected to be one of `fraud`, `user_cancel`, `icc_rejected`, `icc_card_removed`, `icc_no_confirmation`, `pos_timeout`. This cancellation_reason"),
connector: "nmi"
})?;
Ok(Self {
transaction_type: TransactionType::Void,
security_key: auth.api_key,
transactionid: item.request.connector_transaction_id.clone(),
void_reason,
})
}
None => Err(ConnectorError::MissingRequiredField {
field_name: "cancellation_reason",
}
.into()),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub enum Response {
#[serde(alias = "1")]
Approved,
#[serde(alias = "2")]
Declined,
#[serde(alias = "3")]
Error,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StandardResponse {
pub response: Response,
pub responsetext: String,
pub authcode: Option<String>,
pub transactionid: String,
pub avsresponse: Option<String>,
pub cvvresponse: Option<String>,
pub orderid: String,
pub response_code: String,
pub customer_vault_id: Option<Secret<String>>,
}
impl<T> TryFrom<ResponseRouterData<SetupMandate, StandardResponse, T, PaymentsResponseData>>
for RouterData<SetupMandate, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<SetupMandate, StandardResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (response, status) = match item.response.response {
Response::Approved => (
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transactionid.clone(),
),
redirection_data: Box::new(None),
mandate_reference: match item.response.customer_vault_id {
Some(vault_id) => Box::new(Some(
hyperswitch_domain_models::router_response_types::MandateReference {
connector_mandate_id: Some(vault_id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
},
)),
None => Box::new(None),
},
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
incremental_authorization_allowed: None,
charges: None,
}),
AttemptStatus::Charged,
),
Response::Declined | Response::Error => (
Err(get_standard_error_response(item.response, item.http_code)),
AttemptStatus::Failure,
),
};
Ok(Self {
status,
response,
..item.data
})
}
}
fn get_standard_error_response(response: StandardResponse, http_code: u16) -> ErrorResponse {
ErrorResponse {
code: response.response_code,
message: response.responsetext.to_owned(),
reason: Some(response.responsetext),
status_code: http_code,
attempt_status: None,
connector_transaction_id: Some(response.transactionid),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
impl TryFrom<PaymentsResponseRouterData<StandardResponse>>
for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<
Authorize,
StandardResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let (response, status) = match item.response.response {
Response::Approved => (
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transactionid.clone(),
),
redirection_data: Box::new(None),
mandate_reference: match item.response.customer_vault_id {
Some(vault_id) => Box::new(Some(
hyperswitch_domain_models::router_response_types::MandateReference {
connector_mandate_id: Some(vault_id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
},
)),
None => Box::new(None),
},
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
incremental_authorization_allowed: None,
charges: None,
}),
if item.data.request.is_auto_capture()? {
AttemptStatus::Charged
} else {
AttemptStatus::Authorized
},
),
Response::Declined | Response::Error => (
Err(get_standard_error_response(item.response, item.http_code)),
AttemptStatus::Failure,
),
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl<T> TryFrom<ResponseRouterData<Void, StandardResponse, T, PaymentsResponseData>>
for RouterData<Void, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<Void, StandardResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (response, status) = match item.response.response {
Response::Approved => (
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transactionid.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
incremental_authorization_allowed: None,
charges: None,
}),
AttemptStatus::VoidInitiated,
),
Response::Declined | Response::Error => (
Err(get_standard_error_response(item.response, item.http_code)),
AttemptStatus::VoidFailed,
),
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NmiStatus {
Abandoned,
Cancelled,
Pendingsettlement,
Pending,
Failed,
Complete,
InProgress,
Unknown,
}
impl<F, T> TryFrom<ResponseRouterData<F, SyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, SyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.transaction {
Some(trn) => Ok(Self {
status: AttemptStatus::from(NmiStatus::from(trn.condition)),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(trn.transaction_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
None => Ok(Self { ..item.data }), //when there is empty connector response i.e. response we get in psync when payment status is in authentication_pending
}
}
}
impl TryFrom<Vec<u8>> for SyncResponse {
type Error = Error;
fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
let query_response = String::from_utf8(bytes)
.change_context(ConnectorError::ResponseDeserializationFailed)?;
query_response
.parse_xml::<Self>()
.change_context(ConnectorError::ResponseDeserializationFailed)
}
}
impl TryFrom<Vec<u8>> for NmiRefundSyncResponse {
type Error = Error;
fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
let query_response = String::from_utf8(bytes)
.change_context(ConnectorError::ResponseDeserializationFailed)?;
query_response
.parse_xml::<Self>()
.change_context(ConnectorError::ResponseDeserializationFailed)
}
}
impl From<NmiStatus> for AttemptStatus {
fn from(item: NmiStatus) -> Self {
match item {
NmiStatus::Abandoned => Self::AuthenticationFailed,
NmiStatus::Cancelled => Self::Voided,
NmiStatus::Pending => Self::Authorized,
NmiStatus::Pendingsettlement | NmiStatus::Complete => Self::Charged,
NmiStatus::InProgress => Self::AuthenticationPending,
NmiStatus::Failed | NmiStatus::Unknown => Self::Failure,
}
}
}
// REFUND :
#[derive(Debug, Serialize)]
pub struct NmiRefundRequest {
#[serde(rename = "type")]
transaction_type: TransactionType,
security_key: Secret<String>,
transactionid: String,
orderid: String,
amount: FloatMajorUnit,
}
impl<F> TryFrom<&NmiRouterData<&RefundsRouterData<F>>> for NmiRefundRequest {
type Error = Error;
fn try_from(item: &NmiRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?;
Ok(Self {
transaction_type: TransactionType::Refund,
security_key: auth_type.api_key,
transactionid: item.router_data.request.connector_transaction_id.clone(),
orderid: item.router_data.request.refund_id.clone(),
amount: item.amount,
})
}
}
impl TryFrom<RefundsResponseRouterData<Execute, StandardResponse>> for RefundsRouterData<Execute> {
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<Execute, StandardResponse>,
) -> Result<Self, Self::Error> {
let refund_status = RefundStatus::from(item.response.response);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.orderid,
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<Capture, StandardResponse>> for RefundsRouterData<Capture> {
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<Capture, StandardResponse>,
) -> Result<Self, Self::Error> {
let refund_status = RefundStatus::from(item.response.response);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transactionid,
refund_status,
}),
..item.data
})
}
}
impl From<Response> for RefundStatus {
fn from(item: Response) -> Self {
match item {
Response::Approved => Self::Success,
Response::Declined | Response::Error => Self::Failure,
}
}
}
impl TryFrom<&RefundSyncRouterData> for NmiSyncRequest {
type Error = Error;
fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> {
let auth = NmiAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
security_key: auth.api_key,
order_id: item
.request
.connector_refund_id
.clone()
.ok_or(ConnectorError::MissingConnectorRefundID)?,
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, NmiRefundSyncResponse>> for RefundsRouterData<RSync> {
type Error = Report<ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, NmiRefundSyncResponse>,
) -> Result<Self, Self::Error> {
let refund_status =
RefundStatus::from(NmiStatus::from(item.response.transaction.condition));
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction.order_id,
refund_status,
}),
..item.data
})
}
}
impl From<NmiStatus> for RefundStatus {
fn from(item: NmiStatus) -> Self {
match item {
NmiStatus::Abandoned
| NmiStatus::Cancelled
| NmiStatus::Failed
| NmiStatus::Unknown => Self::Failure,
NmiStatus::Pending | NmiStatus::InProgress => Self::Pending,
NmiStatus::Pendingsettlement | NmiStatus::Complete => Self::Success,
}
}
}
impl From<String> for NmiStatus {
fn from(value: String) -> Self {
match value.as_str() {
"abandoned" => Self::Abandoned,
"canceled" => Self::Cancelled,
"in_progress" => Self::InProgress,
"pendingsettlement" => Self::Pendingsettlement,
"complete" => Self::Complete,
"failed" => Self::Failed,
"unknown" => Self::Unknown,
// Other than above values only pending is possible, since value is a string handling this as default
_ => Self::Pending,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct SyncTransactionResponse {
pub transaction_id: String,
pub condition: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct SyncResponse {
pub transaction: Option<SyncTransactionResponse>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RefundSyncBody {
order_id: String,
condition: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NmiRefundSyncResponse {
transaction: RefundSyncBody,
}
#[derive(Debug, Deserialize)]
pub struct NmiWebhookObjectReference {
pub event_body: NmiReferenceBody,
}
#[derive(Debug, Deserialize)]
pub struct NmiReferenceBody {
pub order_id: String,
pub action: NmiActionBody,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NmiActionBody {
pub action_type: NmiActionType,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum NmiActionType {
Auth,
Capture,
Credit,
Refund,
Sale,
Void,
}
#[derive(Debug, Deserialize)]
pub struct NmiWebhookEventBody {
pub event_type: NmiWebhookEventType,
}
#[derive(Debug, Deserialize, Serialize)]
pub enum NmiWebhookEventType {
#[serde(rename = "transaction.sale.success")]
SaleSuccess,
#[serde(rename = "transaction.sale.failure")]
SaleFailure,
#[serde(rename = "transaction.sale.unknown")]
SaleUnknown,
#[serde(rename = "transaction.auth.success")]
AuthSuccess,
#[serde(rename = "transaction.auth.failure")]
AuthFailure,
#[serde(rename = "transaction.auth.unknown")]
AuthUnknown,
#[serde(rename = "transaction.refund.success")]
RefundSuccess,
#[serde(rename = "transaction.refund.failure")]
RefundFailure,
#[serde(rename = "transaction.refund.unknown")]
RefundUnknown,
#[serde(rename = "transaction.void.success")]
VoidSuccess,
#[serde(rename = "transaction.void.failure")]
VoidFailure,
#[serde(rename = "transaction.void.unknown")]
VoidUnknown,
#[serde(rename = "transaction.capture.success")]
CaptureSuccess,
#[serde(rename = "transaction.capture.failure")]
CaptureFailure,
#[serde(rename = "transaction.capture.unknown")]
CaptureUnknown,
}
pub fn get_nmi_webhook_event(status: NmiWebhookEventType) -> IncomingWebhookEvent {
match status {
NmiWebhookEventType::SaleSuccess => IncomingWebhookEvent::PaymentIntentSuccess,
NmiWebhookEventType::SaleFailure => IncomingWebhookEvent::PaymentIntentFailure,
NmiWebhookEventType::RefundSuccess => IncomingWebhookEvent::RefundSuccess,
NmiWebhookEventType::RefundFailure => IncomingWebhookEvent::RefundFailure,
NmiWebhookEventType::VoidSuccess => IncomingWebhookEvent::PaymentIntentCancelled,
NmiWebhookEventType::AuthSuccess => IncomingWebhookEvent::PaymentIntentAuthorizationSuccess,
NmiWebhookEventType::CaptureSuccess => IncomingWebhookEvent::PaymentIntentCaptureSuccess,
NmiWebhookEventType::AuthFailure => IncomingWebhookEvent::PaymentIntentAuthorizationFailure,
NmiWebhookEventType::CaptureFailure => IncomingWebhookEvent::PaymentIntentCaptureFailure,
NmiWebhookEventType::VoidFailure => IncomingWebhookEvent::PaymentIntentCancelFailure,
NmiWebhookEventType::SaleUnknown
| NmiWebhookEventType::RefundUnknown
| NmiWebhookEventType::AuthUnknown
| NmiWebhookEventType::VoidUnknown
| NmiWebhookEventType::CaptureUnknown => IncomingWebhookEvent::EventNotSupported,
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NmiWebhookBody {
pub event_body: NmiWebhookObject,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NmiWebhookObject {
pub transaction_id: String,
pub order_id: String,
pub condition: String,
pub action: NmiActionBody,
}
impl TryFrom<&NmiWebhookBody> for SyncResponse {
type Error = Error;
fn try_from(item: &NmiWebhookBody) -> Result<Self, Self::Error> {
let transaction = Some(SyncTransactionResponse {
transaction_id: item.event_body.transaction_id.to_owned(),
condition: item.event_body.condition.to_owned(),
});
Ok(Self { transaction })
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 10437
}
|
large_file_-4158946106142091581
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs
</path>
<file>
use common_enums::enums;
use common_utils::{
request::Method,
types::{MinorUnit, StringMinorUnit, StringMinorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankDebitData, PaymentMethodData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, PaymentsAuthorizeRequestData, RouterData as _},
};
pub struct InespayRouterData<T> {
pub amount: StringMinorUnit,
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for InespayRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct InespayPaymentsRequest {
description: String,
amount: StringMinorUnit,
reference: String,
debtor_account: Option<Secret<String>>,
success_link_redirect: Option<String>,
notif_url: Option<String>,
}
impl TryFrom<&InespayRouterData<&PaymentsAuthorizeRouterData>> for InespayPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &InespayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => {
let order_id = item.router_data.connector_request_reference_id.clone();
let webhook_url = item.router_data.request.get_webhook_url()?;
let return_url = item.router_data.request.get_router_return_url()?;
Ok(Self {
description: item.router_data.get_description()?,
amount: item.amount.clone(),
reference: order_id,
debtor_account: Some(iban),
success_link_redirect: Some(return_url),
notif_url: Some(webhook_url),
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
pub struct InespayAuthType {
pub(super) api_key: Secret<String>,
pub authorization: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for InespayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
authorization: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct InespayPaymentsResponseData {
status: String,
status_desc: String,
single_payin_id: String,
single_payin_link: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum InespayPaymentsResponse {
InespayPaymentsData(InespayPaymentsResponseData),
InespayPaymentsError(InespayErrorResponse),
}
impl<F, T> TryFrom<ResponseRouterData<F, InespayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, InespayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, response) = match item.response {
InespayPaymentsResponse::InespayPaymentsData(data) => {
let redirection_url = Url::parse(data.single_payin_link.as_str())
.change_context(errors::ConnectorError::ParsingFailed)?;
let redirection_data = RedirectForm::from((redirection_url, Method::Get));
(
common_enums::AttemptStatus::AuthenticationPending,
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
data.single_payin_id.clone(),
),
redirection_data: Box::new(Some(redirection_data)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
)
}
InespayPaymentsResponse::InespayPaymentsError(data) => (
common_enums::AttemptStatus::Failure,
Err(ErrorResponse {
code: data.status.clone(),
message: data.status_desc.clone(),
reason: Some(data.status_desc.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
),
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum InespayPSyncStatus {
Ok,
Created,
Opened,
BankSelected,
Initiated,
Pending,
Aborted,
Unfinished,
Rejected,
Cancelled,
PartiallyAccepted,
Failed,
Settled,
PartRefunded,
Refunded,
}
impl From<InespayPSyncStatus> for common_enums::AttemptStatus {
fn from(item: InespayPSyncStatus) -> Self {
match item {
InespayPSyncStatus::Ok | InespayPSyncStatus::Settled => Self::Charged,
InespayPSyncStatus::Created
| InespayPSyncStatus::Opened
| InespayPSyncStatus::BankSelected
| InespayPSyncStatus::Initiated
| InespayPSyncStatus::Pending
| InespayPSyncStatus::Unfinished
| InespayPSyncStatus::PartiallyAccepted => Self::AuthenticationPending,
InespayPSyncStatus::Aborted
| InespayPSyncStatus::Rejected
| InespayPSyncStatus::Cancelled
| InespayPSyncStatus::Failed => Self::Failure,
InespayPSyncStatus::PartRefunded | InespayPSyncStatus::Refunded => Self::AutoRefunded,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct InespayPSyncResponseData {
cod_status: InespayPSyncStatus,
status_desc: String,
single_payin_id: String,
single_payin_link: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum InespayPSyncResponse {
InespayPSyncData(InespayPSyncResponseData),
InespayPSyncWebhook(InespayPaymentWebhookData),
InespayPSyncError(InespayErrorResponse),
}
impl<F, T> TryFrom<ResponseRouterData<F, InespayPSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, InespayPSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
InespayPSyncResponse::InespayPSyncData(data) => {
let redirection_url = Url::parse(data.single_payin_link.as_str())
.change_context(errors::ConnectorError::ParsingFailed)?;
let redirection_data = RedirectForm::from((redirection_url, Method::Get));
Ok(Self {
status: common_enums::AttemptStatus::from(data.cod_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
data.single_payin_id.clone(),
),
redirection_data: Box::new(Some(redirection_data)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
InespayPSyncResponse::InespayPSyncWebhook(data) => {
let status = enums::AttemptStatus::from(data.cod_status);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
data.single_payin_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
InespayPSyncResponse::InespayPSyncError(data) => Ok(Self {
response: Err(ErrorResponse {
code: data.status.clone(),
message: data.status_desc.clone(),
reason: Some(data.status_desc.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct InespayRefundRequest {
single_payin_id: String,
amount: Option<MinorUnit>,
}
impl<F> TryFrom<&InespayRouterData<&RefundsRouterData<F>>> for InespayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &InespayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let amount = utils::convert_back_amount_to_minor_units(
&StringMinorUnitForConnector,
item.amount.to_owned(),
item.router_data.request.currency,
)?;
Ok(Self {
single_payin_id: item.router_data.request.connector_transaction_id.clone(),
amount: Some(amount),
})
}
}
#[derive(Debug, Serialize, Default, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum InespayRSyncStatus {
Confirmed,
#[default]
Pending,
Rejected,
Denied,
Reversed,
Mistake,
}
impl From<InespayRSyncStatus> for enums::RefundStatus {
fn from(item: InespayRSyncStatus) -> Self {
match item {
InespayRSyncStatus::Confirmed => Self::Success,
InespayRSyncStatus::Pending => Self::Pending,
InespayRSyncStatus::Rejected
| InespayRSyncStatus::Denied
| InespayRSyncStatus::Reversed
| InespayRSyncStatus::Mistake => Self::Failure,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundsData {
status: String,
status_desc: String,
refund_id: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum InespayRefundsResponse {
InespayRefundsData(RefundsData),
InespayRefundsError(InespayErrorResponse),
}
impl TryFrom<RefundsResponseRouterData<Execute, InespayRefundsResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, InespayRefundsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
InespayRefundsResponse::InespayRefundsData(data) => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: data.refund_id,
refund_status: enums::RefundStatus::Pending,
}),
..item.data
}),
InespayRefundsResponse::InespayRefundsError(data) => Ok(Self {
response: Err(ErrorResponse {
code: data.status.clone(),
message: data.status_desc.clone(),
reason: Some(data.status_desc.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct InespayRSyncResponseData {
cod_status: InespayRSyncStatus,
status_desc: String,
refund_id: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum InespayRSyncResponse {
InespayRSyncData(InespayRSyncResponseData),
InespayRSyncWebhook(InespayRefundWebhookData),
InespayRSyncError(InespayErrorResponse),
}
impl TryFrom<RefundsResponseRouterData<RSync, InespayRSyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, InespayRSyncResponse>,
) -> Result<Self, Self::Error> {
let response = match item.response {
InespayRSyncResponse::InespayRSyncData(data) => Ok(RefundsResponseData {
connector_refund_id: data.refund_id,
refund_status: enums::RefundStatus::from(data.cod_status),
}),
InespayRSyncResponse::InespayRSyncWebhook(data) => Ok(RefundsResponseData {
connector_refund_id: data.refund_id,
refund_status: enums::RefundStatus::from(data.cod_status),
}),
InespayRSyncResponse::InespayRSyncError(data) => Err(ErrorResponse {
code: data.status.clone(),
message: data.status_desc.clone(),
reason: Some(data.status_desc.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct InespayPaymentWebhookData {
pub single_payin_id: String,
pub cod_status: InespayPSyncStatus,
pub description: String,
pub amount: MinorUnit,
pub reference: String,
pub creditor_account: Secret<String>,
pub debtor_name: Secret<String>,
pub debtor_account: Secret<String>,
pub custom_data: Option<String>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct InespayRefundWebhookData {
pub refund_id: String,
pub simple_payin_id: String,
pub cod_status: InespayRSyncStatus,
pub description: String,
pub amount: MinorUnit,
pub reference: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum InespayWebhookEventData {
Payment(InespayPaymentWebhookData),
Refund(InespayRefundWebhookData),
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct InespayWebhookEvent {
pub data_return: String,
pub signature_data_return: String,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct InespayErrorResponse {
pub status: String,
pub status_desc: String,
}
impl From<InespayWebhookEventData> for api_models::webhooks::IncomingWebhookEvent {
fn from(item: InespayWebhookEventData) -> Self {
match item {
InespayWebhookEventData::Payment(payment_data) => match payment_data.cod_status {
InespayPSyncStatus::Ok | InespayPSyncStatus::Settled => Self::PaymentIntentSuccess,
InespayPSyncStatus::Failed | InespayPSyncStatus::Rejected => {
Self::PaymentIntentFailure
}
InespayPSyncStatus::Created
| InespayPSyncStatus::Opened
| InespayPSyncStatus::BankSelected
| InespayPSyncStatus::Initiated
| InespayPSyncStatus::Pending
| InespayPSyncStatus::Unfinished
| InespayPSyncStatus::PartiallyAccepted => Self::PaymentIntentProcessing,
InespayPSyncStatus::Aborted
| InespayPSyncStatus::Cancelled
| InespayPSyncStatus::PartRefunded
| InespayPSyncStatus::Refunded => Self::EventNotSupported,
},
InespayWebhookEventData::Refund(refund_data) => match refund_data.cod_status {
InespayRSyncStatus::Confirmed => Self::RefundSuccess,
InespayRSyncStatus::Rejected
| InespayRSyncStatus::Denied
| InespayRSyncStatus::Reversed
| InespayRSyncStatus::Mistake => Self::RefundFailure,
InespayRSyncStatus::Pending => Self::EventNotSupported,
},
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4028
}
|
large_file_2567803141310014431
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs
</path>
<file>
use api_models::payments::QrCodeInformation;
use common_enums::enums;
use common_utils::{errors::CustomResult, ext_traits::Encode, types::StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankTransferData, PaymentMethodData},
router_data::{AccessToken, ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{get_timestamp_in_milliseconds, QrImage, RouterData as _},
};
pub struct ItaubankRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for ItaubankRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct ItaubankPaymentsRequest {
valor: PixPaymentValue, // amount
chave: Secret<String>, // pix-key
devedor: ItaubankDebtor, // debtor
}
#[derive(Default, Debug, Serialize)]
pub struct PixPaymentValue {
original: StringMajorUnit,
}
#[derive(Default, Debug, Serialize)]
pub struct ItaubankDebtor {
#[serde(skip_serializing_if = "Option::is_none")]
cpf: Option<Secret<String>>, // CPF is a Brazilian tax identification number
#[serde(skip_serializing_if = "Option::is_none")]
cnpj: Option<Secret<String>>, // CNPJ is a Brazilian company tax identification number
#[serde(skip_serializing_if = "Option::is_none")]
nome: Option<Secret<String>>, // name of the debtor
}
impl TryFrom<&ItaubankRouterData<&types::PaymentsAuthorizeRouterData>> for ItaubankPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ItaubankRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankTransfer(bank_transfer_data) => {
match *bank_transfer_data {
BankTransferData::Pix {
pix_key, cpf, cnpj, ..
} => {
let nome = item.router_data.get_optional_billing_full_name();
// cpf and cnpj are mutually exclusive
let devedor = match (cnpj, cpf) {
(Some(cnpj), _) => ItaubankDebtor {
cpf: None,
cnpj: Some(cnpj),
nome,
},
(None, Some(cpf)) => ItaubankDebtor {
cpf: Some(cpf),
cnpj: None,
nome,
},
_ => Err(errors::ConnectorError::MissingRequiredField {
field_name: "cpf and cnpj both missing in payment_method_data",
})?,
};
Ok(Self {
valor: PixPaymentValue {
original: item.amount.to_owned(),
},
chave: pix_key.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "pix_key",
})?,
devedor,
})
}
BankTransferData::AchBankTransfer {}
| BankTransferData::SepaBankTransfer {}
| BankTransferData::BacsBankTransfer {}
| BankTransferData::MultibancoBankTransfer {}
| BankTransferData::PermataBankTransfer {}
| BankTransferData::BcaBankTransfer {}
| BankTransferData::BniVaBankTransfer {}
| BankTransferData::BriVaBankTransfer {}
| BankTransferData::CimbVaBankTransfer {}
| BankTransferData::DanamonVaBankTransfer {}
| BankTransferData::MandiriVaBankTransfer {}
| BankTransferData::Pse {}
| BankTransferData::InstantBankTransfer {}
| BankTransferData::InstantBankTransferFinland {}
| BankTransferData::InstantBankTransferPoland {}
| BankTransferData::IndonesianBankTransfer { .. }
| BankTransferData::LocalBankTransfer { .. } => {
Err(errors::ConnectorError::NotImplemented(
"Selected payment method through itaubank".to_string(),
)
.into())
}
}
}
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
"Selected payment method through itaubank".to_string(),
)
.into())
}
}
}
}
pub struct ItaubankAuthType {
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
pub(super) certificate: Option<Secret<String>>,
pub(super) certificate_key: Option<Secret<String>>,
}
impl TryFrom<&ConnectorAuthType> for ItaubankAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Ok(Self {
client_secret: api_key.to_owned(),
client_id: key1.to_owned(),
certificate: Some(api_secret.to_owned()),
certificate_key: Some(key2.to_owned()),
}),
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
client_secret: api_key.to_owned(),
client_id: key1.to_owned(),
certificate: None,
certificate_key: None,
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize)]
pub struct ItaubankAuthRequest {
client_id: Secret<String>,
client_secret: Secret<String>,
grant_type: ItaubankGrantType,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ItaubankGrantType {
ClientCredentials,
}
impl TryFrom<&types::RefreshTokenRouterData> for ItaubankAuthRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> {
let auth_details = ItaubankAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
client_id: auth_details.client_id,
client_secret: auth_details.client_secret,
grant_type: ItaubankGrantType::ClientCredentials,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ItaubankUpdateTokenResponse {
access_token: Secret<String>,
expires_in: i64,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ItaubankTokenErrorResponse {
pub status: i64,
pub title: Option<String>,
pub detail: Option<String>,
pub user_message: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, ItaubankUpdateTokenResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ItaubankUpdateTokenResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ItaubankPaymentStatus {
Ativa, // Active
Concluida, // Completed
RemovidaPeloPsp, // Removed by PSP
RemovidaPeloUsuarioRecebedor, // Removed by receiving User
}
impl From<ItaubankPaymentStatus> for enums::AttemptStatus {
fn from(item: ItaubankPaymentStatus) -> Self {
match item {
ItaubankPaymentStatus::Ativa => Self::AuthenticationPending,
ItaubankPaymentStatus::Concluida => Self::Charged,
ItaubankPaymentStatus::RemovidaPeloPsp
| ItaubankPaymentStatus::RemovidaPeloUsuarioRecebedor => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ItaubankPaymentsResponse {
status: ItaubankPaymentStatus,
calendario: ItaubankPixExpireTime,
txid: String,
#[serde(rename = "pixCopiaECola")]
pix_qr_value: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ItaubankPixExpireTime {
#[serde(with = "common_utils::custom_serde::iso8601")]
criacao: PrimitiveDateTime,
expiracao: i64,
}
impl<F, T> TryFrom<ResponseRouterData<F, ItaubankPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ItaubankPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let connector_metadata = get_qr_code_data(&item.response)?;
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.txid.to_owned()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(item.response.txid),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
fn get_qr_code_data(
response: &ItaubankPaymentsResponse,
) -> CustomResult<Option<serde_json::Value>, errors::ConnectorError> {
let creation_time = get_timestamp_in_milliseconds(&response.calendario.criacao);
// convert expiration to milliseconds and add to creation time
let expiration_time = creation_time + (response.calendario.expiracao * 1000);
let image_data = QrImage::new_from_data(response.pix_qr_value.clone())
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let image_data_url = Url::parse(image_data.data.clone().as_str())
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let qr_code_info = QrCodeInformation::QrDataUrl {
image_data_url,
display_to_timestamp: Some(expiration_time),
};
Some(qr_code_info.encode_to_value())
.transpose()
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ItaubankPaymentsSyncResponse {
status: ItaubankPaymentStatus,
txid: String,
pix: Vec<ItaubankPixResponse>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ItaubankPixResponse {
#[serde(rename = "endToEndId")]
pix_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ItaubankMetaData {
pub pix_id: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, ItaubankPaymentsSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ItaubankPaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let pix_data = item
.response
.pix
.first()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "pix_id",
})?
.to_owned();
let connector_metadata = Some(serde_json::json!(ItaubankMetaData {
pix_id: pix_data.pix_id
}));
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.txid.to_owned()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(item.response.txid),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct ItaubankRefundRequest {
pub valor: StringMajorUnit, // refund_amount
}
impl<F> TryFrom<&ItaubankRouterData<&types::RefundsRouterData<F>>> for ItaubankRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ItaubankRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
valor: item.amount.to_owned(),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundStatus {
EmProcessamento, // Processing
Devolvido, // Returned
NaoRealizado, // Unrealized
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Devolvido => Self::Success,
RefundStatus::NaoRealizado => Self::Failure,
RefundStatus::EmProcessamento => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
rtr_id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.rtr_id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.rtr_id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ItaubankErrorResponse {
pub error: ItaubankErrorBody,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ItaubankErrorBody {
pub status: u16,
pub title: Option<String>,
pub detail: Option<String>,
pub violacoes: Option<Vec<Violations>>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Violations {
pub razao: String,
pub propriedade: String,
pub valor: String,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3686
}
|
large_file_-245368530144937493
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
</path>
<file>
use common_enums::enums;
use common_utils::{pii::Email, request::Method, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::{refunds::Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{AddressDetailsData, PaymentsAuthorizeRequestData, RouterData as _},
};
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
pub struct Payer {
pub name: Option<Secret<String>>,
pub email: Option<Email>,
pub document: Secret<String>,
}
#[derive(Debug, Default, Eq, Clone, PartialEq, Serialize, Deserialize)]
pub struct Card {
pub holder_name: Secret<String>,
pub number: cards::CardNumber,
pub cvv: Secret<String>,
pub expiration_month: Secret<String>,
pub expiration_year: Secret<String>,
pub capture: String,
pub installments_id: Option<String>,
pub installments: Option<String>,
}
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
pub struct ThreeDSecureReqData {
pub force: bool,
}
#[derive(Debug, Serialize, Default, Deserialize, Clone, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaymentMethodId {
#[default]
Card,
}
#[derive(Debug, Serialize, Default, Deserialize, Clone, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaymentMethodFlow {
#[default]
Direct,
ReDirect,
}
#[derive(Debug, Serialize)]
pub struct DlocalRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for DlocalRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, router_data): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data,
})
}
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct DlocalPaymentsRequest {
pub amount: MinorUnit,
pub currency: enums::Currency,
pub country: String,
pub payment_method_id: PaymentMethodId,
pub payment_method_flow: PaymentMethodFlow,
pub payer: Payer,
pub card: Option<Card>,
pub order_id: String,
pub three_dsecure: Option<ThreeDSecureReqData>,
pub callback_url: Option<String>,
pub description: Option<String>,
}
impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DlocalRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let email = item.router_data.request.email.clone();
let address = item.router_data.get_billing_address()?;
let country = address.get_country()?;
let name = get_payer_name(address);
match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => {
let should_capture = matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
);
let payment_request = Self {
amount: item.amount,
currency: item.router_data.request.currency,
payment_method_id: PaymentMethodId::Card,
payment_method_flow: PaymentMethodFlow::Direct,
country: country.to_string(),
payer: Payer {
name,
email,
// [#589]: Allow securely collecting PII from customer in payments request
document: get_doc_from_currency(country.to_string()),
},
card: Some(Card {
holder_name: item
.router_data
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string())),
number: ccard.card_number.clone(),
cvv: ccard.card_cvc.clone(),
expiration_month: ccard.card_exp_month.clone(),
expiration_year: ccard.card_exp_year.clone(),
capture: should_capture.to_string(),
installments_id: item
.router_data
.request
.mandate_id
.as_ref()
.and_then(|ids| ids.mandate_id.clone()),
// [#595[FEATURE] Pass Mandate history information in payment flows/request]
installments: item
.router_data
.request
.mandate_id
.clone()
.map(|_| "1".to_string()),
}),
order_id: item.router_data.connector_request_reference_id.clone(),
three_dsecure: match item.router_data.auth_type {
enums::AuthenticationType::ThreeDs => {
Some(ThreeDSecureReqData { force: true })
}
enums::AuthenticationType::NoThreeDs => None,
},
callback_url: Some(item.router_data.request.get_router_return_url()?),
description: item.router_data.description.clone(),
};
Ok(payment_request)
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
crate::utils::get_unimplemented_payment_method_error_message("Dlocal"),
))?
}
}
}
}
fn get_payer_name(
address: &hyperswitch_domain_models::address::AddressDetails,
) -> Option<Secret<String>> {
let first_name = address
.first_name
.clone()
.map_or("".to_string(), |first_name| first_name.peek().to_string());
let last_name = address
.last_name
.clone()
.map_or("".to_string(), |last_name| last_name.peek().to_string());
let name: String = format!("{first_name} {last_name}").trim().to_string();
if !name.is_empty() {
Some(Secret::new(name))
} else {
None
}
}
pub struct DlocalPaymentsSyncRequest {
pub authz_id: String,
}
impl TryFrom<&types::PaymentsSyncRouterData> for DlocalPaymentsSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
Ok(Self {
authz_id: (item
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?),
})
}
}
pub struct DlocalPaymentsCancelRequest {
pub cancel_id: String,
}
impl TryFrom<&types::PaymentsCancelRouterData> for DlocalPaymentsCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Ok(Self {
cancel_id: item.request.connector_transaction_id.clone(),
})
}
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct DlocalPaymentsCaptureRequest {
pub authorization_id: String,
pub amount: i64,
pub currency: String,
pub order_id: String,
}
impl TryFrom<&types::PaymentsCaptureRouterData> for DlocalPaymentsCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
Ok(Self {
authorization_id: item.request.connector_transaction_id.clone(),
amount: item.request.amount_to_capture,
currency: item.request.currency.to_string(),
order_id: item.connector_request_reference_id.clone(),
})
}
}
// Auth Struct
pub struct DlocalAuthType {
pub(super) x_login: Secret<String>,
pub(super) x_trans_key: Secret<String>,
pub(super) secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for DlocalAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = auth_type
{
Ok(Self {
x_login: api_key.to_owned(),
x_trans_key: key1.to_owned(),
secret: api_secret.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
#[derive(Debug, Clone, Eq, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum DlocalPaymentStatus {
Authorized,
Paid,
Verified,
Cancelled,
#[default]
Pending,
Rejected,
}
impl From<DlocalPaymentStatus> for enums::AttemptStatus {
fn from(item: DlocalPaymentStatus) -> Self {
match item {
DlocalPaymentStatus::Authorized => Self::Authorized,
DlocalPaymentStatus::Verified => Self::Authorized,
DlocalPaymentStatus::Paid => Self::Charged,
DlocalPaymentStatus::Pending => Self::AuthenticationPending,
DlocalPaymentStatus::Cancelled => Self::Voided,
DlocalPaymentStatus::Rejected => Self::AuthenticationFailed,
}
}
}
#[derive(Eq, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ThreeDSecureResData {
pub redirect_url: Option<Url>,
}
#[derive(Debug, Default, Eq, Clone, PartialEq, Serialize, Deserialize)]
pub struct DlocalPaymentsResponse {
status: DlocalPaymentStatus,
id: String,
three_dsecure: Option<ThreeDSecureResData>,
order_id: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DlocalPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.three_dsecure
.and_then(|three_secure_data| three_secure_data.redirect_url)
.map(|redirect_url| RedirectForm::from((redirect_url, Method::Get)));
let response = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.order_id.clone(),
incremental_authorization_allowed: None,
charges: None,
};
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(response),
..item.data
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DlocalPaymentsSyncResponse {
status: DlocalPaymentStatus,
id: String,
order_id: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DlocalPaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.order_id.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DlocalPaymentsCaptureResponse {
status: DlocalPaymentStatus,
id: String,
order_id: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsCaptureResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DlocalPaymentsCaptureResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.order_id.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
pub struct DlocalPaymentsCancelResponse {
status: DlocalPaymentStatus,
order_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsCancelResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DlocalPaymentsCancelResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
#[derive(Default, Debug, Serialize)]
pub struct DlocalRefundRequest {
pub amount: String,
pub payment_id: String,
pub currency: enums::Currency,
pub id: String,
}
impl<F> TryFrom<&DlocalRouterData<&types::RefundsRouterData<F>>> for DlocalRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DlocalRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let amount_to_refund = item.router_data.request.refund_amount.to_string();
Ok(Self {
amount: amount_to_refund,
payment_id: item.router_data.request.connector_transaction_id.clone(),
currency: item.router_data.request.currency,
id: item.router_data.request.refund_id.clone(),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Success,
#[default]
Pending,
Rejected,
Cancelled,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Success => Self::Success,
RefundStatus::Pending => Self::Pending,
RefundStatus::Rejected => Self::ManualReview,
RefundStatus::Cancelled => Self::Failure,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
pub id: String,
pub status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
..item.data
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct DlocalRefundsSyncRequest {
pub refund_id: String,
}
impl TryFrom<&types::RefundSyncRouterData> for DlocalRefundsSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
let refund_id = match item.request.connector_refund_id.clone() {
Some(val) => val,
None => item.request.refund_id.clone(),
};
Ok(Self {
refund_id: (refund_id),
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DlocalErrorResponse {
pub code: i32,
pub message: String,
pub param: Option<String>,
}
fn get_doc_from_currency(country: String) -> Secret<String> {
let doc = match country.as_str() {
"BR" => "91483309223",
"ZA" => "2001014800086",
"BD" | "GT" | "HN" | "PK" | "SN" | "TH" => "1234567890001",
"CR" | "SV" | "VN" => "123456789",
"DO" | "NG" => "12345678901",
"EG" => "12345678901112",
"GH" | "ID" | "RW" | "UG" => "1234567890111123",
"IN" => "NHSTP6374G",
"CI" => "CA124356789",
"JP" | "MY" | "PH" => "123456789012",
"NI" => "1234567890111A",
"TZ" => "12345678912345678900",
_ => "12345678",
};
Secret::new(doc.to_string())
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4423
}
|
large_file_5603447531890045960
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs
</path>
<file>
use common_enums::enums;
use common_utils::{
ext_traits::OptionExt,
request::Method,
types::{FloatMajorUnit, MinorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
use hyperswitch_interfaces::{consts::NO_ERROR_CODE, errors};
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{PaymentsAuthorizeRequestData, RouterData as _},
};
#[derive(Debug, Serialize)]
pub struct RapydRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for RapydRouterData<T> {
fn from((amount, router_data): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct RapydPaymentsRequest {
pub amount: FloatMajorUnit,
pub currency: enums::Currency,
pub payment_method: PaymentMethod,
pub payment_method_options: Option<PaymentMethodOptions>,
pub merchant_reference_id: Option<String>,
pub capture: Option<bool>,
pub description: Option<String>,
pub complete_payment_url: Option<String>,
pub error_payment_url: Option<String>,
}
#[derive(Default, Debug, Serialize)]
pub struct PaymentMethodOptions {
#[serde(rename = "3d_required")]
pub three_ds: bool,
}
#[derive(Default, Debug, Serialize)]
pub struct PaymentMethod {
#[serde(rename = "type")]
pub pm_type: String,
pub fields: Option<PaymentFields>,
pub address: Option<Address>,
pub digital_wallet: Option<RapydWallet>,
}
#[derive(Default, Debug, Serialize)]
pub struct PaymentFields {
pub number: cards::CardNumber,
pub expiration_month: Secret<String>,
pub expiration_year: Secret<String>,
pub name: Secret<String>,
pub cvv: Secret<String>,
}
#[derive(Default, Debug, Serialize)]
pub struct Address {
name: Secret<String>,
line_1: Secret<String>,
line_2: Option<Secret<String>>,
line_3: Option<Secret<String>>,
city: Option<String>,
state: Option<Secret<String>>,
country: Option<String>,
zip: Option<Secret<String>>,
phone_number: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RapydWallet {
#[serde(rename = "type")]
payment_type: String,
#[serde(rename = "details")]
token: Option<Secret<String>>,
}
impl TryFrom<&RapydRouterData<&types::PaymentsAuthorizeRouterData>> for RapydPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RapydRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let (capture, payment_method_options) = match item.router_data.payment_method {
enums::PaymentMethod::Card => {
let three_ds_enabled = matches!(
item.router_data.auth_type,
enums::AuthenticationType::ThreeDs
);
let payment_method_options = PaymentMethodOptions {
three_ds: three_ds_enabled,
};
(
Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None
)),
Some(payment_method_options),
)
}
_ => (None, None),
};
let payment_method = match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => {
Some(PaymentMethod {
pm_type: "in_amex_card".to_owned(), //[#369] Map payment method type based on country
fields: Some(PaymentFields {
number: ccard.card_number.to_owned(),
expiration_month: ccard.card_exp_month.to_owned(),
expiration_year: ccard.card_exp_year.to_owned(),
name: item
.router_data
.get_optional_billing_full_name()
.to_owned()
.unwrap_or(Secret::new("".to_string())),
cvv: ccard.card_cvc.to_owned(),
}),
address: None,
digital_wallet: None,
})
}
PaymentMethodData::Wallet(ref wallet_data) => {
let digital_wallet = match wallet_data {
WalletData::GooglePay(data) => Some(RapydWallet {
payment_type: "google_pay".to_string(),
token: Some(Secret::new(
data.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?
.to_owned(),
)),
}),
WalletData::ApplePay(data) => {
let apple_pay_encrypted_data = data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
Some(RapydWallet {
payment_type: "apple_pay".to_string(),
token: Some(Secret::new(apple_pay_encrypted_data.to_string())),
})
}
_ => None,
};
Some(PaymentMethod {
pm_type: "by_visa_card".to_string(), //[#369]
fields: None,
address: None,
digital_wallet,
})
}
_ => None,
}
.get_required_value("payment_method not implemented")
.change_context(errors::ConnectorError::NotImplemented(
"payment_method".to_owned(),
))?;
let return_url = item.router_data.request.get_router_return_url()?;
Ok(Self {
amount: item.amount,
currency: item.router_data.request.currency,
payment_method,
capture,
payment_method_options,
merchant_reference_id: Some(item.router_data.connector_request_reference_id.clone()),
description: None,
error_payment_url: Some(return_url.clone()),
complete_payment_url: Some(return_url),
})
}
}
#[derive(Debug, Deserialize)]
pub struct RapydAuthType {
pub access_key: Secret<String>,
pub secret_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for RapydAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
access_key: api_key.to_owned(),
secret_key: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[allow(clippy::upper_case_acronyms)]
pub enum RapydPaymentStatus {
#[serde(rename = "ACT")]
Active,
#[serde(rename = "CAN")]
CanceledByClientOrBank,
#[serde(rename = "CLO")]
Closed,
#[serde(rename = "ERR")]
Error,
#[serde(rename = "EXP")]
Expired,
#[serde(rename = "REV")]
ReversedByRapyd,
#[default]
#[serde(rename = "NEW")]
New,
}
fn get_status(status: RapydPaymentStatus, next_action: NextAction) -> enums::AttemptStatus {
match (status, next_action) {
(RapydPaymentStatus::Closed, _) => enums::AttemptStatus::Charged,
(
RapydPaymentStatus::Active,
NextAction::ThreedsVerification | NextAction::PendingConfirmation,
) => enums::AttemptStatus::AuthenticationPending,
(RapydPaymentStatus::Active, NextAction::PendingCapture | NextAction::NotApplicable) => {
enums::AttemptStatus::Authorized
}
(
RapydPaymentStatus::CanceledByClientOrBank
| RapydPaymentStatus::Expired
| RapydPaymentStatus::ReversedByRapyd,
_,
) => enums::AttemptStatus::Voided,
(RapydPaymentStatus::Error, _) => enums::AttemptStatus::Failure,
(RapydPaymentStatus::New, _) => enums::AttemptStatus::Authorizing,
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RapydPaymentsResponse {
pub status: Status,
pub data: Option<ResponseData>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Status {
pub error_code: String,
pub status: Option<String>,
pub message: Option<String>,
pub response_code: Option<String>,
pub operation_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum NextAction {
#[serde(rename = "3d_verification")]
ThreedsVerification,
#[serde(rename = "pending_capture")]
PendingCapture,
#[serde(rename = "not_applicable")]
NotApplicable,
#[serde(rename = "pending_confirmation")]
PendingConfirmation,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ResponseData {
pub id: String,
pub amount: i64,
pub status: RapydPaymentStatus,
pub next_action: NextAction,
pub redirect_url: Option<String>,
pub original_amount: Option<i64>,
pub is_partial: Option<bool>,
pub currency_code: Option<enums::Currency>,
pub country_code: Option<String>,
pub captured: Option<bool>,
pub transaction_id: String,
pub merchant_reference_id: Option<String>,
pub paid: Option<bool>,
pub failure_code: Option<String>,
pub failure_message: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DisputeResponseData {
pub id: String,
pub amount: MinorUnit,
pub currency: api_models::enums::Currency,
pub token: String,
pub dispute_reason_description: String,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub due_date: Option<PrimitiveDateTime>,
pub status: RapydWebhookDisputeStatus,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub created_at: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub updated_at: Option<PrimitiveDateTime>,
pub original_transaction_id: String,
}
#[derive(Default, Debug, Serialize)]
pub struct RapydRefundRequest {
pub payment: String,
pub amount: Option<FloatMajorUnit>,
pub currency: Option<enums::Currency>,
}
impl<F> TryFrom<&RapydRouterData<&types::RefundsRouterData<F>>> for RapydRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RapydRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
payment: item
.router_data
.request
.connector_transaction_id
.to_string(),
amount: Some(item.amount),
currency: Some(item.router_data.request.currency),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub enum RefundStatus {
Completed,
Error,
Rejected,
#[default]
Pending,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Completed => Self::Success,
RefundStatus::Error | RefundStatus::Rejected => Self::Failure,
RefundStatus::Pending => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
pub status: Status,
pub data: Option<RefundResponseData>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RefundResponseData {
//Some field related to foreign exchange and split payment can be added as and when implemented
pub id: String,
pub payment: String,
pub amount: i64,
pub currency: enums::Currency,
pub status: RefundStatus,
pub created_at: Option<i64>,
pub failure_reason: Option<String>,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let (connector_refund_id, refund_status) = match item.response.data {
Some(data) => (data.id, enums::RefundStatus::from(data.status)),
None => (
item.response.status.error_code,
enums::RefundStatus::Failure,
),
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id,
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let (connector_refund_id, refund_status) = match item.response.data {
Some(data) => (data.id, enums::RefundStatus::from(data.status)),
None => (
item.response.status.error_code,
enums::RefundStatus::Failure,
),
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id,
refund_status,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Clone)]
pub struct CaptureRequest {
amount: Option<FloatMajorUnit>,
receipt_email: Option<Secret<String>>,
statement_descriptor: Option<String>,
}
impl TryFrom<&RapydRouterData<&types::PaymentsCaptureRouterData>> for CaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RapydRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: Some(item.amount),
receipt_email: None,
statement_descriptor: None,
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, RapydPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, RapydPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, response) = match &item.response.data {
Some(data) => {
let attempt_status =
get_status(data.status.to_owned(), data.next_action.to_owned());
match attempt_status {
enums::AttemptStatus::Failure => (
enums::AttemptStatus::Failure,
Err(ErrorResponse {
code: data
.failure_code
.to_owned()
.unwrap_or(item.response.status.error_code),
status_code: item.http_code,
message: item.response.status.status.unwrap_or_default(),
reason: data.failure_message.to_owned(),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
),
_ => {
let redirection_url = data
.redirect_url
.as_ref()
.filter(|redirect_str| !redirect_str.is_empty())
.map(|url| {
Url::parse(url).change_context(
errors::ConnectorError::FailedToObtainIntegrationUrl,
)
})
.transpose()?;
let redirection_data =
redirection_url.map(|url| RedirectForm::from((url, Method::Get)));
(
attempt_status,
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(data.id.to_owned()), //transaction_id is also the field but this id is used to initiate a refund
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: data
.merchant_reference_id
.to_owned(),
incremental_authorization_allowed: None,
charges: None,
}),
)
}
}
}
None => (
enums::AttemptStatus::Failure,
Err(ErrorResponse {
code: item.response.status.error_code,
status_code: item.http_code,
message: item.response.status.status.unwrap_or_default(),
reason: item.response.status.message,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
),
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Deserialize)]
pub struct RapydIncomingWebhook {
pub id: String,
#[serde(rename = "type")]
pub webhook_type: RapydWebhookObjectEventType,
pub data: WebhookData,
pub trigger_operation_id: Option<String>,
pub status: String,
pub created_at: i64,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RapydWebhookObjectEventType {
PaymentCompleted,
PaymentCaptured,
PaymentFailed,
RefundCompleted,
PaymentRefundRejected,
PaymentRefundFailed,
PaymentDisputeCreated,
PaymentDisputeUpdated,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, strum::Display)]
pub enum RapydWebhookDisputeStatus {
#[serde(rename = "ACT")]
Active,
#[serde(rename = "RVW")]
Review,
#[serde(rename = "LOS")]
Lose,
#[serde(rename = "WIN")]
Win,
#[serde(other)]
Unknown,
}
impl From<RapydWebhookDisputeStatus> for api_models::webhooks::IncomingWebhookEvent {
fn from(value: RapydWebhookDisputeStatus) -> Self {
match value {
RapydWebhookDisputeStatus::Active => Self::DisputeOpened,
RapydWebhookDisputeStatus::Review => Self::DisputeChallenged,
RapydWebhookDisputeStatus::Lose => Self::DisputeLost,
RapydWebhookDisputeStatus::Win => Self::DisputeWon,
RapydWebhookDisputeStatus::Unknown => Self::EventNotSupported,
}
}
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum WebhookData {
Payment(ResponseData),
Refund(RefundResponseData),
Dispute(DisputeResponseData),
}
impl From<ResponseData> for RapydPaymentsResponse {
fn from(value: ResponseData) -> Self {
Self {
status: Status {
error_code: NO_ERROR_CODE.to_owned(),
status: None,
message: None,
response_code: None,
operation_id: None,
},
data: Some(value),
}
}
}
impl From<RefundResponseData> for RefundResponse {
fn from(value: RefundResponseData) -> Self {
Self {
status: Status {
error_code: NO_ERROR_CODE.to_owned(),
status: None,
message: None,
response_code: None,
operation_id: None,
},
data: Some(value),
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4413
}
|
large_file_1241947452849820114
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
</path>
<file>
use base64::Engine;
use common_enums::enums;
use common_utils::{
ext_traits::ValueExt,
pii::{Email, IpAddress},
types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{
CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
PaymentsSyncData, ResponseId,
},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Deserializer, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, BrowserInformationData, CardData as _,
PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
PaymentsSyncRequestData, RouterData as _,
},
};
pub struct BamboraRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(FloatMajorUnit, T)> for BamboraRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (FloatMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct BamboraCard {
name: Secret<String>,
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvd: Secret<String>,
complete: bool,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "3d_secure")]
three_d_secure: Option<ThreeDSecure>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct ThreeDSecure {
browser: Option<BamboraBrowserInfo>, //Needed only in case of 3Ds 2.0. Need to update request for this.
enabled: bool,
version: Option<i64>,
auth_required: Option<bool>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct BamboraBrowserInfo {
accept_header: String,
java_enabled: bool,
language: String,
color_depth: u8,
screen_height: u32,
screen_width: u32,
time_zone: i32,
user_agent: String,
javascript_enabled: bool,
}
#[derive(Default, Debug, Serialize)]
pub struct BamboraPaymentsRequest {
order_number: String,
amount: FloatMajorUnit,
payment_method: PaymentMethod,
customer_ip: Option<Secret<String, IpAddress>>,
term_url: Option<String>,
card: BamboraCard,
billing: AddressData,
}
#[derive(Default, Debug, Serialize)]
pub struct BamboraVoidRequest {
amount: FloatMajorUnit,
}
fn get_browser_info(
item: &types::PaymentsAuthorizeRouterData,
) -> Result<Option<BamboraBrowserInfo>, error_stack::Report<errors::ConnectorError>> {
if matches!(item.auth_type, enums::AuthenticationType::ThreeDs) {
item.request
.browser_info
.as_ref()
.map(|info| {
Ok(BamboraBrowserInfo {
accept_header: info.get_accept_header()?,
java_enabled: info.get_java_enabled()?,
language: info.get_language()?,
screen_height: info.get_screen_height()?,
screen_width: info.get_screen_width()?,
color_depth: info.get_color_depth()?,
user_agent: info.get_user_agent()?,
time_zone: info.get_time_zone()?,
javascript_enabled: info.get_java_script_enabled()?,
})
})
.transpose()
} else {
Ok(None)
}
}
impl TryFrom<&CompleteAuthorizeData> for BamboraThreedsContinueRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &CompleteAuthorizeData) -> Result<Self, Self::Error> {
let card_response: CardResponse = value
.redirect_response
.as_ref()
.and_then(|f| f.payload.to_owned())
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response.payload",
})?
.parse_value("CardResponse")
.change_context(errors::ConnectorError::ParsingFailed)?;
let bambora_req = Self {
payment_method: "credit_card".to_string(),
card_response,
};
Ok(bambora_req)
}
}
impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for BamboraPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: BamboraRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let (three_ds, customer_ip) = match item.router_data.auth_type {
enums::AuthenticationType::ThreeDs => (
Some(ThreeDSecure {
enabled: true,
browser: get_browser_info(item.router_data)?,
version: Some(2),
auth_required: Some(true),
}),
Some(
item.router_data
.request
.get_browser_info()?
.get_ip_address()?,
),
),
enums::AuthenticationType::NoThreeDs => (None, None),
};
let card = BamboraCard {
name: item.router_data.get_billing_address()?.get_full_name()?,
expiry_year: req_card.get_card_expiry_year_2_digit()?,
number: req_card.card_number,
expiry_month: req_card.card_exp_month,
cvd: req_card.card_cvc,
three_d_secure: three_ds,
complete: item.router_data.request.is_auto_capture()?,
};
let (country, province) = match (
item.router_data.get_optional_billing_country(),
item.router_data.get_optional_billing_state_2_digit(),
) {
(Some(billing_country), Some(billing_state)) => {
(Some(billing_country), Some(billing_state))
}
_ => (None, None),
};
let billing = AddressData {
name: item.router_data.get_optional_billing_full_name(),
address_line1: item.router_data.get_optional_billing_line1(),
address_line2: item.router_data.get_optional_billing_line2(),
city: item.router_data.get_optional_billing_city(),
province,
country,
postal_code: item.router_data.get_optional_billing_zip(),
phone_number: item.router_data.get_optional_billing_phone_number(),
email_address: item.router_data.get_optional_billing_email(),
};
Ok(Self {
order_number: item.router_data.connector_request_reference_id.clone(),
amount: item.amount,
payment_method: PaymentMethod::Card,
card,
customer_ip,
term_url: item.router_data.request.complete_authorize_url.clone(),
billing,
})
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("bambora"),
)
.into())
}
}
}
}
impl TryFrom<BamboraRouterData<&types::PaymentsCancelRouterData>> for BamboraVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: BamboraRouterData<&types::PaymentsCancelRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
})
}
}
pub struct BamboraAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BamboraAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
let auth_key = format!("{}:{}", key1.peek(), api_key.peek());
let auth_header = format!(
"Passcode {}",
common_utils::consts::BASE64_ENGINE.encode(auth_key)
);
Ok(Self {
api_key: Secret::new(auth_header),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
fn str_or_i32<'de, D>(deserializer: D) -> Result<String, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum StrOrI32 {
Str(String),
I32(i32),
}
let value = StrOrI32::deserialize(deserializer)?;
let res = match value {
StrOrI32::Str(v) => v,
StrOrI32::I32(v) => v.to_string(),
};
Ok(res)
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BamboraResponse {
NormalTransaction(Box<BamboraPaymentsResponse>),
ThreeDsResponse(Box<Bambora3DsResponse>),
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct BamboraPaymentsResponse {
#[serde(deserialize_with = "str_or_i32")]
id: String,
authorizing_merchant_id: i32,
#[serde(deserialize_with = "str_or_i32")]
approved: String,
#[serde(deserialize_with = "str_or_i32")]
message_id: String,
message: String,
auth_code: String,
created: String,
amount: FloatMajorUnit,
order_number: String,
#[serde(rename = "type")]
payment_type: String,
comments: Option<String>,
batch_number: Option<String>,
total_refunds: Option<f32>,
total_completions: Option<f32>,
payment_method: String,
card: CardData,
billing: Option<AddressData>,
shipping: Option<AddressData>,
custom: CustomData,
adjusted_by: Option<Vec<AdjustedBy>>,
links: Vec<Links>,
risk_score: Option<f32>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Bambora3DsResponse {
#[serde(rename = "3d_session_data")]
three_d_session_data: Secret<String>,
contents: String,
}
#[derive(Debug, Serialize, Default, Deserialize)]
pub struct BamboraMeta {
pub three_d_session_data: String,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct BamboraThreedsContinueRequest {
pub(crate) payment_method: String,
pub card_response: CardResponse,
}
#[derive(Default, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct CardResponse {
pub(crate) cres: Option<common_utils::pii::SecretSerdeValue>,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct CardData {
name: Option<Secret<String>>,
expiry_month: Option<Secret<String>>,
expiry_year: Option<Secret<String>>,
card_type: String,
last_four: Secret<String>,
card_bin: Option<Secret<String>>,
avs_result: String,
cvd_result: String,
cavv_result: Option<String>,
address_match: Option<i32>,
postal_result: Option<i32>,
avs: Option<AvsObject>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AvsObject {
id: String,
message: String,
processed: bool,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AddressData {
name: Option<Secret<String>>,
address_line1: Option<Secret<String>>,
address_line2: Option<Secret<String>>,
city: Option<String>,
province: Option<Secret<String>>,
country: Option<enums::CountryAlpha2>,
postal_code: Option<Secret<String>>,
phone_number: Option<Secret<String>>,
email_address: Option<Email>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CustomData {
ref1: String,
ref2: String,
ref3: String,
ref4: String,
ref5: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AdjustedBy {
id: i32,
#[serde(rename = "type")]
adjusted_by_type: String,
approval: i32,
message: String,
amount: FloatMajorUnit,
created: String,
url: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Links {
rel: String,
href: String,
method: String,
}
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum PaymentMethod {
#[default]
Card,
Token,
PaymentProfile,
Cash,
Cheque,
Interac,
ApplePay,
AndroidPay,
#[serde(rename = "3d_secure")]
ThreeDSecure,
ProcessorToken,
}
// Capture
#[derive(Default, Debug, Clone, Serialize, PartialEq)]
pub struct BamboraPaymentsCaptureRequest {
amount: FloatMajorUnit,
payment_method: PaymentMethod,
}
impl TryFrom<BamboraRouterData<&types::PaymentsCaptureRouterData>>
for BamboraPaymentsCaptureRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: BamboraRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
payment_method: PaymentMethod::Card,
})
}
}
impl<F> TryFrom<ResponseRouterData<F, BamboraResponse, PaymentsAuthorizeData, PaymentsResponseData>>
for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BamboraResponse, PaymentsAuthorizeData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
BamboraResponse::NormalTransaction(pg_response) => Ok(Self {
status: if pg_response.approved.as_str() == "1" {
match item.data.request.is_auto_capture()? {
true => enums::AttemptStatus::Charged,
false => enums::AttemptStatus::Authorized,
}
} else {
match item.data.request.is_auto_capture()? {
true => enums::AttemptStatus::Failure,
false => enums::AttemptStatus::AuthorizationFailed,
}
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(pg_response.id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(pg_response.order_number.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
BamboraResponse::ThreeDsResponse(response) => {
let value = url::form_urlencoded::parse(response.contents.as_bytes())
.map(|(key, val)| [key, val].concat())
.collect();
let redirection_data = Some(RedirectForm::Html { html_data: value });
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(
serde_json::to_value(BamboraMeta {
three_d_session_data: response.three_d_session_data.expose(),
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)?,
),
network_txn_id: None,
connector_response_reference_id: Some(
item.data.connector_request_reference_id.to_string(),
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
}
}
impl<F>
TryFrom<
ResponseRouterData<F, BamboraPaymentsResponse, CompleteAuthorizeData, PaymentsResponseData>,
> for RouterData<F, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BamboraPaymentsResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: if item.response.approved.as_str() == "1" {
match item.data.request.is_auto_capture()? {
true => enums::AttemptStatus::Charged,
false => enums::AttemptStatus::Authorized,
}
} else {
match item.data.request.is_auto_capture()? {
true => enums::AttemptStatus::Failure,
false => enums::AttemptStatus::AuthorizationFailed,
}
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<F>
TryFrom<ResponseRouterData<F, BamboraPaymentsResponse, PaymentsSyncData, PaymentsResponseData>>
for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BamboraPaymentsResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: match item.data.request.is_auto_capture()? {
true => {
if item.response.approved.as_str() == "1" {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Failure
}
}
false => {
if item.response.approved.as_str() == "1" {
enums::AttemptStatus::Authorized
} else {
enums::AttemptStatus::AuthorizationFailed
}
}
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<F>
TryFrom<
ResponseRouterData<F, BamboraPaymentsResponse, PaymentsCaptureData, PaymentsResponseData>,
> for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BamboraPaymentsResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: if item.response.approved.as_str() == "1" {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Failure
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<F>
TryFrom<
ResponseRouterData<F, BamboraPaymentsResponse, PaymentsCancelData, PaymentsResponseData>,
> for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BamboraPaymentsResponse,
PaymentsCancelData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: if item.response.approved.as_str() == "1" {
enums::AttemptStatus::Voided
} else {
enums::AttemptStatus::VoidFailed
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct BamboraRefundRequest {
amount: FloatMajorUnit,
}
impl<F> TryFrom<BamboraRouterData<&types::RefundsRouterData<F>>> for BamboraRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: BamboraRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
#[serde(deserialize_with = "str_or_i32")]
pub id: String,
pub authorizing_merchant_id: i32,
#[serde(deserialize_with = "str_or_i32")]
pub approved: String,
#[serde(deserialize_with = "str_or_i32")]
pub message_id: String,
pub message: String,
pub auth_code: String,
pub created: String,
pub amount: FloatMajorUnit,
pub order_number: String,
#[serde(rename = "type")]
pub payment_type: String,
pub comments: Option<String>,
pub batch_number: Option<String>,
pub total_refunds: Option<f32>,
pub total_completions: Option<f32>,
pub payment_method: String,
pub card: CardData,
pub billing: Option<AddressData>,
pub shipping: Option<AddressData>,
pub custom: CustomData,
pub adjusted_by: Option<Vec<AdjustedBy>>,
pub links: Vec<Links>,
pub risk_score: Option<f32>,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = if item.response.approved.as_str() == "1" {
enums::RefundStatus::Success
} else {
enums::RefundStatus::Failure
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = if item.response.approved.as_str() == "1" {
enums::RefundStatus::Success
} else {
enums::RefundStatus::Failure
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status,
}),
..item.data
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct BamboraErrorResponse {
pub code: i32,
pub category: i32,
pub message: String,
pub reference: String,
pub details: Option<Vec<ErrorDetail>>,
pub validation: Option<CardValidation>,
pub card: Option<CardError>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CardError {
pub avs: AVSDetails,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AVSDetails {
pub message: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ErrorDetail {
field: String,
message: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CardValidation {
id: String,
approved: i32,
message_id: i32,
message: String,
auth_code: String,
trans_date: String,
order_number: String,
type_: String,
amount: f64,
cvd_id: i32,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5887
}
|
large_file_2479719544608429333
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs
</path>
<file>
use common_enums::{enums, CountryAlpha2, UsStatesAbbreviation};
use common_utils::{
id_type,
pii::{self, IpAddress},
types::MinorUnit,
};
use hyperswitch_domain_models::{
address::AddressDetails,
payment_method_data::{BankDebitData, PaymentMethodData},
router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
router_flow_types::refunds::Execute,
router_request_types::{
ConnectorCustomerData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsSyncData, ResponseId, SetupMandateRequestData,
},
router_response_types::{
ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, RefundsResponseData,
},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, BrowserInformationData, CustomerData, ForeignTryFrom,
PaymentsAuthorizeRequestData, PaymentsSetupMandateRequestData, RouterData as _,
},
};
pub struct GocardlessRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for GocardlessRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct GocardlessCustomerRequest {
customers: GocardlessCustomer,
}
#[derive(Default, Debug, Serialize)]
pub struct GocardlessCustomer {
address_line1: Option<Secret<String>>,
address_line2: Option<Secret<String>>,
address_line3: Option<Secret<String>>,
city: Option<Secret<String>>,
region: Option<Secret<String>>,
country_code: Option<CountryAlpha2>,
email: pii::Email,
given_name: Secret<String>,
family_name: Secret<String>,
metadata: CustomerMetaData,
danish_identity_number: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
swedish_identity_number: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize)]
pub struct CustomerMetaData {
crm_id: Option<Secret<id_type::CustomerId>>,
}
impl TryFrom<&types::ConnectorCustomerRouterData> for GocardlessCustomerRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> {
let email = item.request.get_email()?;
let billing_details_name = item.get_billing_full_name()?.expose();
let (given_name, family_name) = billing_details_name
.trim()
.rsplit_once(' ')
.unwrap_or((&billing_details_name, &billing_details_name));
let billing_address = item.get_billing_address()?;
let metadata = CustomerMetaData {
crm_id: item.customer_id.clone().map(Secret::new),
};
let region = get_region(billing_address)?;
Ok(Self {
customers: GocardlessCustomer {
email,
given_name: Secret::new(given_name.to_string()),
family_name: Secret::new(family_name.to_string()),
metadata,
address_line1: billing_address.line1.to_owned(),
address_line2: billing_address.line2.to_owned(),
address_line3: billing_address.line3.to_owned(),
country_code: billing_address.country,
region,
// Should be populated based on the billing country
danish_identity_number: None,
postal_code: billing_address.zip.to_owned(),
// Should be populated based on the billing country
swedish_identity_number: None,
city: billing_address.city.clone().map(Secret::new),
},
})
}
}
fn get_region(
address_details: &AddressDetails,
) -> Result<Option<Secret<String>>, error_stack::Report<errors::ConnectorError>> {
match address_details.country {
Some(CountryAlpha2::US) => {
let state = address_details.get_state()?.to_owned();
Ok(Some(Secret::new(
UsStatesAbbreviation::foreign_try_from(state.expose())?.to_string(),
)))
}
_ => Ok(None),
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GocardlessCustomerResponse {
customers: Customers,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Customers {
id: Secret<String>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
GocardlessCustomerResponse,
ConnectorCustomerData,
PaymentsResponseData,
>,
> for RouterData<F, ConnectorCustomerData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
GocardlessCustomerResponse,
ConnectorCustomerData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(
item.response.customers.id.expose(),
),
)),
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct GocardlessBankAccountRequest {
customer_bank_accounts: CustomerBankAccounts,
}
#[derive(Debug, Serialize)]
pub struct CustomerBankAccounts {
#[serde(flatten)]
accounts: CustomerBankAccount,
links: CustomerAccountLink,
}
#[derive(Debug, Serialize)]
pub struct CustomerAccountLink {
customer: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum CustomerBankAccount {
InternationalBankAccount(InternationalBankAccount),
AUBankAccount(AUBankAccount),
USBankAccount(USBankAccount),
}
#[derive(Debug, Serialize)]
pub struct InternationalBankAccount {
iban: Secret<String>,
account_holder_name: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct AUBankAccount {
country_code: CountryAlpha2,
account_number: Secret<String>,
branch_code: Secret<String>,
account_holder_name: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub struct USBankAccount {
country_code: CountryAlpha2,
account_number: Secret<String>,
bank_code: Secret<String>,
account_type: AccountType,
account_holder_name: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AccountType {
Checking,
Savings,
}
impl TryFrom<&types::TokenizationRouterData> for GocardlessBankAccountRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
let customer = item.get_connector_customer_id()?;
let accounts = CustomerBankAccount::try_from(item)?;
let links = CustomerAccountLink {
customer: Secret::new(customer),
};
Ok(Self {
customer_bank_accounts: CustomerBankAccounts { accounts, links },
})
}
}
impl TryFrom<&types::TokenizationRouterData> for CustomerBankAccount {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
match &item.request.payment_method_data {
PaymentMethodData::BankDebit(bank_debit_data) => {
Self::try_from((bank_debit_data, item))
}
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Gocardless"),
)
.into())
}
}
}
}
impl TryFrom<(&BankDebitData, &types::TokenizationRouterData)> for CustomerBankAccount {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(bank_debit_data, item): (&BankDebitData, &types::TokenizationRouterData),
) -> Result<Self, Self::Error> {
match bank_debit_data {
BankDebitData::AchBankDebit {
account_number,
routing_number,
bank_type,
..
} => {
let bank_type = bank_type.ok_or_else(utils::missing_field_err("bank_type"))?;
let country_code = item.get_billing_country()?;
let account_holder_name = item.get_billing_full_name()?;
let us_bank_account = USBankAccount {
country_code,
account_number: account_number.clone(),
bank_code: routing_number.clone(),
account_type: AccountType::from(bank_type),
account_holder_name,
};
Ok(Self::USBankAccount(us_bank_account))
}
BankDebitData::BecsBankDebit {
account_number,
bsb_number,
..
} => {
let country_code = item.get_billing_country()?;
let account_holder_name = item.get_billing_full_name()?;
let au_bank_account = AUBankAccount {
country_code,
account_number: account_number.clone(),
branch_code: bsb_number.clone(),
account_holder_name,
};
Ok(Self::AUBankAccount(au_bank_account))
}
BankDebitData::SepaBankDebit { iban, .. } => {
let account_holder_name = item.get_billing_full_name()?;
let international_bank_account = InternationalBankAccount {
iban: iban.clone(),
account_holder_name,
};
Ok(Self::InternationalBankAccount(international_bank_account))
}
BankDebitData::BacsBankDebit { .. } | BankDebitData::SepaGuarenteedBankDebit { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Gocardless"),
)
.into())
}
}
}
}
impl From<common_enums::BankType> for AccountType {
fn from(item: common_enums::BankType) -> Self {
match item {
common_enums::BankType::Checking => Self::Checking,
common_enums::BankType::Savings => Self::Savings,
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GocardlessBankAccountResponse {
customer_bank_accounts: CustomerBankAccountResponse,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CustomerBankAccountResponse {
pub id: Secret<String>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
GocardlessBankAccountResponse,
PaymentMethodTokenizationData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentMethodTokenizationData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
GocardlessBankAccountResponse,
PaymentMethodTokenizationData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.customer_bank_accounts.id.expose(),
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct GocardlessMandateRequest {
mandates: Mandate,
}
#[derive(Debug, Serialize)]
pub struct Mandate {
scheme: GocardlessScheme,
metadata: MandateMetaData,
payer_ip_address: Option<Secret<String, IpAddress>>,
links: MandateLink,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum GocardlessScheme {
Becs,
SepaCore,
Ach,
BecsNz,
}
#[derive(Debug, Serialize)]
pub struct MandateMetaData {
payment_reference: String,
}
#[derive(Debug, Serialize)]
pub struct MandateLink {
customer_bank_account: Secret<String>,
}
impl TryFrom<&types::SetupMandateRouterData> for GocardlessMandateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> {
let (scheme, payer_ip_address) = match &item.request.payment_method_data {
PaymentMethodData::BankDebit(bank_debit_data) => {
let payer_ip_address = get_ip_if_required(bank_debit_data, item)?;
Ok((
GocardlessScheme::try_from(bank_debit_data)?,
payer_ip_address,
))
}
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
"Setup Mandate flow for selected payment method through Gocardless".to_string(),
))
}
}?;
let payment_method_token = item.get_payment_method_token()?;
let customer_bank_account = match payment_method_token {
PaymentMethodToken::Token(token) => Ok(token),
PaymentMethodToken::ApplePayDecrypt(_)
| PaymentMethodToken::PazeDecrypt(_)
| PaymentMethodToken::GooglePayDecrypt(_) => {
Err(errors::ConnectorError::NotImplemented(
"Setup Mandate flow for selected payment method through Gocardless".to_string(),
))
}
}?;
Ok(Self {
mandates: Mandate {
scheme,
metadata: MandateMetaData {
payment_reference: item.connector_request_reference_id.clone(),
},
payer_ip_address,
links: MandateLink {
customer_bank_account,
},
},
})
}
}
fn get_ip_if_required(
bank_debit_data: &BankDebitData,
item: &types::SetupMandateRouterData,
) -> Result<Option<Secret<String, IpAddress>>, error_stack::Report<errors::ConnectorError>> {
let ip_address = item.request.get_browser_info()?.get_ip_address()?;
match bank_debit_data {
BankDebitData::AchBankDebit { .. } => Ok(Some(ip_address)),
BankDebitData::SepaBankDebit { .. }
| BankDebitData::SepaGuarenteedBankDebit { .. }
| BankDebitData::BecsBankDebit { .. }
| BankDebitData::BacsBankDebit { .. } => Ok(None),
}
}
impl TryFrom<&BankDebitData> for GocardlessScheme {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &BankDebitData) -> Result<Self, Self::Error> {
match item {
BankDebitData::AchBankDebit { .. } => Ok(Self::Ach),
BankDebitData::SepaBankDebit { .. } => Ok(Self::SepaCore),
BankDebitData::BecsBankDebit { .. } => Ok(Self::Becs),
BankDebitData::BacsBankDebit { .. } | BankDebitData::SepaGuarenteedBankDebit { .. } => {
Err(errors::ConnectorError::NotImplemented(
"Setup Mandate flow for selected payment method through Gocardless".to_string(),
)
.into())
}
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GocardlessMandateResponse {
mandates: MandateResponse,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MandateResponse {
id: Secret<String>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
GocardlessMandateResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
> for RouterData<F, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
GocardlessMandateResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let mandate_reference = Some(MandateReference {
connector_mandate_id: Some(item.response.mandates.id.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
connector_metadata: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
network_txn_id: None,
charges: None,
}),
status: enums::AttemptStatus::Charged,
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct GocardlessPaymentsRequest {
payments: GocardlessPayment,
}
#[derive(Debug, Serialize)]
pub struct GocardlessPayment {
amount: MinorUnit,
currency: enums::Currency,
description: Option<String>,
metadata: PaymentMetaData,
links: PaymentLink,
}
#[derive(Debug, Serialize)]
pub struct PaymentMetaData {
payment_reference: String,
}
#[derive(Debug, Serialize)]
pub struct PaymentLink {
mandate: Secret<String>,
}
impl TryFrom<&GocardlessRouterData<&types::PaymentsAuthorizeRouterData>>
for GocardlessPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &GocardlessRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let mandate_id = if item.router_data.request.is_mandate_payment() {
item.router_data
.request
.connector_mandate_id()
.ok_or_else(utils::missing_field_err("mandate_id"))
} else {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("gocardless"),
)
.into())
}?;
let payments = GocardlessPayment {
amount: item.router_data.request.minor_amount,
currency: item.router_data.request.currency,
description: item.router_data.description.clone(),
metadata: PaymentMetaData {
payment_reference: item.router_data.connector_request_reference_id.clone(),
},
links: PaymentLink {
mandate: Secret::new(mandate_id),
},
};
Ok(Self { payments })
}
}
// Auth Struct
pub struct GocardlessAuthType {
pub(super) access_token: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for GocardlessAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
access_token: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GocardlessPaymentStatus {
PendingCustomerApproval,
PendingSubmission,
Submitted,
Confirmed,
PaidOut,
Cancelled,
CustomerApprovalDenied,
Failed,
}
impl From<GocardlessPaymentStatus> for enums::AttemptStatus {
fn from(item: GocardlessPaymentStatus) -> Self {
match item {
GocardlessPaymentStatus::PendingCustomerApproval
| GocardlessPaymentStatus::PendingSubmission
| GocardlessPaymentStatus::Submitted => Self::Pending,
GocardlessPaymentStatus::Confirmed | GocardlessPaymentStatus::PaidOut => Self::Charged,
GocardlessPaymentStatus::Cancelled => Self::Voided,
GocardlessPaymentStatus::CustomerApprovalDenied => Self::AuthenticationFailed,
GocardlessPaymentStatus::Failed => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GocardlessPaymentsResponse {
payments: PaymentResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentResponse {
status: GocardlessPaymentStatus,
id: String,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
GocardlessPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
GocardlessPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let mandate_reference = MandateReference {
connector_mandate_id: Some(item.data.request.get_connector_mandate_id()?),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
};
Ok(Self {
status: enums::AttemptStatus::from(item.response.payments.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.payments.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(Some(mandate_reference)),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<F>
TryFrom<
ResponseRouterData<F, GocardlessPaymentsResponse, PaymentsSyncData, PaymentsResponseData>,
> for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
GocardlessPaymentsResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.payments.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.payments.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
#[derive(Default, Debug, Serialize)]
pub struct GocardlessRefundRequest {
refunds: GocardlessRefund,
}
#[derive(Default, Debug, Serialize)]
pub struct GocardlessRefund {
amount: MinorUnit,
metadata: RefundMetaData,
links: RefundLink,
}
#[derive(Default, Debug, Serialize)]
pub struct RefundMetaData {
refund_reference: String,
}
#[derive(Default, Debug, Serialize)]
pub struct RefundLink {
payment: String,
}
impl<F> TryFrom<&GocardlessRouterData<&types::RefundsRouterData<F>>> for GocardlessRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &GocardlessRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
refunds: GocardlessRefund {
amount: item.amount.to_owned(),
metadata: RefundMetaData {
refund_reference: item.router_data.connector_request_reference_id.clone(),
},
links: RefundLink {
payment: item.router_data.request.connector_transaction_id.clone(),
},
},
})
}
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
id: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::Pending,
}),
..item.data
})
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GocardlessErrorResponse {
pub error: GocardlessError,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GocardlessError {
pub message: String,
pub code: u16,
pub errors: Vec<Error>,
#[serde(rename = "type")]
pub error_type: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Error {
pub field: Option<String>,
pub message: String,
}
#[derive(Debug, Deserialize)]
pub struct GocardlessWebhookEvent {
pub events: Vec<WebhookEvent>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WebhookEvent {
pub resource_type: WebhookResourceType,
pub action: WebhookAction,
pub links: WebhooksLink,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WebhookResourceType {
Payments,
Refunds,
Mandates,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum WebhookAction {
PaymentsAction(PaymentsAction),
RefundsAction(RefundsAction),
MandatesAction(MandatesAction),
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PaymentsAction {
Created,
CustomerApprovalGranted,
CustomerApprovalDenied,
Submitted,
Confirmed,
PaidOut,
LateFailureSettled,
SurchargeFeeDebited,
Failed,
Cancelled,
ResubmissionRequired,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RefundsAction {
Created,
Failed,
Paid,
// Payout statuses
RefundSettled,
FundsReturned,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MandatesAction {
Created,
CustomerApprovalGranted,
CustomerApprovalSkipped,
Active,
Cancelled,
Failed,
Transferred,
Expired,
Submitted,
ResubmissionRequested,
Reinstated,
Replaced,
Consumed,
Blocked,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum WebhooksLink {
PaymentWebhooksLink(PaymentWebhooksLink),
RefundWebhookLink(RefundWebhookLink),
MandateWebhookLink(MandateWebhookLink),
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RefundWebhookLink {
pub refund: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PaymentWebhooksLink {
pub payment: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct MandateWebhookLink {
pub mandate: String,
}
impl TryFrom<&WebhookEvent> for GocardlessPaymentsResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &WebhookEvent) -> Result<Self, Self::Error> {
let id = match &item.links {
WebhooksLink::PaymentWebhooksLink(link) => link.payment.to_owned(),
WebhooksLink::RefundWebhookLink(_) | WebhooksLink::MandateWebhookLink(_) => {
Err(errors::ConnectorError::WebhookEventTypeNotFound)?
}
};
Ok(Self {
payments: PaymentResponse {
status: GocardlessPaymentStatus::try_from(&item.action)?,
id,
},
})
}
}
impl TryFrom<&WebhookAction> for GocardlessPaymentStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &WebhookAction) -> Result<Self, Self::Error> {
match item {
WebhookAction::PaymentsAction(action) => match action {
PaymentsAction::CustomerApprovalGranted | PaymentsAction::Submitted => {
Ok(Self::Submitted)
}
PaymentsAction::CustomerApprovalDenied => Ok(Self::CustomerApprovalDenied),
PaymentsAction::LateFailureSettled => Ok(Self::Failed),
PaymentsAction::Failed => Ok(Self::Failed),
PaymentsAction::Cancelled => Ok(Self::Cancelled),
PaymentsAction::Confirmed => Ok(Self::Confirmed),
PaymentsAction::PaidOut => Ok(Self::PaidOut),
PaymentsAction::SurchargeFeeDebited
| PaymentsAction::ResubmissionRequired
| PaymentsAction::Created => Err(errors::ConnectorError::WebhookEventTypeNotFound)?,
},
WebhookAction::RefundsAction(_) | WebhookAction::MandatesAction(_) => {
Err(errors::ConnectorError::WebhookEventTypeNotFound)?
}
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6595
}
|
large_file_-5110111464660028207
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs
</path>
<file>
use common_enums::enums;
use common_utils::{ext_traits::OptionExt as _, types::SemanticVersion};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, ErrorResponse},
router_flow_types::authentication::{Authentication, PreAuthentication},
router_request_types::authentication::{
AuthNFlowType, ChallengeParams, ConnectorAuthenticationRequestData,
MessageExtensionAttribute, PreAuthNRequestData,
},
router_response_types::AuthenticationResponseData,
};
use hyperswitch_interfaces::{api::CurrencyUnit, errors::ConnectorError};
use masking::Secret;
use serde::{Deserialize, Serialize};
use super::netcetera_types;
use crate::{
types::{ConnectorAuthenticationRouterData, PreAuthNRouterData, ResponseRouterData},
utils::{get_card_details, to_connector_meta_from_secret, CardData as _},
};
//TODO: Fill the struct with respective fields
pub struct NetceteraRouterData<T> {
pub amount: i64, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> TryFrom<(&CurrencyUnit, enums::Currency, i64, T)> for NetceteraRouterData<T> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
(_currency_unit, _currency, amount, item): (&CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Ok(Self {
amount,
router_data: item,
})
}
}
impl<T> TryFrom<(i64, T)> for NetceteraRouterData<T> {
type Error = error_stack::Report<ConnectorError>;
fn try_from((amount, router_data): (i64, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data,
})
}
}
impl
TryFrom<
ResponseRouterData<
PreAuthentication,
NetceteraPreAuthenticationResponse,
PreAuthNRequestData,
AuthenticationResponseData,
>,
> for PreAuthNRouterData
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
PreAuthentication,
NetceteraPreAuthenticationResponse,
PreAuthNRequestData,
AuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
let response = match item.response {
NetceteraPreAuthenticationResponse::Success(pre_authn_response) => {
// if card is not enrolled for 3ds, card_range will be None
let card_range = pre_authn_response.get_card_range_if_available();
let maximum_supported_3ds_version = card_range
.as_ref()
.map(|card_range| card_range.highest_common_supported_version.clone())
.unwrap_or_else(|| {
// Version "0.0.0" will be less that "2.0.0", hence we will treat this card as not eligible for 3ds authentication
SemanticVersion::new(0, 0, 0)
});
let three_ds_method_data = card_range.as_ref().and_then(|card_range| {
card_range
.three_ds_method_data_form
.as_ref()
.map(|data| data.three_ds_method_data.clone())
});
let three_ds_method_url = card_range
.as_ref()
.and_then(|card_range| card_range.get_three_ds_method_url());
Ok(AuthenticationResponseData::PreAuthNResponse {
threeds_server_transaction_id: pre_authn_response
.three_ds_server_trans_id
.clone(),
maximum_supported_3ds_version: maximum_supported_3ds_version.clone(),
connector_authentication_id: pre_authn_response.three_ds_server_trans_id,
three_ds_method_data,
three_ds_method_url,
message_version: maximum_supported_3ds_version,
connector_metadata: None,
directory_server_id: card_range
.as_ref()
.and_then(|card_range| card_range.directory_server_id.clone()),
})
}
NetceteraPreAuthenticationResponse::Failure(error_response) => Err(ErrorResponse {
code: error_response.error_details.error_code,
message: error_response.error_details.error_description,
reason: error_response.error_details.error_detail,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
};
Ok(Self {
response,
..item.data.clone()
})
}
}
impl
TryFrom<
ResponseRouterData<
Authentication,
NetceteraAuthenticationResponse,
ConnectorAuthenticationRequestData,
AuthenticationResponseData,
>,
> for ConnectorAuthenticationRouterData
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
Authentication,
NetceteraAuthenticationResponse,
ConnectorAuthenticationRequestData,
AuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
let response = match item.response {
NetceteraAuthenticationResponse::Success(response) => {
let authn_flow_type = match response.acs_challenge_mandated {
Some(ACSChallengeMandatedIndicator::Y) => {
AuthNFlowType::Challenge(Box::new(ChallengeParams {
acs_url: response.authentication_response.acs_url.clone(),
challenge_request: response.encoded_challenge_request,
acs_reference_number: response
.authentication_response
.acs_reference_number,
acs_trans_id: response.authentication_response.acs_trans_id,
three_dsserver_trans_id: Some(response.three_ds_server_trans_id),
acs_signed_content: response.authentication_response.acs_signed_content,
challenge_request_key: None,
}))
}
Some(ACSChallengeMandatedIndicator::N) | None => AuthNFlowType::Frictionless,
};
let challenge_code = response
.authentication_request
.as_ref()
.and_then(|req| req.three_ds_requestor_challenge_ind.as_ref())
.and_then(|ind| match ind {
ThreedsRequestorChallengeInd::Single(s) => Some(s.clone()),
ThreedsRequestorChallengeInd::Multiple(v) => v.first().cloned(),
});
let message_extension = response
.authentication_response
.message_extension
.as_ref()
.and_then(|v| match serde_json::to_value(v) {
Ok(val) => Some(Secret::new(val)),
Err(e) => {
router_env::logger::error!(
"Failed to serialize message_extension: {:?}",
e
);
None
}
});
Ok(AuthenticationResponseData::AuthNResponse {
authn_flow_type,
authentication_value: response.authentication_value,
trans_status: response.trans_status,
connector_metadata: None,
ds_trans_id: response.authentication_response.ds_trans_id,
eci: response.eci,
challenge_code,
challenge_cancel: None, // Note - challenge_cancel field is received in the RReq and updated in DB during external_authentication_incoming_webhook_flow
challenge_code_reason: response.authentication_response.trans_status_reason,
message_extension,
})
}
NetceteraAuthenticationResponse::Error(error_response) => Err(ErrorResponse {
code: error_response.error_details.error_code,
message: error_response.error_details.error_description,
reason: error_response.error_details.error_detail,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
};
Ok(Self {
response,
..item.data.clone()
})
}
}
pub struct NetceteraAuthType {
pub(super) certificate: Secret<String>,
pub(super) private_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for NetceteraAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type.to_owned() {
ConnectorAuthType::CertificateAuth {
certificate,
private_key,
} => Ok(Self {
certificate,
private_key,
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NetceteraErrorResponse {
pub three_ds_server_trans_id: Option<String>,
pub error_details: NetceteraErrorDetails,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NetceteraErrorDetails {
/// Universally unique identifier for the transaction assigned by the 3DS Server.
#[serde(rename = "threeDSServerTransID")]
pub three_ds_server_trans_id: Option<String>,
/// Universally Unique identifier for the transaction assigned by the ACS.
#[serde(rename = "acsTransID")]
pub acs_trans_id: Option<String>,
/// Universally unique identifier for the transaction assigned by the DS.
#[serde(rename = "dsTransID")]
pub ds_trans_id: Option<String>,
/// Code indicating the type of problem identified.
pub error_code: String,
/// Code indicating the 3-D Secure component that identified the error.
pub error_component: Option<String>,
/// Text describing the problem identified.
pub error_description: String,
/// Additional detail regarding the problem identified.
pub error_detail: Option<String>,
/// Universally unique identifier for the transaction assigned by the 3DS SDK.
#[serde(rename = "sdkTransID")]
pub sdk_trans_id: Option<String>,
/// The Message Type that was identified as erroneous.
pub error_message_type: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NetceteraMetaData {
pub mcc: Option<String>,
pub merchant_country_code: Option<String>,
pub merchant_name: Option<String>,
pub endpoint_prefix: String,
pub three_ds_requestor_name: Option<String>,
pub three_ds_requestor_id: Option<String>,
pub merchant_configuration_id: Option<String>,
}
impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for NetceteraMetaData {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
meta_data: &Option<common_utils::pii::SecretSerdeValue>,
) -> Result<Self, Self::Error> {
let metadata: Self = to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(ConnectorError::InvalidConnectorConfig { config: "metadata" })?;
Ok(metadata)
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NetceteraPreAuthenticationRequest {
cardholder_account_number: cards::CardNumber,
scheme_id: Option<netcetera_types::SchemeId>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum NetceteraPreAuthenticationResponse {
Success(Box<NetceteraPreAuthenticationResponseData>),
Failure(Box<NetceteraErrorResponse>),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetceteraPreAuthenticationResponseData {
#[serde(rename = "threeDSServerTransID")]
pub three_ds_server_trans_id: String,
pub card_ranges: Vec<CardRange>,
}
impl NetceteraPreAuthenticationResponseData {
pub fn get_card_range_if_available(&self) -> Option<CardRange> {
let card_range = self
.card_ranges
.iter()
.max_by_key(|card_range| &card_range.highest_common_supported_version);
card_range.cloned()
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CardRange {
pub scheme_id: netcetera_types::SchemeId,
pub directory_server_id: Option<String>,
pub acs_protocol_versions: Vec<AcsProtocolVersion>,
#[serde(rename = "threeDSMethodDataForm")]
pub three_ds_method_data_form: Option<ThreeDSMethodDataForm>,
pub highest_common_supported_version: SemanticVersion,
}
impl CardRange {
pub fn get_three_ds_method_url(&self) -> Option<String> {
self.acs_protocol_versions
.iter()
.find(|acs_protocol_version| {
acs_protocol_version.version == self.highest_common_supported_version
})
.and_then(|acs_version| acs_version.three_ds_method_url.clone())
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSMethodDataForm {
// base64 encoded value for 3ds method data collection
#[serde(rename = "threeDSMethodData")]
pub three_ds_method_data: String,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct AcsProtocolVersion {
pub version: SemanticVersion,
#[serde(rename = "threeDSMethodURL")]
pub three_ds_method_url: Option<String>,
}
impl TryFrom<&NetceteraRouterData<&PreAuthNRouterData>> for NetceteraPreAuthenticationRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(value: &NetceteraRouterData<&PreAuthNRouterData>) -> Result<Self, Self::Error> {
let router_data = value.router_data;
let is_cobadged_card = || {
router_data
.request
.card
.card_number
.is_cobadged_card()
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("error while checking is_cobadged_card")
};
Ok(Self {
cardholder_account_number: router_data.request.card.card_number.clone(),
scheme_id: router_data
.request
.card
.card_network
.clone()
.map(|card_network| {
is_cobadged_card().map(|is_cobadged_card| {
is_cobadged_card
.then_some(netcetera_types::SchemeId::try_from(card_network))
})
})
.transpose()?
.flatten()
.transpose()?,
})
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
#[serde_with::skip_serializing_none]
pub struct NetceteraAuthenticationRequest {
/// Specifies the preferred version of 3D Secure protocol to be utilized while executing 3D Secure authentication.
/// 3DS Server initiates an authentication request with the preferred version and if this version is not supported by
/// other 3D Secure components, it falls back to the next supported version(s) and continues authentication.
///
/// If the preferred version is enforced by setting #enforcePreferredProtocolVersion flag, but this version
/// is not supported by one of the 3D Secure components, 3DS Server does not initiate an authentication and provides
/// corresponding error message to the customer.
///
/// The accepted values are:
/// - 2.1.0 -> prefer authentication with 2.1.0 version,
/// - 2.2.0 -> prefer authentication with 2.2.0 version,
/// - 2.3.1 -> prefer authentication with 2.3.1 version,
/// - latest -> prefer authentication with the latest version, the 3DS Server is certified for. 2.3.1 at this moment.
pub preferred_protocol_version: Option<SemanticVersion>,
/// Boolean flag that enforces preferred 3D Secure protocol version to be used in 3D Secure authentication.
/// The value should be set true to enforce preferred version. If value is false or not provided,
/// 3DS Server can fall back to next supported 3DS protocol version while initiating 3D Secure authentication.
///
/// For application initiated transactions (deviceChannel = '01'), the preferred protocol version must be enforced.
pub enforce_preferred_protocol_version: Option<bool>,
pub device_channel: netcetera_types::NetceteraDeviceChannel,
/// Identifies the category of the message for a specific use case. The accepted values are:
///
/// - 01 -> PA
/// - 02 -> NPA
/// - 80 - 99 -> PS Specific Values (80 -> MasterCard Identity Check Insights;
/// 85 -> MasterCard Identity Check, Production Validation PA;
/// 86 -> MasterCard Identity Check, Production Validation NPA)
pub message_category: netcetera_types::NetceteraMessageCategory,
#[serde(rename = "threeDSCompInd")]
pub three_ds_comp_ind: Option<netcetera_types::ThreeDSMethodCompletionIndicator>,
/**
* Contains the 3DS Server Transaction ID used during the previous execution of the 3DS method. Accepted value
* length is 36 characters. Accepted value is a Canonical format as defined in IETF RFC 4122. May utilise any of the
* specified versions if the output meets specified requirements.
*
* This field is required if the 3DS Requestor reuses previous 3DS Method execution with deviceChannel = 02 (BRW).
* Available for supporting EMV 3DS 2.3.1 and later versions.
*/
#[serde(rename = "threeDSMethodId")]
pub three_ds_method_id: Option<String>,
#[serde(rename = "threeDSRequestor")]
pub three_ds_requestor: Option<netcetera_types::ThreeDSRequestor>,
#[serde(rename = "threeDSServerTransID")]
pub three_ds_server_trans_id: String,
#[serde(rename = "threeDSRequestorURL")]
pub three_ds_requestor_url: Option<String>,
pub cardholder_account: netcetera_types::CardholderAccount,
pub cardholder: Option<netcetera_types::Cardholder>,
pub purchase: Option<netcetera_types::Purchase>,
pub acquirer: Option<netcetera_types::AcquirerData>,
pub merchant: Option<netcetera_types::MerchantData>,
pub broad_info: Option<String>,
pub device_render_options: Option<netcetera_types::DeviceRenderingOptionsSupported>,
pub message_extension: Option<Vec<MessageExtensionAttribute>>,
pub challenge_message_extension: Option<Vec<MessageExtensionAttribute>>,
pub browser_information: Option<netcetera_types::Browser>,
#[serde(rename = "threeRIInd")]
pub three_ri_ind: Option<String>,
pub sdk_information: Option<netcetera_types::Sdk>,
pub device: Option<String>,
pub multi_transaction: Option<String>,
pub device_id: Option<String>,
pub user_id: Option<String>,
pub payee_origin: Option<url::Url>,
}
impl TryFrom<&NetceteraRouterData<&ConnectorAuthenticationRouterData>>
for NetceteraAuthenticationRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &NetceteraRouterData<&ConnectorAuthenticationRouterData>,
) -> Result<Self, Self::Error> {
let now = common_utils::date_time::now();
let request = item.router_data.request.clone();
let pre_authn_data = request.pre_authentication_data.clone();
let ip_address = request
.browser_details
.as_ref()
.and_then(|browser| browser.ip_address);
let three_ds_requestor = netcetera_types::ThreeDSRequestor::new(
ip_address,
item.router_data.psd2_sca_exemption_type,
item.router_data.request.force_3ds_challenge,
item.router_data
.request
.pre_authentication_data
.message_version
.clone(),
);
let card = get_card_details(request.payment_method_data, "netcetera")?;
let is_cobadged_card = card
.card_number
.clone()
.is_cobadged_card()
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("error while checking is_cobadged_card")?;
let cardholder_account = netcetera_types::CardholderAccount {
acct_type: None,
card_expiry_date: Some(card.get_expiry_date_as_yymm()?),
acct_info: None,
acct_number: card.card_number,
scheme_id: card
.card_network
.clone()
.and_then(|card_network| {
is_cobadged_card.then_some(netcetera_types::SchemeId::try_from(card_network))
})
.transpose()?,
acct_id: None,
pay_token_ind: None,
pay_token_info: None,
card_security_code: Some(card.card_cvc),
};
let currency = request
.currency
.get_required_value("currency")
.change_context(ConnectorError::MissingRequiredField {
field_name: "currency",
})?;
let purchase = netcetera_types::Purchase {
purchase_instal_data: None,
merchant_risk_indicator: None,
purchase_amount: request.amount,
purchase_currency: currency.iso_4217().to_string(),
purchase_exponent: currency.number_of_digits_after_decimal_point(),
purchase_date: Some(
common_utils::date_time::format_date(
now,
common_utils::date_time::DateFormat::YYYYMMDDHHmmss,
)
.change_context(
ConnectorError::RequestEncodingFailedWithReason(
"Failed to format Date".to_string(),
),
)?,
),
recurring_expiry: None,
recurring_frequency: None,
// 01 -> Goods and Services, hardcoding this as we serve this usecase only for now
trans_type: Some("01".to_string()),
recurring_amount: None,
recurring_currency: None,
recurring_exponent: None,
recurring_date: None,
amount_ind: None,
frequency_ind: None,
};
let acquirer_details = netcetera_types::AcquirerData {
acquirer_bin: request.pre_authentication_data.acquirer_bin,
acquirer_merchant_id: request.pre_authentication_data.acquirer_merchant_id,
acquirer_country_code: request.pre_authentication_data.acquirer_country_code,
};
let connector_meta_data: NetceteraMetaData = item
.router_data
.connector_meta_data
.clone()
.parse_value("NetceteraMetaData")
.change_context(ConnectorError::RequestEncodingFailed)?;
let merchant_data = netcetera_types::MerchantData {
merchant_configuration_id: connector_meta_data.merchant_configuration_id,
mcc: connector_meta_data.mcc,
merchant_country_code: connector_meta_data.merchant_country_code,
merchant_name: connector_meta_data.merchant_name,
notification_url: request.return_url.clone(),
three_ds_requestor_id: connector_meta_data.three_ds_requestor_id,
three_ds_requestor_name: connector_meta_data.three_ds_requestor_name,
white_list_status: None,
trust_list_status: None,
seller_info: None,
results_response_notification_url: Some(request.webhook_url),
};
let browser_information = match request.device_channel {
api_models::payments::DeviceChannel::Browser => {
request.browser_details.map(netcetera_types::Browser::from)
}
api_models::payments::DeviceChannel::App => None,
};
let sdk_information = match request.device_channel {
api_models::payments::DeviceChannel::App => {
request.sdk_information.map(netcetera_types::Sdk::from)
}
api_models::payments::DeviceChannel::Browser => None,
};
let device_render_options = match request.device_channel {
api_models::payments::DeviceChannel::App => {
Some(netcetera_types::DeviceRenderingOptionsSupported {
// hard-coded until core provides these values.
sdk_interface: netcetera_types::SdkInterface::Both,
sdk_ui_type: vec![
netcetera_types::SdkUiType::Text,
netcetera_types::SdkUiType::SingleSelect,
netcetera_types::SdkUiType::MultiSelect,
netcetera_types::SdkUiType::Oob,
netcetera_types::SdkUiType::HtmlOther,
],
})
}
api_models::payments::DeviceChannel::Browser => None,
};
Ok(Self {
preferred_protocol_version: Some(pre_authn_data.message_version),
// For Device channel App, we should enforce the preferred protocol version
enforce_preferred_protocol_version: Some(matches!(
request.device_channel,
api_models::payments::DeviceChannel::App
)),
device_channel: netcetera_types::NetceteraDeviceChannel::from(request.device_channel),
message_category: netcetera_types::NetceteraMessageCategory::from(
request.message_category,
),
three_ds_comp_ind: Some(netcetera_types::ThreeDSMethodCompletionIndicator::from(
request.threeds_method_comp_ind,
)),
three_ds_method_id: None,
three_ds_requestor: Some(three_ds_requestor),
three_ds_server_trans_id: pre_authn_data.threeds_server_transaction_id,
three_ds_requestor_url: Some(request.three_ds_requestor_url),
cardholder_account,
cardholder: Some(netcetera_types::Cardholder::try_from((
request.billing_address,
request.shipping_address,
))?),
purchase: Some(purchase),
acquirer: Some(acquirer_details),
merchant: Some(merchant_data),
broad_info: None,
device_render_options,
message_extension: None,
challenge_message_extension: None,
browser_information,
three_ri_ind: None,
sdk_information,
device: None,
multi_transaction: None,
device_id: None,
user_id: None,
payee_origin: None,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum NetceteraAuthenticationResponse {
Error(NetceteraAuthenticationFailureResponse),
Success(NetceteraAuthenticationSuccessResponse),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetceteraAuthenticationSuccessResponse {
#[serde(rename = "threeDSServerTransID")]
pub three_ds_server_trans_id: String,
pub trans_status: common_enums::TransactionStatus,
pub authentication_value: Option<Secret<String>>,
pub eci: Option<String>,
pub acs_challenge_mandated: Option<ACSChallengeMandatedIndicator>,
pub authentication_request: Option<AuthenticationRequest>,
pub authentication_response: AuthenticationResponse,
#[serde(rename = "base64EncodedChallengeRequest")]
pub encoded_challenge_request: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetceteraAuthenticationFailureResponse {
pub error_details: NetceteraErrorDetails,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthenticationRequest {
#[serde(rename = "threeDSRequestorChallengeInd")]
pub three_ds_requestor_challenge_ind: Option<ThreedsRequestorChallengeInd>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ThreedsRequestorChallengeInd {
Single(String),
Multiple(Vec<String>),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthenticationResponse {
#[serde(rename = "acsURL")]
pub acs_url: Option<url::Url>,
pub acs_reference_number: Option<String>,
#[serde(rename = "acsTransID")]
pub acs_trans_id: Option<String>,
#[serde(rename = "dsTransID")]
pub ds_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
pub trans_status_reason: Option<String>,
pub message_extension: Option<serde_json::Value>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub enum ACSChallengeMandatedIndicator {
/// Challenge is mandated
Y,
/// Challenge is not mandated
N,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResultsResponseData {
/// Universally unique transaction identifier assigned by the 3DS Server to identify a single transaction.
/// It has the same value as the authentication request and conforms to the format defined in IETF RFC 4122.
#[serde(rename = "threeDSServerTransID")]
pub three_ds_server_trans_id: String,
/// Indicates the status of a transaction in terms of its authentication.
///
/// Valid values:
/// - `Y`: Authentication / Account verification successful.
/// - `N`: Not authenticated / Account not verified; Transaction denied.
/// - `U`: Authentication / Account verification could not be performed; technical or other problem.
/// - `C`: A challenge is required to complete the authentication.
/// - `R`: Authentication / Account verification Rejected. Issuer is rejecting authentication/verification
/// and request that authorization not be attempted.
/// - `A`: Attempts processing performed; Not authenticated / verified, but a proof of attempt
/// authentication / verification is provided.
/// - `D`: A challenge is required to complete the authentication. Decoupled Authentication confirmed.
/// - `I`: Informational Only; 3DS Requestor challenge preference acknowledged.
pub trans_status: Option<common_enums::TransactionStatus>,
/// Payment System-specific value provided as part of the ACS registration for each supported DS.
/// Authentication Value may be used to provide proof of authentication.
pub authentication_value: Option<Secret<String>>,
/// Payment System-specific value provided by the ACS to indicate the results of the attempt to authenticate
/// the Cardholder.
pub eci: Option<String>,
/// The received Results Request from the Directory Server.
pub results_request: Option<serde_json::Value>,
/// The sent Results Response to the Directory Server.
pub results_response: Option<serde_json::Value>,
/// Optional object containing error details if any errors occurred during the process.
pub error_details: Option<NetceteraErrorDetails>,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6624
}
|
large_file_-7880988656009360565
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs
</path>
<file>
#[cfg(feature = "payouts")]
use api_models::enums::Currency;
#[cfg(feature = "payouts")]
use api_models::payouts::{Bank, PayoutMethodData};
#[cfg(feature = "payouts")]
use common_enums::{PayoutStatus, PayoutType};
#[cfg(feature = "payouts")]
use common_utils::pii::Email;
use common_utils::types::FloatMajorUnit;
use hyperswitch_domain_models::router_data::ConnectorAuthType;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::router_flow_types::PoCreate;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::types::{PayoutsResponseData, PayoutsRouterData};
use hyperswitch_interfaces::errors::ConnectorError;
#[cfg(feature = "payouts")]
use masking::ExposeInterface;
use masking::Secret;
use serde::{Deserialize, Serialize};
#[cfg(feature = "payouts")]
use crate::types::PayoutsResponseRouterData;
#[cfg(feature = "payouts")]
use crate::utils::{
AddressDetailsData as _, CustomerDetails as _, PayoutsData as _, RouterData as _,
};
pub struct EbanxRouterData<T> {
pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for EbanxRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub struct EbanxPayoutCreateRequest {
integration_key: Secret<String>,
external_reference: String,
country: String,
amount: FloatMajorUnit,
currency: Currency,
target: EbanxPayoutType,
target_account: Secret<String>,
payee: EbanxPayoutDetails,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub enum EbanxPayoutType {
BankAccount,
Mercadopago,
EwalletNequi,
PixKey,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub struct EbanxPayoutDetails {
name: Secret<String>,
email: Option<Email>,
document: Option<Secret<String>>,
document_type: Option<EbanxDocumentType>,
bank_info: EbanxBankDetails,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub enum EbanxDocumentType {
#[serde(rename = "CPF")]
NaturalPersonsRegister,
#[serde(rename = "CNPJ")]
NationalRegistryOfLegalEntities,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub struct EbanxBankDetails {
bank_name: Option<String>,
bank_branch: Option<String>,
bank_account: Option<Secret<String>>,
account_type: Option<EbanxBankAccountType>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub enum EbanxBankAccountType {
#[serde(rename = "C")]
CheckingAccount,
}
#[cfg(feature = "payouts")]
impl TryFrom<&EbanxRouterData<&PayoutsRouterData<PoCreate>>> for EbanxPayoutCreateRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &EbanxRouterData<&PayoutsRouterData<PoCreate>>) -> Result<Self, Self::Error> {
let ebanx_auth_type = EbanxAuthType::try_from(&item.router_data.connector_auth_type)?;
match item.router_data.get_payout_method_data()? {
PayoutMethodData::Bank(Bank::Pix(pix_data)) => {
let bank_info = EbanxBankDetails {
bank_account: Some(pix_data.bank_account_number),
bank_branch: pix_data.bank_branch,
bank_name: pix_data.bank_name,
account_type: Some(EbanxBankAccountType::CheckingAccount),
};
let billing_address = item.router_data.get_billing_address()?;
let customer_details = item.router_data.request.get_customer_details()?;
let document_type = pix_data.tax_id.clone().map(|tax_id| {
if tax_id.clone().expose().len() == 11 {
EbanxDocumentType::NaturalPersonsRegister
} else {
EbanxDocumentType::NationalRegistryOfLegalEntities
}
});
let payee = EbanxPayoutDetails {
name: billing_address.get_full_name()?,
email: customer_details.email.clone(),
bank_info,
document_type,
document: pix_data.tax_id.to_owned(),
};
Ok(Self {
amount: item.amount,
integration_key: ebanx_auth_type.integration_key,
country: customer_details.get_customer_phone_country_code()?,
currency: item.router_data.request.source_currency,
external_reference: item.router_data.connector_request_reference_id.to_owned(),
target: EbanxPayoutType::PixKey,
target_account: pix_data.pix_key,
payee,
})
}
PayoutMethodData::Card(_)
| PayoutMethodData::Bank(_)
| PayoutMethodData::Wallet(_)
| PayoutMethodData::BankRedirect(_) => Err(ConnectorError::NotSupported {
message: "Payment Method Not Supported".to_string(),
connector: "Ebanx",
})?,
}
}
}
pub struct EbanxAuthType {
pub integration_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for EbanxAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
integration_key: api_key.to_owned(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EbanxPayoutStatus {
#[serde(rename = "PA")]
Succeeded,
#[serde(rename = "CA")]
Cancelled,
#[serde(rename = "PE")]
Processing,
#[serde(rename = "OP")]
RequiresFulfillment,
}
#[cfg(feature = "payouts")]
impl From<EbanxPayoutStatus> for PayoutStatus {
fn from(item: EbanxPayoutStatus) -> Self {
match item {
EbanxPayoutStatus::Succeeded => Self::Success,
EbanxPayoutStatus::Cancelled => Self::Cancelled,
EbanxPayoutStatus::Processing => Self::Pending,
EbanxPayoutStatus::RequiresFulfillment => Self::RequiresFulfillment,
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxPayoutResponse {
payout: EbanxPayoutResponseDetails,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxPayoutResponseDetails {
uid: String,
status: EbanxPayoutStatus,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, EbanxPayoutResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, EbanxPayoutResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::from(item.response.payout.status)),
connector_payout_id: Some(item.response.payout.uid),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxPayoutFulfillRequest {
integration_key: Secret<String>,
uid: String,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<&EbanxRouterData<&PayoutsRouterData<F>>> for EbanxPayoutFulfillRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &EbanxRouterData<&PayoutsRouterData<F>>) -> Result<Self, Self::Error> {
let request = item.router_data.request.to_owned();
let ebanx_auth_type = EbanxAuthType::try_from(&item.router_data.connector_auth_type)?;
let payout_type = request.get_payout_type()?;
match payout_type {
PayoutType::Bank => Ok(Self {
integration_key: ebanx_auth_type.integration_key,
uid: request
.connector_payout_id
.to_owned()
.ok_or(ConnectorError::MissingRequiredField { field_name: "uid" })?,
}),
PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => {
Err(ConnectorError::NotSupported {
message: "Payout Method Not Supported".to_string(),
connector: "Ebanx",
})?
}
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxFulfillResponse {
#[serde(rename = "type")]
status: EbanxFulfillStatus,
message: String,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EbanxFulfillStatus {
Success,
ApiError,
AuthenticationError,
InvalidRequestError,
RequestError,
}
#[cfg(feature = "payouts")]
impl From<EbanxFulfillStatus> for PayoutStatus {
fn from(item: EbanxFulfillStatus) -> Self {
match item {
EbanxFulfillStatus::Success => Self::Success,
EbanxFulfillStatus::ApiError
| EbanxFulfillStatus::AuthenticationError
| EbanxFulfillStatus::InvalidRequestError
| EbanxFulfillStatus::RequestError => Self::Failed,
}
}
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, EbanxFulfillResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, EbanxFulfillResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::from(item.response.status)),
connector_payout_id: Some(item.data.request.get_transfer_id()?),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct EbanxErrorResponse {
pub code: String,
pub status_code: String,
pub message: Option<String>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxPayoutCancelRequest {
integration_key: Secret<String>,
uid: String,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<&PayoutsRouterData<F>> for EbanxPayoutCancelRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
let ebanx_auth_type = EbanxAuthType::try_from(&item.connector_auth_type)?;
let payout_type = request.get_payout_type()?;
match payout_type {
PayoutType::Bank => Ok(Self {
integration_key: ebanx_auth_type.integration_key,
uid: request
.connector_payout_id
.to_owned()
.ok_or(ConnectorError::MissingRequiredField { field_name: "uid" })?,
}),
PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => {
Err(ConnectorError::NotSupported {
message: "Payout Method Not Supported".to_string(),
connector: "Ebanx",
})?
}
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxCancelResponse {
#[serde(rename = "type")]
status: EbanxCancelStatus,
message: String,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EbanxCancelStatus {
Success,
ApiError,
AuthenticationError,
InvalidRequestError,
RequestError,
}
#[cfg(feature = "payouts")]
impl From<EbanxCancelStatus> for PayoutStatus {
fn from(item: EbanxCancelStatus) -> Self {
match item {
EbanxCancelStatus::Success => Self::Cancelled,
EbanxCancelStatus::ApiError
| EbanxCancelStatus::AuthenticationError
| EbanxCancelStatus::InvalidRequestError
| EbanxCancelStatus::RequestError => Self::Failed,
}
}
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, EbanxCancelResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, EbanxCancelResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::from(item.response.status)),
connector_payout_id: item.data.request.connector_payout_id.clone(),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3160
}
|
large_file_-7476444514756778456
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs
</path>
<file>
use api_models::webhooks::IncomingWebhookEvent;
use common_enums::{AttemptStatus, Currency, FraudCheckStatus, PaymentMethod};
use common_utils::{ext_traits::ValueExt, pii::Email};
use error_stack::{self, ResultExt};
pub use hyperswitch_domain_models::router_request_types::fraud_check::RefundMethod;
use hyperswitch_domain_models::{
router_data::RouterData,
router_flow_types::Fulfillment,
router_request_types::{
fraud_check::{self, FraudCheckFulfillmentData, FrmFulfillmentRequest},
ResponseId,
},
router_response_types::fraud_check::FraudCheckResponseData,
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::Secret;
use num_traits::ToPrimitive;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;
use crate::{
types::{
FrmCheckoutRouterData, FrmFulfillmentRouterData, FrmRecordReturnRouterData,
FrmSaleRouterData, FrmTransactionRouterData, ResponseRouterData,
},
utils::{
AddressDetailsData as _, FraudCheckCheckoutRequest, FraudCheckRecordReturnRequest as _,
FraudCheckSaleRequest as _, FraudCheckTransactionRequest as _, RouterData as _,
},
};
#[allow(dead_code)]
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DecisionDelivery {
Sync,
AsyncOnly,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Purchase {
#[serde(with = "common_utils::custom_serde::iso8601")]
created_at: PrimitiveDateTime,
order_channel: OrderChannel,
total_price: i64,
products: Vec<Products>,
shipments: Shipments,
currency: Option<Currency>,
total_shipping_cost: Option<i64>,
confirmation_email: Option<Email>,
confirmation_phone: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde(rename_all(serialize = "SCREAMING_SNAKE_CASE", deserialize = "snake_case"))]
pub enum OrderChannel {
Web,
Phone,
MobileApp,
Social,
Marketplace,
InStoreKiosk,
ScanAndGo,
SmartTv,
Mit,
}
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde(rename_all(serialize = "SCREAMING_SNAKE_CASE", deserialize = "snake_case"))]
pub enum FulfillmentMethod {
Delivery,
CounterPickup,
CubsidePickup,
LockerPickup,
StandardShipping,
ExpeditedShipping,
GasPickup,
ScheduledDelivery,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Products {
item_name: String,
item_price: i64,
item_quantity: i32,
item_id: Option<String>,
item_category: Option<String>,
item_sub_category: Option<String>,
item_is_digital: Option<bool>,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Shipments {
destination: Destination,
fulfillment_method: Option<FulfillmentMethod>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Destination {
full_name: Secret<String>,
organization: Option<String>,
email: Option<Email>,
address: Address,
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Address {
street_address: Secret<String>,
unit: Option<Secret<String>>,
postal_code: Secret<String>,
city: String,
province_code: Secret<String>,
country_code: common_enums::CountryAlpha2,
}
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde(rename_all(serialize = "SCREAMING_SNAKE_CASE", deserialize = "snake_case"))]
pub enum CoverageRequests {
Fraud, // use when you need a financial guarantee for Payment Fraud.
Inr, // use when you need a financial guarantee for Item Not Received.
Snad, // use when you need a financial guarantee for fraud alleging items are Significantly Not As Described.
All, // use when you need a financial guarantee on all chargebacks.
None, // use when you do not need a financial guarantee. Suggested actions in decision.checkpointAction are recommendations.
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsSaleRequest {
order_id: String,
purchase: Purchase,
decision_delivery: DecisionDelivery,
coverage_requests: Option<CoverageRequests>,
}
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde(rename_all(serialize = "camelCase", deserialize = "snake_case"))]
pub struct SignifydFrmMetadata {
pub total_shipping_cost: Option<i64>,
pub fulfillment_method: Option<FulfillmentMethod>,
pub coverage_request: Option<CoverageRequests>,
pub order_channel: OrderChannel,
}
impl TryFrom<&FrmSaleRouterData> for SignifydPaymentsSaleRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &FrmSaleRouterData) -> Result<Self, Self::Error> {
let products = item
.request
.get_order_details()?
.iter()
.map(|order_detail| Products {
item_name: order_detail.product_name.clone(),
item_price: order_detail.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future.
item_quantity: i32::from(order_detail.quantity),
item_id: order_detail.product_id.clone(),
item_category: order_detail.category.clone(),
item_sub_category: order_detail.sub_category.clone(),
item_is_digital: order_detail
.product_type
.as_ref()
.map(|product| product == &common_enums::ProductType::Digital),
})
.collect::<Vec<_>>();
let metadata: SignifydFrmMetadata = item
.frm_metadata
.clone()
.ok_or(ConnectorError::MissingRequiredField {
field_name: "frm_metadata",
})?
.parse_value("Signifyd Frm Metadata")
.change_context(ConnectorError::InvalidDataFormat {
field_name: "frm_metadata",
})?;
let ship_address = item.get_shipping_address()?;
let billing_address = item.get_billing()?;
let street_addr = ship_address.get_line1()?;
let city_addr = ship_address.get_city()?;
let zip_code_addr = ship_address.get_zip()?;
let country_code_addr = ship_address.get_country()?;
let _first_name_addr = ship_address.get_first_name()?;
let _last_name_addr = ship_address.get_last_name()?;
let address: Address = Address {
street_address: street_addr.clone(),
unit: None,
postal_code: zip_code_addr.clone(),
city: city_addr.clone(),
province_code: zip_code_addr.clone(),
country_code: country_code_addr.to_owned(),
};
let destination: Destination = Destination {
full_name: ship_address.get_full_name().unwrap_or_default(),
organization: None,
email: None,
address,
};
let created_at = common_utils::date_time::now();
let order_channel = metadata.order_channel;
let shipments = Shipments {
destination,
fulfillment_method: metadata.fulfillment_method,
};
let purchase = Purchase {
created_at,
order_channel,
total_price: item.request.amount,
products,
shipments,
currency: item.request.currency,
total_shipping_cost: metadata.total_shipping_cost,
confirmation_email: item.request.email.clone(),
confirmation_phone: billing_address
.clone()
.phone
.and_then(|phone_data| phone_data.number),
};
Ok(Self {
order_id: item.attempt_id.clone(),
purchase,
decision_delivery: DecisionDelivery::Sync, // Specify SYNC if you require the Response to contain a decision field. If you have registered for a webhook associated with this checkpoint, then the webhook will also be sent when SYNC is specified. If ASYNC_ONLY is specified, then the decision field in the response will be null, and you will require a Webhook integration to receive Signifyd's final decision
coverage_requests: metadata.coverage_request,
})
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Decision {
#[serde(with = "common_utils::custom_serde::iso8601")]
created_at: PrimitiveDateTime,
checkpoint_action: SignifydPaymentStatus,
checkpoint_action_reason: Option<String>,
checkpoint_action_policy: Option<String>,
score: Option<f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SignifydPaymentStatus {
Accept,
Challenge,
Credit,
Hold,
Reject,
}
impl From<SignifydPaymentStatus> for FraudCheckStatus {
fn from(item: SignifydPaymentStatus) -> Self {
match item {
SignifydPaymentStatus::Accept => Self::Legit,
SignifydPaymentStatus::Reject => Self::Fraud,
SignifydPaymentStatus::Hold => Self::ManualReview,
SignifydPaymentStatus::Challenge | SignifydPaymentStatus::Credit => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsResponse {
signifyd_id: i64,
order_id: String,
decision: Decision,
}
impl<F, T> TryFrom<ResponseRouterData<F, SignifydPaymentsResponse, T, FraudCheckResponseData>>
for RouterData<F, T, FraudCheckResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SignifydPaymentsResponse, T, FraudCheckResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id),
status: FraudCheckStatus::from(item.response.decision.checkpoint_action),
connector_metadata: None,
score: item.response.decision.score.and_then(|data| data.to_i32()),
reason: item
.response
.decision
.checkpoint_action_reason
.map(serde_json::Value::from),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct SignifydErrorResponse {
pub messages: Vec<String>,
pub errors: serde_json::Value,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Transactions {
transaction_id: String,
gateway_status_code: String,
payment_method: PaymentMethod,
amount: i64,
currency: Currency,
gateway: Option<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsTransactionRequest {
order_id: String,
checkout_id: String,
transactions: Transactions,
}
impl From<AttemptStatus> for GatewayStatusCode {
fn from(item: AttemptStatus) -> Self {
match item {
AttemptStatus::Pending => Self::Pending,
AttemptStatus::Failure => Self::Failure,
AttemptStatus::Charged => Self::Success,
_ => Self::Pending,
}
}
}
impl TryFrom<&FrmTransactionRouterData> for SignifydPaymentsTransactionRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &FrmTransactionRouterData) -> Result<Self, Self::Error> {
let currency = item.request.get_currency()?;
let transactions = Transactions {
amount: item.request.amount,
transaction_id: item.clone().payment_id,
gateway_status_code: GatewayStatusCode::from(item.status).to_string(),
payment_method: item.payment_method,
currency,
gateway: item.request.connector.clone(),
};
Ok(Self {
order_id: item.attempt_id.clone(),
checkout_id: item.payment_id.clone(),
transactions,
})
}
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
pub enum GatewayStatusCode {
Success,
Failure,
#[default]
Pending,
Error,
Cancelled,
Expired,
SoftDecline,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsCheckoutRequest {
checkout_id: String,
order_id: String,
purchase: Purchase,
coverage_requests: Option<CoverageRequests>,
}
impl TryFrom<&FrmCheckoutRouterData> for SignifydPaymentsCheckoutRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &FrmCheckoutRouterData) -> Result<Self, Self::Error> {
let products = item
.request
.get_order_details()?
.iter()
.map(|order_detail| Products {
item_name: order_detail.product_name.clone(),
item_price: order_detail.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future.
item_quantity: i32::from(order_detail.quantity),
item_id: order_detail.product_id.clone(),
item_category: order_detail.category.clone(),
item_sub_category: order_detail.sub_category.clone(),
item_is_digital: order_detail
.product_type
.as_ref()
.map(|product| product == &common_enums::ProductType::Digital),
})
.collect::<Vec<_>>();
let metadata: SignifydFrmMetadata = item
.frm_metadata
.clone()
.ok_or(ConnectorError::MissingRequiredField {
field_name: "frm_metadata",
})?
.parse_value("Signifyd Frm Metadata")
.change_context(ConnectorError::InvalidDataFormat {
field_name: "frm_metadata",
})?;
let ship_address = item.get_shipping_address()?;
let street_addr = ship_address.get_line1()?;
let city_addr = ship_address.get_city()?;
let zip_code_addr = ship_address.get_zip()?;
let country_code_addr = ship_address.get_country()?;
let _first_name_addr = ship_address.get_first_name()?;
let _last_name_addr = ship_address.get_last_name()?;
let billing_address = item.get_billing()?;
let address: Address = Address {
street_address: street_addr.clone(),
unit: None,
postal_code: zip_code_addr.clone(),
city: city_addr.clone(),
province_code: zip_code_addr.clone(),
country_code: country_code_addr.to_owned(),
};
let destination: Destination = Destination {
full_name: ship_address.get_full_name().unwrap_or_default(),
organization: None,
email: None,
address,
};
let created_at = common_utils::date_time::now();
let order_channel = metadata.order_channel;
let shipments: Shipments = Shipments {
destination,
fulfillment_method: metadata.fulfillment_method,
};
let purchase = Purchase {
created_at,
order_channel,
total_price: item.request.amount,
products,
shipments,
currency: item.request.currency,
total_shipping_cost: metadata.total_shipping_cost,
confirmation_email: item.request.email.clone(),
confirmation_phone: billing_address
.clone()
.phone
.and_then(|phone_data| phone_data.number),
};
Ok(Self {
checkout_id: item.payment_id.clone(),
order_id: item.attempt_id.clone(),
purchase,
coverage_requests: metadata.coverage_request,
})
}
}
#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct FrmFulfillmentSignifydRequest {
pub order_id: String,
pub fulfillment_status: Option<FulfillmentStatus>,
pub fulfillments: Vec<Fulfillments>,
}
#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde(untagged)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub enum FulfillmentStatus {
PARTIAL,
COMPLETE,
REPLACEMENT,
CANCELED,
}
#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct Fulfillments {
pub shipment_id: String,
pub products: Option<Vec<Product>>,
pub destination: Destination,
pub fulfillment_method: Option<String>,
pub carrier: Option<String>,
pub shipment_status: Option<String>,
pub tracking_urls: Option<Vec<String>>,
pub tracking_numbers: Option<Vec<String>>,
pub shipped_at: Option<String>,
}
#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct Product {
pub item_name: String,
pub item_quantity: i64,
pub item_id: String,
}
impl TryFrom<&FrmFulfillmentRouterData> for FrmFulfillmentSignifydRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &FrmFulfillmentRouterData) -> Result<Self, Self::Error> {
Ok(Self {
order_id: item.request.fulfillment_req.order_id.clone(),
fulfillment_status: item
.request
.fulfillment_req
.fulfillment_status
.as_ref()
.map(|fulfillment_status| FulfillmentStatus::from(&fulfillment_status.clone())),
fulfillments: get_signifyd_fulfillments_from_frm_fulfillment_request(
&item.request.fulfillment_req,
),
})
}
}
impl From<&fraud_check::FulfillmentStatus> for FulfillmentStatus {
fn from(status: &fraud_check::FulfillmentStatus) -> Self {
match status {
fraud_check::FulfillmentStatus::PARTIAL => Self::PARTIAL,
fraud_check::FulfillmentStatus::COMPLETE => Self::COMPLETE,
fraud_check::FulfillmentStatus::REPLACEMENT => Self::REPLACEMENT,
fraud_check::FulfillmentStatus::CANCELED => Self::CANCELED,
}
}
}
pub(crate) fn get_signifyd_fulfillments_from_frm_fulfillment_request(
fulfillment_req: &FrmFulfillmentRequest,
) -> Vec<Fulfillments> {
fulfillment_req
.fulfillments
.iter()
.map(|fulfillment| Fulfillments {
shipment_id: fulfillment.shipment_id.clone(),
products: fulfillment
.products
.as_ref()
.map(|products| products.iter().map(|p| Product::from(p.clone())).collect()),
destination: Destination::from(fulfillment.destination.clone()),
tracking_urls: fulfillment_req.tracking_urls.clone(),
tracking_numbers: fulfillment_req.tracking_numbers.clone(),
fulfillment_method: fulfillment_req.fulfillment_method.clone(),
carrier: fulfillment_req.carrier.clone(),
shipment_status: fulfillment_req.shipment_status.clone(),
shipped_at: fulfillment_req.shipped_at.clone(),
})
.collect()
}
impl From<fraud_check::Product> for Product {
fn from(product: fraud_check::Product) -> Self {
Self {
item_name: product.item_name,
item_quantity: product.item_quantity,
item_id: product.item_id,
}
}
}
impl From<fraud_check::Destination> for Destination {
fn from(destination: fraud_check::Destination) -> Self {
Self {
full_name: destination.full_name,
organization: destination.organization,
email: destination.email,
address: Address::from(destination.address),
}
}
}
impl From<fraud_check::Address> for Address {
fn from(address: fraud_check::Address) -> Self {
Self {
street_address: address.street_address,
unit: address.unit,
postal_code: address.postal_code,
city: address.city,
province_code: address.province_code,
country_code: address.country_code,
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct FrmFulfillmentSignifydApiResponse {
pub order_id: String,
pub shipment_ids: Vec<String>,
}
impl
TryFrom<
ResponseRouterData<
Fulfillment,
FrmFulfillmentSignifydApiResponse,
FraudCheckFulfillmentData,
FraudCheckResponseData,
>,
> for RouterData<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
Fulfillment,
FrmFulfillmentSignifydApiResponse,
FraudCheckFulfillmentData,
FraudCheckResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(FraudCheckResponseData::FulfillmentResponse {
order_id: item.response.order_id,
shipment_ids: item.response.shipment_ids,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct SignifydRefund {
method: RefundMethod,
amount: String,
currency: Currency,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsRecordReturnRequest {
order_id: String,
return_id: String,
refund_transaction_id: Option<String>,
refund: SignifydRefund,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsRecordReturnResponse {
return_id: String,
order_id: String,
}
impl<F, T>
TryFrom<ResponseRouterData<F, SignifydPaymentsRecordReturnResponse, T, FraudCheckResponseData>>
for RouterData<F, T, FraudCheckResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
SignifydPaymentsRecordReturnResponse,
T,
FraudCheckResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(FraudCheckResponseData::RecordReturnResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id),
return_id: Some(item.response.return_id.to_string()),
connector_metadata: None,
}),
..item.data
})
}
}
impl TryFrom<&FrmRecordReturnRouterData> for SignifydPaymentsRecordReturnRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &FrmRecordReturnRouterData) -> Result<Self, Self::Error> {
let currency = item.request.get_currency()?;
let refund = SignifydRefund {
method: item.request.refund_method.clone(),
amount: item.request.amount.to_string(),
currency,
};
Ok(Self {
return_id: uuid::Uuid::new_v4().to_string(),
refund_transaction_id: item.request.refund_transaction_id.clone(),
refund,
order_id: item.attempt_id.clone(),
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SignifydWebhookBody {
pub order_id: String,
pub review_disposition: ReviewDisposition,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ReviewDisposition {
Fraudulent,
Good,
}
impl From<ReviewDisposition> for IncomingWebhookEvent {
fn from(value: ReviewDisposition) -> Self {
match value {
ReviewDisposition::Fraudulent => Self::FrmRejected,
ReviewDisposition::Good => Self::FrmApproved,
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5369
}
|
large_file_-4486126775891299715
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs
</path>
<file>
use bytes::Bytes;
use common_enums::enums;
use common_utils::{
date_time::DateFormat, errors::CustomResult, ext_traits::ValueExt, types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{CompleteAuthorizeData, PaymentsAuthorizeData, ResponseId},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types,
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, CardData as _, CardMandateInfo, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, RouterData as _,
},
};
pub struct PayboxRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for PayboxRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
const AUTH_REQUEST: &str = "00001";
const CAPTURE_REQUEST: &str = "00002";
const AUTH_AND_CAPTURE_REQUEST: &str = "00003";
const SYNC_REQUEST: &str = "00017";
const REFUND_REQUEST: &str = "00014";
const SUCCESS_CODE: &str = "00000";
const VERSION_PAYBOX: &str = "00104";
const PAY_ORIGIN_INTERNET: &str = "024";
const THREE_DS_FAIL_CODE: &str = "00000000";
const RECURRING_ORIGIN: &str = "027";
const MANDATE_REQUEST: &str = "00056";
const MANDATE_AUTH_ONLY: &str = "00051";
const MANDATE_AUTH_AND_CAPTURE_ONLY: &str = "00053";
type Error = error_stack::Report<errors::ConnectorError>;
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PayboxPaymentsRequest {
Card(PaymentsRequest),
CardThreeDs(ThreeDSPaymentsRequest),
Mandate(MandatePaymentRequest),
}
#[derive(Debug, Serialize)]
pub struct PaymentsRequest {
#[serde(rename = "DATEQ")]
pub date: String,
#[serde(rename = "TYPE")]
pub transaction_type: String,
#[serde(rename = "NUMQUESTION")]
pub paybox_request_number: String,
#[serde(rename = "MONTANT")]
pub amount: MinorUnit,
#[serde(rename = "REFERENCE")]
pub description_reference: String,
#[serde(rename = "VERSION")]
pub version: String,
#[serde(rename = "DEVISE")]
pub currency: String,
#[serde(rename = "PORTEUR")]
pub card_number: cards::CardNumber,
#[serde(rename = "DATEVAL")]
pub expiration_date: Secret<String>,
#[serde(rename = "CVV")]
pub cvv: Secret<String>,
#[serde(rename = "ACTIVITE")]
pub activity: String,
#[serde(rename = "SITE")]
pub site: Secret<String>,
#[serde(rename = "RANG")]
pub rank: Secret<String>,
#[serde(rename = "CLE")]
pub key: Secret<String>,
#[serde(rename = "ID3D")]
#[serde(skip_serializing_if = "Option::is_none")]
pub three_ds_data: Option<Secret<String>>,
#[serde(rename = "REFABONNE")]
#[serde(skip_serializing_if = "Option::is_none")]
pub customer_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ThreeDSPaymentsRequest {
id_merchant: Secret<String>,
id_session: String,
amount: MinorUnit,
currency: String,
#[serde(rename = "CCNumber")]
cc_number: cards::CardNumber,
#[serde(rename = "CCExpDate")]
cc_exp_date: Secret<String>,
#[serde(rename = "CVVCode")]
cvv_code: Secret<String>,
#[serde(rename = "URLRetour")]
url_retour: String,
#[serde(rename = "URLHttpDirect")]
url_http_direct: String,
email_porteur: common_utils::pii::Email,
first_name: Secret<String>,
last_name: Secret<String>,
address1: Secret<String>,
zip_code: Secret<String>,
city: String,
country_code: String,
total_quantity: i32,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PayboxCaptureRequest {
#[serde(rename = "DATEQ")]
pub date: String,
#[serde(rename = "TYPE")]
pub transaction_type: String,
#[serde(rename = "NUMQUESTION")]
pub paybox_request_number: String,
#[serde(rename = "MONTANT")]
pub amount: MinorUnit,
#[serde(rename = "REFERENCE")]
pub reference: String,
#[serde(rename = "VERSION")]
pub version: String,
#[serde(rename = "DEVISE")]
pub currency: String,
#[serde(rename = "SITE")]
pub site: Secret<String>,
#[serde(rename = "RANG")]
pub rank: Secret<String>,
#[serde(rename = "CLE")]
pub key: Secret<String>,
#[serde(rename = "NUMTRANS")]
pub transaction_number: String,
#[serde(rename = "NUMAPPEL")]
pub paybox_order_id: String,
}
impl TryFrom<&PayboxRouterData<&types::PaymentsCaptureRouterData>> for PayboxCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PayboxRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let auth_data: PayboxAuthType =
PayboxAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let currency = enums::Currency::iso_4217(item.router_data.request.currency).to_string();
let paybox_meta_data: PayboxMeta =
utils::to_connector_meta(item.router_data.request.connector_meta.clone())?;
let format_time = common_utils::date_time::format_date(
common_utils::date_time::now(),
DateFormat::DDMMYYYYHHmmss,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
date: format_time.clone(),
transaction_type: CAPTURE_REQUEST.to_string(),
paybox_request_number: get_paybox_request_number()?,
version: VERSION_PAYBOX.to_string(),
currency,
site: auth_data.site,
rank: auth_data.rang,
key: auth_data.cle,
transaction_number: paybox_meta_data.connector_request_id,
paybox_order_id: item.router_data.request.connector_transaction_id.clone(),
amount: item.amount,
reference: item.router_data.connector_request_reference_id.to_string(),
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PayboxRsyncRequest {
#[serde(rename = "DATEQ")]
pub date: String,
#[serde(rename = "TYPE")]
pub transaction_type: String,
#[serde(rename = "NUMQUESTION")]
pub paybox_request_number: String,
#[serde(rename = "VERSION")]
pub version: String,
#[serde(rename = "SITE")]
pub site: Secret<String>,
#[serde(rename = "RANG")]
pub rank: Secret<String>,
#[serde(rename = "CLE")]
pub key: Secret<String>,
#[serde(rename = "NUMTRANS")]
pub transaction_number: String,
#[serde(rename = "NUMAPPEL")]
pub paybox_order_id: String,
}
impl TryFrom<&types::RefundSyncRouterData> for PayboxRsyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
let auth_data: PayboxAuthType = PayboxAuthType::try_from(&item.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let format_time = common_utils::date_time::format_date(
common_utils::date_time::now(),
DateFormat::DDMMYYYYHHmmss,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
date: format_time.clone(),
transaction_type: SYNC_REQUEST.to_string(),
paybox_request_number: get_paybox_request_number()?,
version: VERSION_PAYBOX.to_string(),
site: auth_data.site,
rank: auth_data.rang,
key: auth_data.cle,
transaction_number: item
.request
.connector_refund_id
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?,
paybox_order_id: item.request.connector_transaction_id.clone(),
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PayboxPSyncRequest {
#[serde(rename = "DATEQ")]
pub date: String,
#[serde(rename = "TYPE")]
pub transaction_type: String,
#[serde(rename = "NUMQUESTION")]
pub paybox_request_number: String,
#[serde(rename = "VERSION")]
pub version: String,
#[serde(rename = "SITE")]
pub site: Secret<String>,
#[serde(rename = "RANG")]
pub rank: Secret<String>,
#[serde(rename = "CLE")]
pub key: Secret<String>,
#[serde(rename = "NUMTRANS")]
pub transaction_number: String,
#[serde(rename = "NUMAPPEL")]
pub paybox_order_id: String,
}
impl TryFrom<&types::PaymentsSyncRouterData> for PayboxPSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let auth_data: PayboxAuthType = PayboxAuthType::try_from(&item.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let format_time = common_utils::date_time::format_date(
common_utils::date_time::now(),
DateFormat::DDMMYYYYHHmmss,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let paybox_meta_data: PayboxMeta =
utils::to_connector_meta(item.request.connector_meta.clone())?;
Ok(Self {
date: format_time.clone(),
transaction_type: SYNC_REQUEST.to_string(),
paybox_request_number: get_paybox_request_number()?,
version: VERSION_PAYBOX.to_string(),
site: auth_data.site,
rank: auth_data.rang,
key: auth_data.cle,
transaction_number: paybox_meta_data.connector_request_id,
paybox_order_id: item
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PayboxMeta {
pub connector_request_id: String,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PayboxRefundRequest {
#[serde(rename = "DATEQ")]
pub date: String,
#[serde(rename = "TYPE")]
pub transaction_type: String,
#[serde(rename = "NUMQUESTION")]
pub paybox_request_number: String,
#[serde(rename = "MONTANT")]
pub amount: MinorUnit,
#[serde(rename = "VERSION")]
pub version: String,
#[serde(rename = "DEVISE")]
pub currency: String,
#[serde(rename = "SITE")]
pub site: Secret<String>,
#[serde(rename = "RANG")]
pub rank: Secret<String>,
#[serde(rename = "CLE")]
pub key: Secret<String>,
#[serde(rename = "NUMTRANS")]
pub transaction_number: String,
#[serde(rename = "NUMAPPEL")]
pub paybox_order_id: String,
}
impl TryFrom<&PayboxRouterData<&types::PaymentsAuthorizeRouterData>> for PayboxPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PayboxRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let auth_data: PayboxAuthType =
PayboxAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let transaction_type = get_transaction_type(
item.router_data.request.capture_method,
item.router_data.request.is_mandate_payment(),
)?;
let currency =
enums::Currency::iso_4217(item.router_data.request.currency).to_string();
let expiration_date =
req_card.get_card_expiry_month_year_2_digit_with_delimiter("".to_owned())?;
let format_time = common_utils::date_time::format_date(
common_utils::date_time::now(),
DateFormat::DDMMYYYYHHmmss,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
if item.router_data.is_three_ds() {
let address = item.router_data.get_billing_address()?;
Ok(Self::CardThreeDs(ThreeDSPaymentsRequest {
id_merchant: auth_data.merchant_id,
id_session: item.router_data.connector_request_reference_id.clone(),
amount: item.amount,
currency,
cc_number: req_card.card_number,
cc_exp_date: expiration_date,
cvv_code: req_card.card_cvc,
url_retour: item.router_data.request.get_complete_authorize_url()?,
url_http_direct: item.router_data.request.get_complete_authorize_url()?,
email_porteur: item.router_data.request.get_email()?,
first_name: address.get_first_name()?.clone(),
last_name: address.get_last_name()?.clone(),
address1: address.get_line1()?.clone(),
zip_code: address.get_zip()?.clone(),
city: address.get_city()?.clone(),
country_code: format!(
"{:03}",
common_enums::Country::from_alpha2(*address.get_country()?)
.to_numeric()
),
total_quantity: 1,
}))
} else {
Ok(Self::Card(PaymentsRequest {
date: format_time.clone(),
transaction_type,
paybox_request_number: get_paybox_request_number()?,
amount: item.amount,
description_reference: item
.router_data
.connector_request_reference_id
.clone(),
version: VERSION_PAYBOX.to_string(),
currency,
card_number: req_card.card_number,
expiration_date,
cvv: req_card.card_cvc,
activity: PAY_ORIGIN_INTERNET.to_string(),
site: auth_data.site,
rank: auth_data.rang,
key: auth_data.cle,
three_ds_data: None,
customer_id: match item.router_data.request.is_mandate_payment() {
true => {
let reference_id = item
.router_data
.connector_mandate_request_reference_id
.clone()
.ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_request_reference_id",
}
})?;
Some(Secret::new(reference_id))
}
false => None,
},
}))
}
}
PaymentMethodData::MandatePayment => {
let mandate_data = item.router_data.request.get_card_mandate_info()?;
Ok(Self::Mandate(MandatePaymentRequest::try_from((
item,
mandate_data,
))?))
}
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
fn get_transaction_type(
capture_method: Option<enums::CaptureMethod>,
is_mandate_request: bool,
) -> Result<String, Error> {
match (capture_method, is_mandate_request) {
(Some(enums::CaptureMethod::Automatic), false)
| (None, false)
| (Some(enums::CaptureMethod::SequentialAutomatic), false) => {
Ok(AUTH_AND_CAPTURE_REQUEST.to_string())
}
(Some(enums::CaptureMethod::Automatic), true) | (None, true) => {
Err(errors::ConnectorError::NotSupported {
message: "Automatic Capture in CIT payments".to_string(),
connector: "Paybox",
})?
}
(Some(enums::CaptureMethod::Manual), false) => Ok(AUTH_REQUEST.to_string()),
(Some(enums::CaptureMethod::Manual), true)
| (Some(enums::CaptureMethod::SequentialAutomatic), true) => {
Ok(MANDATE_REQUEST.to_string())
}
_ => Err(errors::ConnectorError::CaptureMethodNotSupported)?,
}
}
fn get_paybox_request_number() -> Result<String, Error> {
let time_stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.ok()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.as_millis()
.to_string();
// unix time (in milliseconds) has 13 digits.if we consider 8 digits(the number digits to make day deterministic) there is no collision in the paybox_request_number as it will reset the paybox_request_number for each day and paybox accepting maximum length is 10 so we gonna take 9 (13-9)
let request_number = time_stamp
.get(4..)
.ok_or(errors::ConnectorError::ParsingFailed)?;
Ok(request_number.to_string())
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PayboxAuthType {
pub(super) site: Secret<String>,
pub(super) rang: Secret<String>,
pub(super) cle: Secret<String>,
pub(super) merchant_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PayboxAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} = auth_type
{
Ok(Self {
site: api_key.to_owned(),
rang: key1.to_owned(),
cle: api_secret.to_owned(),
merchant_id: key2.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PayboxResponse {
NonThreeDs(TransactionResponse),
ThreeDs(Secret<String>),
Error(String),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransactionResponse {
#[serde(rename = "NUMTRANS")]
pub transaction_number: String,
#[serde(rename = "NUMAPPEL")]
pub paybox_order_id: String,
#[serde(rename = "CODEREPONSE")]
pub response_code: String,
#[serde(rename = "COMMENTAIRE")]
pub response_message: String,
#[serde(rename = "PORTEUR")]
pub carrier_id: Option<Secret<String>>,
#[serde(rename = "REFABONNE")]
pub customer_id: Option<Secret<String>>,
}
pub fn parse_url_encoded_to_struct<T: DeserializeOwned>(
query_bytes: Bytes,
) -> CustomResult<T, errors::ConnectorError> {
let (cow, _, _) = encoding_rs::ISO_8859_15.decode(&query_bytes);
serde_qs::from_str::<T>(cow.as_ref()).change_context(errors::ConnectorError::ParsingFailed)
}
pub fn parse_paybox_response(
query_bytes: Bytes,
is_three_ds: bool,
) -> CustomResult<PayboxResponse, errors::ConnectorError> {
let (cow, _, _) = encoding_rs::ISO_8859_15.decode(&query_bytes);
let response_str = cow.as_ref().trim();
if utils::is_html_response(response_str) && is_three_ds {
let response = response_str.to_string();
return Ok(if response.contains("Erreur 201") {
PayboxResponse::Error(response)
} else {
PayboxResponse::ThreeDs(response.into())
});
}
serde_qs::from_str::<TransactionResponse>(response_str)
.map(PayboxResponse::NonThreeDs)
.change_context(errors::ConnectorError::ParsingFailed)
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum PayboxStatus {
#[serde(rename = "Remboursé")]
Refunded,
#[serde(rename = "Annulé")]
Cancelled,
#[serde(rename = "Autorisé")]
Authorised,
#[serde(rename = "Capturé")]
Captured,
#[serde(rename = "Refusé")]
Rejected,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PayboxSyncResponse {
#[serde(rename = "NUMTRANS")]
pub transaction_number: String,
#[serde(rename = "NUMAPPEL")]
pub paybox_order_id: String,
#[serde(rename = "CODEREPONSE")]
pub response_code: String,
#[serde(rename = "COMMENTAIRE")]
pub response_message: String,
#[serde(rename = "STATUS")]
pub status: PayboxStatus,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PayboxCaptureResponse {
#[serde(rename = "NUMTRANS")]
pub transaction_number: String,
#[serde(rename = "NUMAPPEL")]
pub paybox_order_id: String,
#[serde(rename = "CODEREPONSE")]
pub response_code: String,
#[serde(rename = "COMMENTAIRE")]
pub response_message: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PayboxCaptureResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PayboxCaptureResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response = item.response.clone();
let status = get_status_of_request(response.response_code.clone());
match status {
true => Ok(Self {
status: enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.paybox_order_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(PayboxMeta {
connector_request_id: response.transaction_number.clone()
})),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
amount_captured: None,
..item.data
}),
false => Ok(Self {
response: Err(ErrorResponse {
code: response.response_code.clone(),
message: response.response_message.clone(),
reason: Some(response.response_message),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.transaction_number),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
impl<F> TryFrom<ResponseRouterData<F, PayboxResponse, PaymentsAuthorizeData, PaymentsResponseData>>
for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PayboxResponse, PaymentsAuthorizeData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.clone() {
PayboxResponse::NonThreeDs(response) => {
let status: bool = get_status_of_request(response.response_code.clone());
match status {
true => Ok(Self {
status: match (
item.data.request.is_auto_capture()?,
item.data.request.is_cit_mandate_payment(),
) {
(_, true) | (false, false) => enums::AttemptStatus::Authorized,
(true, false) => enums::AttemptStatus::Charged,
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.paybox_order_id,
),
redirection_data: Box::new(None),
mandate_reference: Box::new(response.carrier_id.as_ref().map(
|pm: &Secret<String>| MandateReference {
connector_mandate_id: Some(pm.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id:
response.customer_id.map(|secret| secret.expose()),
},
)),
connector_metadata: Some(serde_json::json!(PayboxMeta {
connector_request_id: response.transaction_number.clone()
})),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
false => Ok(Self {
response: Err(ErrorResponse {
code: response.response_code.clone(),
message: response.response_message.clone(),
reason: Some(response.response_message),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(response.transaction_number),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
PayboxResponse::ThreeDs(data) => Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::Html {
html_data: data.peek().to_string(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
PayboxResponse::Error(_) => Ok(Self {
response: Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: Some(NO_ERROR_MESSAGE.to_string()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, PayboxSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PayboxSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response = item.response.clone();
let status = get_status_of_request(response.response_code.clone());
let connector_payment_status = item.response.status;
match status {
true => Ok(Self {
status: enums::AttemptStatus::from(connector_payment_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.paybox_order_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(PayboxMeta {
connector_request_id: response.transaction_number.clone()
})),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
false => Ok(Self {
response: Err(ErrorResponse {
code: response.response_code.clone(),
message: response.response_message.clone(),
reason: Some(response.response_message),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.transaction_number),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
impl From<PayboxStatus> for common_enums::RefundStatus {
fn from(item: PayboxStatus) -> Self {
match item {
PayboxStatus::Refunded => Self::Success,
PayboxStatus::Cancelled
| PayboxStatus::Authorised
| PayboxStatus::Captured
| PayboxStatus::Rejected => Self::Failure,
}
}
}
impl From<PayboxStatus> for enums::AttemptStatus {
fn from(item: PayboxStatus) -> Self {
match item {
PayboxStatus::Cancelled => Self::Voided,
PayboxStatus::Authorised => Self::Authorized,
PayboxStatus::Captured | PayboxStatus::Refunded => Self::Charged,
PayboxStatus::Rejected => Self::Failure,
}
}
}
fn get_status_of_request(item: String) -> bool {
item == *SUCCESS_CODE
}
impl<F> TryFrom<&PayboxRouterData<&types::RefundsRouterData<F>>> for PayboxRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PayboxRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let auth_data: PayboxAuthType =
PayboxAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let currency = enums::Currency::iso_4217(item.router_data.request.currency).to_string();
let format_time = common_utils::date_time::format_date(
common_utils::date_time::now(),
DateFormat::DDMMYYYYHHmmss,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let paybox_meta_data: PayboxMeta =
utils::to_connector_meta(item.router_data.request.connector_metadata.clone())?;
Ok(Self {
date: format_time.clone(),
transaction_type: REFUND_REQUEST.to_string(),
paybox_request_number: get_paybox_request_number()?,
version: VERSION_PAYBOX.to_string(),
currency,
site: auth_data.site,
rank: auth_data.rang,
key: auth_data.cle,
transaction_number: paybox_meta_data.connector_request_id,
paybox_order_id: item.router_data.request.connector_transaction_id.clone(),
amount: item.amount,
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, PayboxSyncResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, PayboxSyncResponse>,
) -> Result<Self, Self::Error> {
let status = get_status_of_request(item.response.response_code.clone());
match status {
true => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_number,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
}),
false => Ok(Self {
response: Err(ErrorResponse {
code: item.response.response_code.clone(),
message: item.response.response_message.clone(),
reason: Some(item.response.response_message),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.transaction_number),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, TransactionResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, TransactionResponse>,
) -> Result<Self, Self::Error> {
let status = get_status_of_request(item.response.response_code.clone());
match status {
true => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_number,
refund_status: common_enums::RefundStatus::Pending,
}),
..item.data
}),
false => Ok(Self {
response: Err(ErrorResponse {
code: item.response.response_code.clone(),
message: item.response.response_message.clone(),
reason: Some(item.response.response_message),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.transaction_number),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct PayboxErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
}
impl<F>
TryFrom<ResponseRouterData<F, TransactionResponse, CompleteAuthorizeData, PaymentsResponseData>>
for RouterData<F, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
TransactionResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response = item.response.clone();
let status = get_status_of_request(response.response_code.clone());
match status {
true => Ok(Self {
status: match (
item.data.request.is_auto_capture()?,
item.data.request.is_cit_mandate_payment(),
) {
(_, true) | (false, false) => enums::AttemptStatus::Authorized,
(true, false) => enums::AttemptStatus::Charged,
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.paybox_order_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(response.carrier_id.as_ref().map(|pm| {
MandateReference {
connector_mandate_id: Some(pm.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: response
.customer_id
.map(|secret| secret.expose()),
}
})),
connector_metadata: Some(serde_json::json!(PayboxMeta {
connector_request_id: response.transaction_number.clone()
})),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
false => Ok(Self {
response: Err(ErrorResponse {
code: response.response_code.clone(),
message: response.response_message.clone(),
reason: Some(response.response_message),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(response.transaction_number),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RedirectionAuthResponse {
#[serde(rename = "ID3D")]
three_ds_data: Option<Secret<String>>,
}
impl TryFrom<&PayboxRouterData<&types::PaymentsCompleteAuthorizeRouterData>> for PaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PayboxRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let redirect_response = item.router_data.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let redirect_payload: RedirectionAuthResponse = redirect_response
.payload
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
})?
.peek()
.clone()
.parse_value("RedirectionAuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
match item.router_data.request.payment_method_data.clone() {
Some(PaymentMethodData::Card(req_card)) => {
let auth_data: PayboxAuthType =
PayboxAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let transaction_type = get_transaction_type(
item.router_data.request.capture_method,
item.router_data.request.is_mandate_payment(),
)?;
let currency =
enums::Currency::iso_4217(item.router_data.request.currency).to_string();
let expiration_date =
req_card.get_card_expiry_month_year_2_digit_with_delimiter("".to_owned())?;
let format_time = common_utils::date_time::format_date(
common_utils::date_time::now(),
DateFormat::DDMMYYYYHHmmss,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
date: format_time.clone(),
transaction_type,
paybox_request_number: get_paybox_request_number()?,
amount: item.router_data.request.minor_amount,
description_reference: item.router_data.connector_request_reference_id.clone(),
version: VERSION_PAYBOX.to_string(),
currency,
card_number: req_card.card_number,
expiration_date,
cvv: req_card.card_cvc,
activity: PAY_ORIGIN_INTERNET.to_string(),
site: auth_data.site,
rank: auth_data.rang,
key: auth_data.cle,
three_ds_data: redirect_payload.three_ds_data.map_or_else(
|| Some(Secret::new(THREE_DS_FAIL_CODE.to_string())),
|data| Some(data.clone()),
),
customer_id: match item.router_data.request.is_mandate_payment() {
true => {
let reference_id = item
.router_data
.connector_mandate_request_reference_id
.clone()
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_request_reference_id",
})?;
Some(Secret::new(reference_id))
}
false => None,
},
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
#[derive(Debug, Serialize)]
pub struct MandatePaymentRequest {
#[serde(rename = "DATEQ")]
pub date: String,
#[serde(rename = "TYPE")]
pub transaction_type: String,
#[serde(rename = "NUMQUESTION")]
pub paybox_request_number: String,
#[serde(rename = "MONTANT")]
pub amount: MinorUnit,
#[serde(rename = "REFERENCE")]
pub description_reference: String,
#[serde(rename = "VERSION")]
pub version: String,
#[serde(rename = "DEVISE")]
pub currency: String,
#[serde(rename = "ACTIVITE")]
pub activity: String,
#[serde(rename = "SITE")]
pub site: Secret<String>,
#[serde(rename = "RANG")]
pub rank: Secret<String>,
#[serde(rename = "CLE")]
pub key: Secret<String>,
#[serde(rename = "DATEVAL")]
pub cc_exp_date: Secret<String>,
#[serde(rename = "REFABONNE")]
pub customer_id: Secret<String>,
#[serde(rename = "PORTEUR")]
pub carrier_id: Secret<String>,
}
impl
TryFrom<(
&PayboxRouterData<&types::PaymentsAuthorizeRouterData>,
CardMandateInfo,
)> for MandatePaymentRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, card_mandate_info): (
&PayboxRouterData<&types::PaymentsAuthorizeRouterData>,
CardMandateInfo,
),
) -> Result<Self, Self::Error> {
let auth_data: PayboxAuthType =
PayboxAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let transaction_type = match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Automatic)
| None
| Some(enums::CaptureMethod::SequentialAutomatic) => {
Ok(MANDATE_AUTH_AND_CAPTURE_ONLY.to_string())
}
Some(enums::CaptureMethod::Manual) => Ok(MANDATE_AUTH_ONLY.to_string()),
_ => Err(errors::ConnectorError::CaptureMethodNotSupported),
}?;
let currency = enums::Currency::iso_4217(item.router_data.request.currency).to_string();
let format_time = common_utils::date_time::format_date(
common_utils::date_time::now(),
DateFormat::DDMMYYYYHHmmss,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
date: format_time.clone(),
transaction_type,
paybox_request_number: get_paybox_request_number()?,
amount: item.router_data.request.minor_amount,
description_reference: item.router_data.connector_request_reference_id.clone(),
version: VERSION_PAYBOX.to_string(),
currency,
activity: RECURRING_ORIGIN.to_string(),
site: auth_data.site,
rank: auth_data.rang,
key: auth_data.cle,
customer_id: Secret::new(
item.router_data
.request
.get_connector_mandate_request_reference_id()?,
),
carrier_id: Secret::new(item.router_data.request.get_connector_mandate_id()?),
cc_exp_date: get_card_expiry_month_year_2_digit(
card_mandate_info.card_exp_month.clone(),
card_mandate_info.card_exp_year.clone(),
)?,
})
}
}
fn get_card_expiry_month_year_2_digit(
card_exp_month: Secret<String>,
card_exp_year: Secret<String>,
) -> Result<Secret<String>, errors::ConnectorError> {
Ok(Secret::new(format!(
"{}{}",
card_exp_month.peek(),
card_exp_year
.peek()
.get(card_exp_year.peek().len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
)))
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 9371
}
|
large_file_-6817216302966306369
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/flexiti/transformers.rs
</path>
<file>
use common_enums::enums;
use common_utils::{pii::Email, request::Method, types::FloatMajorUnit};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{self, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, BrowserInformationData, PaymentsAuthorizeRequestData,
RouterData as _,
},
};
pub struct FlexitiRouterData<T> {
pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for FlexitiRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize)]
pub struct FlexitiPaymentsRequest {
merchant_order_id: Option<String>,
lang: String,
flow: FlexitiFlow,
amount_requested: FloatMajorUnit,
email: Option<Email>,
fname: Secret<String>,
billing_information: BillingInformation,
shipping_information: ShippingInformation,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FlexitiFlow {
#[serde(rename = "apply/buy")]
ApplyAndBuy,
Apply,
Buy,
}
#[derive(Debug, Serialize)]
pub struct BillingInformation {
first_name: Secret<String>,
last_name: Secret<String>,
address_1: Secret<String>,
address_2: Secret<String>,
city: Secret<String>,
postal_code: Secret<String>,
province: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct ShippingInformation {
first_name: Secret<String>,
last_name: Secret<String>,
address_1: Secret<String>,
address_2: Secret<String>,
city: Secret<String>,
postal_code: Secret<String>,
province: Secret<String>,
}
impl TryFrom<&FlexitiRouterData<&PaymentsAuthorizeRouterData>> for FlexitiPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &FlexitiRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::PayLater(pay_later_data) => match pay_later_data {
hyperswitch_domain_models::payment_method_data::PayLaterData::FlexitiRedirect { } => {
let shipping_address = item.router_data.get_shipping_address()?;
let shipping_information = ShippingInformation {
first_name: shipping_address.get_first_name()?.to_owned(),
last_name: shipping_address.get_last_name()?.to_owned(),
address_1: shipping_address.get_line1()?.to_owned(),
address_2: shipping_address.get_line2()?.to_owned(),
city: shipping_address.get_city()?.to_owned().into(),
postal_code: shipping_address.get_zip()?.to_owned(),
province: shipping_address.to_state_code()?,
};
let billing_information = BillingInformation {
first_name: item.router_data.get_billing_first_name()?,
last_name: item.router_data.get_billing_last_name()?,
address_1: item.router_data.get_billing_line1()?,
address_2: item.router_data.get_billing_line2()?,
city: item.router_data.get_billing_city()?.into(),
postal_code: item.router_data.get_billing_zip()?,
province: item.router_data.get_billing_state_code()?,
};
Ok(Self {
merchant_order_id: item.router_data.request.merchant_order_reference_id.to_owned(),
lang: item.router_data.request.get_browser_info()?.get_language()?,
flow: FlexitiFlow::ApplyAndBuy,
amount_requested: item.amount.to_owned(),
email: item.router_data.get_optional_billing_email(),
fname: item.router_data.get_billing_first_name()?,
billing_information,
shipping_information,
})
},
hyperswitch_domain_models::payment_method_data::PayLaterData::KlarnaRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::KlarnaSdk { .. } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AffirmRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::BreadpayRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AfterpayClearpayRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::PayBrightRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::WalleyRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AlmaRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AtomeRedirect { } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("flexiti"),
))
}?,
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
#[derive(Debug, Serialize)]
pub struct FlexitiAccessTokenRequest {
client_id: Secret<String>,
client_secret: Secret<String>,
grant_type: FlexitiGranttype,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FlexitiGranttype {
Password,
RefreshToken,
ClientCredentials,
}
impl TryFrom<&types::RefreshTokenRouterData> for FlexitiAccessTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> {
let auth_details = FlexitiAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
client_id: auth_details.client_id,
client_secret: auth_details.client_secret,
grant_type: FlexitiGranttype::ClientCredentials,
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FlexitiAccessTokenResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FlexitiAccessTokenResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
// Auth Struct
pub struct FlexitiAuthType {
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for FlexitiAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
client_id: api_key.to_owned(),
client_secret: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FlexitiAccessTokenResponse {
access_token: Secret<String>,
expires_in: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlexitiPaymentsResponse {
redirection_url: url::Url,
online_order_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlexitiSyncResponse {
transaction_id: String,
purchase: FlexitiPurchase,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlexitiPurchase {
status: FlexitiPurchaseStatus,
}
// Since this is an alpha integration, we don't have access to all the status mapping. This needs to be updated.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FlexitiPurchaseStatus {
Success,
Failed,
}
// Since this is an alpha integration, we don't have access to all the status mapping. This needs to be updated.
impl From<FlexitiPurchaseStatus> for common_enums::AttemptStatus {
fn from(item: FlexitiPurchaseStatus) -> Self {
match item {
FlexitiPurchaseStatus::Success => Self::Authorized,
FlexitiPurchaseStatus::Failed => Self::Failure,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FlexitiSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FlexitiSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.purchase.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.to_owned(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FlexitiPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FlexitiPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.online_order_id.to_owned(),
),
redirection_data: Box::new(Some(RedirectForm::from((
item.response.redirection_url,
Method::Get,
)))),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct FlexitiRefundRequest {
pub amount: FloatMajorUnit,
}
impl<F> TryFrom<&FlexitiRouterData<&RefundsRouterData<F>>> for FlexitiRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &FlexitiRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FlexitiErrorResponse {
pub message: String,
pub error: String,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/flexiti/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2884
}
|
large_file_5180286650187734789
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs
</path>
<file>
use common_enums::enums;
use common_utils::{
pii::{self, Email},
types::StringMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, RouterData},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm},
types,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::Date;
use crate::{
types::ResponseRouterData,
utils::{self, PaymentsAuthorizeRequestData, PhoneDetailsData, RouterData as _},
};
pub struct MifinityRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for MifinityRouterData<T> {
fn from((amount, router_data): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
pub mod auth_headers {
pub const API_VERSION: &str = "api-version";
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct MifinityConnectorMetadataObject {
pub brand_id: Secret<String>,
pub destination_account_number: Secret<String>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for MifinityConnectorMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
Ok(metadata)
}
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MifinityPaymentsRequest {
money: Money,
client: MifinityClient,
address: MifinityAddress,
validation_key: String,
client_reference: common_utils::id_type::CustomerId,
trace_id: String,
description: String,
destination_account_number: Secret<String>,
brand_id: Secret<String>,
return_url: String,
#[serde(skip_serializing_if = "Option::is_none")]
language_preference: Option<String>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct Money {
amount: StringMajorUnit,
currency: String,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MifinityClient {
first_name: Secret<String>,
last_name: Secret<String>,
phone: Secret<String>,
dialing_code: String,
nationality: api_models::enums::CountryAlpha2,
email_address: Email,
dob: Secret<Date>,
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MifinityAddress {
address_line1: Secret<String>,
country_code: api_models::enums::CountryAlpha2,
city: String,
}
impl TryFrom<&MifinityRouterData<&types::PaymentsAuthorizeRouterData>> for MifinityPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &MifinityRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let metadata: MifinityConnectorMetadataObject =
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::Mifinity(data) => {
let money = Money {
amount: item.amount.clone(),
currency: item.router_data.request.currency.to_string(),
};
let phone_details = item.router_data.get_billing_phone()?;
let client = MifinityClient {
first_name: item.router_data.get_billing_first_name()?,
last_name: item.router_data.get_billing_last_name()?,
phone: phone_details.get_number()?,
dialing_code: phone_details.get_country_code()?,
nationality: item.router_data.get_billing_country()?,
email_address: item.router_data.get_billing_email()?,
dob: data.date_of_birth.clone(),
};
let address = MifinityAddress {
address_line1: item.router_data.get_billing_line1()?,
country_code: item.router_data.get_billing_country()?,
city: item.router_data.get_billing_city()?,
};
let validation_key = format!(
"payment_validation_key_{}_{}",
item.router_data.merchant_id.get_string_repr(),
item.router_data.connector_request_reference_id.clone()
);
let client_reference = item.router_data.customer_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "client_reference",
},
)?;
let destination_account_number = metadata.destination_account_number;
let trace_id = item.router_data.connector_request_reference_id.clone();
let brand_id = metadata.brand_id;
let language_preference = data.language_preference;
Ok(Self {
money,
client,
address,
validation_key,
client_reference,
trace_id: trace_id.clone(),
description: trace_id.clone(), //Connector recommend to use the traceId for a better experience in the BackOffice application later.
destination_account_number,
brand_id,
return_url: item.router_data.request.get_router_return_url()?,
language_preference,
})
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePay(_)
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Mifinity"),
)
.into()),
},
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Mifinity"),
)
.into())
}
}
}
}
// Auth Struct
pub struct MifinityAuthType {
pub(super) key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for MifinityAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MifinityPaymentsResponse {
payload: Vec<MifinityPayload>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MifinityPayload {
trace_id: String,
initialization_token: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, MifinityPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, MifinityPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let payload = item.response.payload.first();
match payload {
Some(payload) => {
let trace_id = payload.trace_id.clone();
let initialization_token = payload.initialization_token.clone();
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(trace_id.clone()),
redirection_data: Box::new(Some(RedirectForm::Mifinity {
initialization_token,
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(trace_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
None => Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MifinityPsyncResponse {
payload: Vec<MifinityPsyncPayload>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MifinityPsyncPayload {
status: MifinityPaymentStatus,
payment_response: Option<PaymentResponse>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentResponse {
trace_id: Option<String>,
client_reference: Option<String>,
validation_key: Option<String>,
transaction_reference: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum MifinityPaymentStatus {
Successful,
Pending,
Failed,
NotCompleted,
}
impl<F, T> TryFrom<ResponseRouterData<F, MifinityPsyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, MifinityPsyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let payload = item.response.payload.first();
match payload {
Some(payload) => {
let status = payload.to_owned().status.clone();
let payment_response = payload.payment_response.clone();
match payment_response {
Some(payment_response) => {
let transaction_reference = payment_response.transaction_reference.clone();
Ok(Self {
status: enums::AttemptStatus::from(status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
transaction_reference,
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
None => Ok(Self {
status: enums::AttemptStatus::from(status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
}
}
None => Ok(Self {
status: item.data.status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
}
}
}
impl From<MifinityPaymentStatus> for enums::AttemptStatus {
fn from(item: MifinityPaymentStatus) -> Self {
match item {
MifinityPaymentStatus::Successful => Self::Charged,
MifinityPaymentStatus::Failed => Self::Failure,
MifinityPaymentStatus::NotCompleted => Self::AuthenticationPending,
MifinityPaymentStatus::Pending => Self::Pending,
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct MifinityErrorResponse {
pub errors: Vec<MifinityErrorList>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MifinityErrorList {
#[serde(rename = "type")]
pub error_type: String,
pub error_code: String,
pub message: String,
pub field: Option<String>,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3183
}
|
large_file_4073703132246133113
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs
</path>
<file>
#[cfg(feature = "v2")]
use std::str::FromStr;
use common_enums::enums;
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
use common_utils::id_type;
use common_utils::{errors::CustomResult, ext_traits::ByteSliceExt, types::StringMinorUnit};
use error_stack::ResultExt;
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
use hyperswitch_domain_models::revenue_recovery;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
#[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_types,
router_response_types::revenue_recovery as recovery_response_types,
types as recovery_router_data_types,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{convert_uppercase, PaymentsAuthorizeRequestData},
};
pub mod auth_headers {
pub const STRIPE_API_VERSION: &str = "stripe-version";
pub const STRIPE_VERSION: &str = "2022-11-15";
}
//TODO: Fill the struct with respective fields
pub struct StripebillingRouterData<T> {
pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for StripebillingRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct StripebillingPaymentsRequest {
amount: StringMinorUnit,
card: StripebillingCard,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct StripebillingCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&StripebillingRouterData<&PaymentsAuthorizeRouterData>>
for StripebillingPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &StripebillingRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = StripebillingCard {
number: req_card.card_number,
expiry_month: req_card.card_exp_month,
expiry_year: req_card.card_exp_year,
cvc: req_card.card_cvc,
complete: item.router_data.request.is_auto_capture()?,
};
Ok(Self {
amount: item.amount.clone(),
card,
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
//TODO: Fill the struct with respective fields
// Auth Struct
pub struct StripebillingAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for StripebillingAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
//TODO: Append the remaining status flags
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Copy)]
#[serde(rename_all = "lowercase")]
pub enum StripebillingPaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<StripebillingPaymentStatus> for common_enums::AttemptStatus {
fn from(item: StripebillingPaymentStatus) -> Self {
match item {
StripebillingPaymentStatus::Succeeded => Self::Charged,
StripebillingPaymentStatus::Failed => Self::Failure,
StripebillingPaymentStatus::Processing => Self::Authorizing,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StripebillingPaymentsResponse {
status: StripebillingPaymentStatus,
id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, StripebillingPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, StripebillingPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct StripebillingRefundRequest {
pub amount: StringMinorUnit,
}
impl<F> TryFrom<&StripebillingRouterData<&RefundsRouterData<F>>> for StripebillingRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &StripebillingRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone, Copy)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct StripebillingErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct StripebillingWebhookBody {
#[serde(rename = "type")]
pub event_type: StripebillingEventType,
pub data: StripebillingWebhookData,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct StripebillingInvoiceBody {
#[serde(rename = "type")]
pub event_type: StripebillingEventType,
pub data: StripebillingInvoiceData,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum StripebillingEventType {
#[serde(rename = "invoice.paid")]
PaymentSucceeded,
#[serde(rename = "invoice.payment_failed")]
PaymentFailed,
#[serde(rename = "invoice.voided")]
InvoiceDeleted,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct StripebillingWebhookData {
pub object: StripebillingWebhookObject,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct StripebillingInvoiceData {
pub object: StripebillingWebhookObject,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct StripebillingWebhookObject {
#[serde(rename = "id")]
pub invoice_id: String,
#[serde(deserialize_with = "convert_uppercase")]
pub currency: enums::Currency,
pub customer: String,
#[serde(rename = "amount_remaining")]
pub amount: common_utils::types::MinorUnit,
pub charge: String,
pub payment_intent: String,
pub customer_address: Option<StripebillingInvoiceBillingAddress>,
pub attempt_count: u16,
pub lines: StripebillingWebhookLinesObject,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct StripebillingWebhookLinesObject {
pub data: Vec<StripebillingWebhookLinesData>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct StripebillingWebhookLinesData {
pub period: StripebillingWebhookLineDataPeriod,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct StripebillingWebhookLineDataPeriod {
#[serde(with = "common_utils::custom_serde::timestamp")]
pub end: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::timestamp")]
pub start: PrimitiveDateTime,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct StripebillingInvoiceBillingAddress {
pub country: Option<enums::CountryAlpha2>,
pub city: Option<String>,
pub address_line1: Option<Secret<String>>,
pub address_line2: Option<Secret<String>>,
pub zip_code: Option<Secret<String>>,
pub state: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct StripebillingInvoiceObject {
#[serde(rename = "id")]
pub invoice_id: String,
#[serde(deserialize_with = "convert_uppercase")]
pub currency: enums::Currency,
#[serde(rename = "amount_remaining")]
pub amount: common_utils::types::MinorUnit,
pub attempt_count: Option<u16>,
}
impl StripebillingWebhookBody {
pub fn get_webhook_object_from_body(body: &[u8]) -> CustomResult<Self, errors::ConnectorError> {
let webhook_body: Self = body
.parse_struct::<Self>("StripebillingWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(webhook_body)
}
}
impl StripebillingInvoiceBody {
pub fn get_invoice_webhook_data_from_body(
body: &[u8],
) -> CustomResult<Self, errors::ConnectorError> {
let webhook_body = body
.parse_struct::<Self>("StripebillingInvoiceBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(webhook_body)
}
}
impl From<StripebillingInvoiceBillingAddress> for api_models::payments::Address {
fn from(item: StripebillingInvoiceBillingAddress) -> Self {
Self {
address: Some(api_models::payments::AddressDetails::from(item)),
phone: None,
email: None,
}
}
}
impl From<StripebillingInvoiceBillingAddress> for api_models::payments::AddressDetails {
fn from(item: StripebillingInvoiceBillingAddress) -> Self {
Self {
city: item.city,
state: item.state,
country: item.country,
zip: item.zip_code,
line1: item.address_line1,
line2: item.address_line2,
line3: None,
first_name: None,
last_name: None,
origin_zip: None,
}
}
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
impl TryFrom<StripebillingInvoiceBody> for revenue_recovery::RevenueRecoveryInvoiceData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: StripebillingInvoiceBody) -> Result<Self, Self::Error> {
let merchant_reference_id =
id_type::PaymentReferenceId::from_str(&item.data.object.invoice_id)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let next_billing_at = item
.data
.object
.lines
.data
.first()
.map(|linedata| linedata.period.end);
let billing_started_at = item
.data
.object
.lines
.data
.first()
.map(|linedata| linedata.period.start);
Ok(Self {
amount: item.data.object.amount,
currency: item.data.object.currency,
merchant_reference_id,
billing_address: item
.data
.object
.customer_address
.map(api_models::payments::Address::from),
retry_count: Some(item.data.object.attempt_count),
next_billing_at,
billing_started_at,
metadata: None,
// TODO! This field should be handled for billing connnector integrations
enable_partial_authorization: None,
})
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct StripebillingRecoveryDetailsData {
#[serde(rename = "id")]
pub charge_id: String,
pub status: StripebillingChargeStatus,
pub amount: common_utils::types::MinorUnit,
#[serde(deserialize_with = "convert_uppercase")]
pub currency: enums::Currency,
pub customer: String,
pub payment_method: String,
pub failure_code: Option<String>,
pub failure_message: Option<String>,
#[serde(with = "common_utils::custom_serde::timestamp")]
pub created: PrimitiveDateTime,
pub payment_method_details: StripePaymentMethodDetails,
#[serde(rename = "invoice")]
pub invoice_id: String,
pub payment_intent: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct StripePaymentMethodDetails {
#[serde(rename = "type")]
pub type_of_payment_method: StripebillingPaymentMethod,
#[serde(rename = "card")]
pub card_details: StripeBillingCardDetails,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum StripebillingPaymentMethod {
Card,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct StripeBillingCardDetails {
pub network: StripebillingCardNetwork,
pub funding: StripebillingFundingTypes,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum StripebillingCardNetwork {
Visa,
Mastercard,
AmericanExpress,
JCB,
DinersClub,
Discover,
CartesBancaires,
UnionPay,
Interac,
RuPay,
Maestro,
Star,
Pulse,
Accel,
Nyce,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename = "snake_case")]
pub enum StripebillingFundingTypes {
#[serde(rename = "credit")]
Credit,
#[serde(rename = "debit")]
Debit,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum StripebillingChargeStatus {
Succeeded,
Failed,
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
// This is the default hard coded mca Id to find the stripe account associated with the stripe biliing
// Context : Since we dont have the concept of connector_reference_id in stripebilling because payments always go through stripe.
// While creating stripebilling we will hard code the stripe account id to string "stripebilling" in mca featrue metadata. So we have to pass the same as account_reference_id here in response.
const MCA_ID_IDENTIFIER_FOR_STRIPE_IN_STRIPEBILLING_MCA_FEAATURE_METADATA: &str = "stripebilling";
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl
TryFrom<
ResponseRouterData<
recovery_router_flows::BillingConnectorPaymentsSync,
StripebillingRecoveryDetailsData,
recovery_request_types::BillingConnectorPaymentsSyncRequest,
recovery_response_types::BillingConnectorPaymentsSyncResponse,
>,
> for recovery_router_data_types::BillingConnectorPaymentsSyncRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
recovery_router_flows::BillingConnectorPaymentsSync,
StripebillingRecoveryDetailsData,
recovery_request_types::BillingConnectorPaymentsSyncRequest,
recovery_response_types::BillingConnectorPaymentsSyncResponse,
>,
) -> Result<Self, Self::Error> {
let charge_details = item.response;
let merchant_reference_id =
id_type::PaymentReferenceId::from_str(charge_details.invoice_id.as_str())
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "invoice_id",
})?;
let connector_transaction_id = Some(common_utils::types::ConnectorTransactionId::from(
charge_details.payment_intent,
));
Ok(Self {
response: Ok(
recovery_response_types::BillingConnectorPaymentsSyncResponse {
status: charge_details.status.into(),
amount: charge_details.amount,
currency: charge_details.currency,
merchant_reference_id,
connector_account_reference_id:
MCA_ID_IDENTIFIER_FOR_STRIPE_IN_STRIPEBILLING_MCA_FEAATURE_METADATA
.to_string(),
connector_transaction_id,
error_code: charge_details.failure_code,
error_message: charge_details.failure_message,
processor_payment_method_token: charge_details.payment_method,
connector_customer_id: charge_details.customer,
transaction_created_at: Some(charge_details.created),
payment_method_sub_type: common_enums::PaymentMethodType::from(
charge_details.payment_method_details.card_details.funding,
),
payment_method_type: common_enums::PaymentMethod::from(
charge_details.payment_method_details.type_of_payment_method,
),
// Todo: Fetch Card issuer details. Generally in the other billing connector we are getting card_issuer using the card bin info. But stripe dosent provide any such details. We should find a way for stripe billing case
charge_id: Some(charge_details.charge_id.clone()),
// Need to populate these card info field
card_info: api_models::payments::AdditionalCardInfo {
card_network: Some(common_enums::CardNetwork::from(
charge_details.payment_method_details.card_details.network,
)),
card_isin: None,
card_issuer: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
last4: None,
card_extended_bin: None,
card_exp_month: None,
card_exp_year: None,
card_holder_name: None,
payment_checks: None,
authentication_data: None,
is_regulated: None,
signature_network: None,
},
},
),
..item.data
})
}
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl From<StripebillingChargeStatus> for enums::AttemptStatus {
fn from(status: StripebillingChargeStatus) -> Self {
match status {
StripebillingChargeStatus::Succeeded => Self::Charged,
StripebillingChargeStatus::Failed => Self::Failure,
}
}
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl From<StripebillingFundingTypes> for common_enums::PaymentMethodType {
fn from(funding: StripebillingFundingTypes) -> Self {
match funding {
StripebillingFundingTypes::Credit => Self::Credit,
StripebillingFundingTypes::Debit => Self::Debit,
}
}
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl From<StripebillingPaymentMethod> for common_enums::PaymentMethod {
fn from(method: StripebillingPaymentMethod) -> Self {
match method {
StripebillingPaymentMethod::Card => Self::Card,
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct StripebillingRecordBackResponse {
pub id: String,
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl
TryFrom<
ResponseRouterData<
recovery_router_flows::InvoiceRecordBack,
StripebillingRecordBackResponse,
recovery_request_types::InvoiceRecordBackRequest,
recovery_response_types::InvoiceRecordBackResponse,
>,
> for recovery_router_data_types::InvoiceRecordBackRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
recovery_router_flows::InvoiceRecordBack,
StripebillingRecordBackResponse,
recovery_request_types::InvoiceRecordBackRequest,
recovery_response_types::InvoiceRecordBackResponse,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(recovery_response_types::InvoiceRecordBackResponse {
merchant_reference_id: id_type::PaymentReferenceId::from_str(
item.response.id.as_str(),
)
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "invoice_id in the response",
})?,
}),
..item.data
})
}
}
impl From<StripebillingCardNetwork> for enums::CardNetwork {
fn from(item: StripebillingCardNetwork) -> Self {
match item {
StripebillingCardNetwork::Visa => Self::Visa,
StripebillingCardNetwork::Mastercard => Self::Mastercard,
StripebillingCardNetwork::AmericanExpress => Self::AmericanExpress,
StripebillingCardNetwork::JCB => Self::JCB,
StripebillingCardNetwork::DinersClub => Self::DinersClub,
StripebillingCardNetwork::Discover => Self::Discover,
StripebillingCardNetwork::CartesBancaires => Self::CartesBancaires,
StripebillingCardNetwork::UnionPay => Self::UnionPay,
StripebillingCardNetwork::Interac => Self::Interac,
StripebillingCardNetwork::RuPay => Self::RuPay,
StripebillingCardNetwork::Maestro => Self::Maestro,
StripebillingCardNetwork::Star => Self::Star,
StripebillingCardNetwork::Pulse => Self::Pulse,
StripebillingCardNetwork::Accel => Self::Accel,
StripebillingCardNetwork::Nyce => Self::Nyce,
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5158
}
|
large_file_3099940076275364781
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
</path>
<file>
use std::collections::HashMap;
use base64::Engine;
use cards::CardNumber;
use common_enums::{enums, Currency};
use common_types::payments::{ApplePayPaymentData, ApplePayPredecryptData};
use common_utils::{
ext_traits::ValueExt,
id_type,
pii::{Email, IpAddress, SecretSerdeValue},
request::Method,
types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{
ApplePayWalletData, BankRedirectData, GiftCardData, PaymentMethodData, WalletData,
},
router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{
CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsPreProcessingData, PaymentsSyncData,
ResponseId,
},
router_response_types::{
ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, RedirectForm,
RefundsResponseData,
},
types::{
ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData,
PaymentsPreProcessingRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, missing_field_err, to_connector_meta, BrowserInformationData, CardData,
PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
PaymentsPreProcessingRequestData, RouterData as RouterDataUtils,
},
};
const MAX_ID_LENGTH: usize = 36;
pub struct PaysafeRouterData<T> {
pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for PaysafeRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct PaysafeConnectorMetadataObject {
pub account_id: PaysafePaymentMethodDetails,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct PaysafePaymentMethodDetails {
pub apple_pay: Option<HashMap<Currency, ApplePayAccountDetails>>,
pub card: Option<HashMap<Currency, CardAccountId>>,
pub interac: Option<HashMap<Currency, RedirectAccountId>>,
pub pay_safe_card: Option<HashMap<Currency, RedirectAccountId>>,
pub skrill: Option<HashMap<Currency, RedirectAccountId>>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct CardAccountId {
no_three_ds: Option<Secret<String>>,
three_ds: Option<Secret<String>>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct ApplePayAccountDetails {
encrypt: Option<Secret<String>>,
decrypt: Option<Secret<String>>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct RedirectAccountId {
three_ds: Option<Secret<String>>,
}
impl TryFrom<&Option<SecretSerdeValue>> for PaysafeConnectorMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
Ok(metadata)
}
}
impl TryFrom<&ConnectorCustomerRouterData> for PaysafeCustomerDetails {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(customer_data: &ConnectorCustomerRouterData) -> Result<Self, Self::Error> {
let merchant_customer_id = match customer_data.customer_id.as_ref() {
Some(customer_id) if customer_id.get_string_repr().len() <= MAX_ID_LENGTH => {
Ok(customer_id.get_string_repr().to_string())
}
Some(customer_id) => Err(errors::ConnectorError::MaxFieldLengthViolated {
connector: "Paysafe".to_string(),
field_name: "customer_id".to_string(),
max_length: MAX_ID_LENGTH,
received_length: customer_id.get_string_repr().len(),
}),
None => Err(errors::ConnectorError::MissingRequiredField {
field_name: "customer_id",
}),
}?;
Ok(Self {
merchant_customer_id,
first_name: customer_data.get_optional_billing_first_name(),
last_name: customer_data.get_optional_billing_last_name(),
email: customer_data.get_optional_billing_email(),
phone: customer_data.get_optional_billing_phone_number(),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeCustomerDetails {
pub merchant_customer_id: String,
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub email: Option<Email>,
pub phone: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDs {
pub merchant_url: String,
pub device_channel: DeviceChannel,
pub message_category: ThreeDsMessageCategory,
pub authentication_purpose: ThreeDsAuthenticationPurpose,
pub requestor_challenge_preference: ThreeDsChallengePreference,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum DeviceChannel {
Browser,
Sdk,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ThreeDsMessageCategory {
Payment,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ThreeDsAuthenticationPurpose {
PaymentTransaction,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ThreeDsChallengePreference {
ChallengeMandated,
NoPreference,
NoChallengeRequested,
ChallengeRequested,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafePaymentHandleRequest {
pub merchant_ref_num: String,
pub amount: MinorUnit,
pub settle_with_auth: bool,
#[serde(flatten)]
pub payment_method: PaysafePaymentMethod,
pub currency_code: Currency,
pub payment_type: PaysafePaymentType,
pub transaction_type: TransactionType,
pub return_links: Vec<ReturnLink>,
pub account_id: Secret<String>,
pub three_ds: Option<ThreeDs>,
pub profile: Option<PaysafeProfile>,
pub billing_details: Option<PaysafeBillingDetails>,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeBillingDetails {
pub nick_name: Option<Secret<String>>,
pub street: Option<Secret<String>>,
pub street2: Option<Secret<String>>,
pub city: Option<String>,
pub state: Secret<String>,
pub zip: Secret<String>,
pub country: api_models::enums::CountryAlpha2,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeProfile {
pub first_name: Secret<String>,
pub last_name: Secret<String>,
pub email: Email,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum PaysafePaymentMethod {
ApplePay {
#[serde(rename = "applePay")]
apple_pay: Box<PaysafeApplepayPayment>,
},
Card {
card: PaysafeCard,
},
Interac {
#[serde(rename = "interacEtransfer")]
interac_etransfer: InteracBankRedirect,
},
PaysafeCard {
#[serde(rename = "paysafecard")]
pay_safe_card: PaysafeGiftCard,
},
Skrill {
skrill: SkrillWallet,
},
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplepayPayment {
pub label: Option<String>,
pub request_billing_address: Option<bool>,
#[serde(rename = "applePayPaymentToken")]
pub apple_pay_payment_token: PaysafeApplePayPaymentToken,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayPaymentToken {
pub token: PaysafeApplePayToken,
#[serde(skip_serializing_if = "Option::is_none")]
pub billing_contact: Option<PaysafeApplePayBillingContact>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayToken {
pub payment_data: PaysafeApplePayPaymentData,
pub payment_method: PaysafeApplePayPaymentMethod,
pub transaction_identifier: String,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum PaysafeApplePayPaymentData {
Encrypted(PaysafeApplePayEncryptedData),
Decrypted(PaysafeApplePayDecryptedDataWrapper),
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayEncryptedData {
pub data: Secret<String>,
pub signature: Secret<String>,
pub header: PaysafeApplePayHeader,
pub version: Secret<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayDecryptedDataWrapper {
pub decrypted_data: PaysafeApplePayDecryptedData,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayDecryptedData {
pub application_primary_account_number: CardNumber,
pub application_expiration_date: Secret<String>,
pub currency_code: String,
pub transaction_amount: Option<MinorUnit>,
pub cardholder_name: Option<Secret<String>>,
pub device_manufacturer_identifier: Option<String>,
pub payment_data_type: Option<String>,
pub payment_data: PaysafeApplePayDecryptedPaymentData,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayDecryptedPaymentData {
pub online_payment_cryptogram: Secret<String>,
pub eci_indicator: Option<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayHeader {
pub public_key_hash: String,
pub ephemeral_public_key: String,
pub transaction_id: String,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayPaymentMethod {
pub display_name: Secret<String>,
pub network: Secret<String>,
#[serde(rename = "type")]
pub method_type: Secret<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayBillingContact {
pub address_lines: Vec<Option<Secret<String>>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub administrative_area: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub country: Option<String>,
pub country_code: api_models::enums::CountryAlpha2,
#[serde(skip_serializing_if = "Option::is_none")]
pub family_name: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub given_name: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub locality: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phonetic_family_name: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phonetic_given_name: Option<Secret<String>>,
pub postal_code: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sub_administrative_area: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sub_locality: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SkrillWallet {
pub consumer_id: Email,
pub country_code: Option<api_models::enums::CountryAlpha2>,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct InteracBankRedirect {
pub consumer_id: Email,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeGiftCard {
pub consumer_id: id_type::CustomerId,
}
#[derive(Debug, Serialize)]
pub struct ReturnLink {
pub rel: LinkType,
pub href: String,
pub method: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum LinkType {
OnCompleted,
OnFailed,
OnCancelled,
Default,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaysafePaymentType {
// For Apple Pay and Google Pay, paymentType is 'CARD' as per Paysafe docs and is not reserved for card payments only
Card,
Skrill,
InteracEtransfer,
Paysafecard,
}
#[derive(Debug, Serialize)]
pub enum TransactionType {
#[serde(rename = "PAYMENT")]
Payment,
}
impl PaysafePaymentMethodDetails {
pub fn get_applepay_encrypt_account_id(
&self,
currency: Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
self.apple_pay
.as_ref()
.and_then(|apple_pay| apple_pay.get(¤cy))
.and_then(|flow| flow.encrypt.clone())
.ok_or_else(|| errors::ConnectorError::InvalidConnectorConfig {
config: "Missing ApplePay encrypt account_id",
})
}
pub fn get_applepay_decrypt_account_id(
&self,
currency: Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
self.apple_pay
.as_ref()
.and_then(|apple_pay| apple_pay.get(¤cy))
.and_then(|flow| flow.decrypt.clone())
.ok_or_else(|| errors::ConnectorError::InvalidConnectorConfig {
config: "Missing ApplePay decrypt account_id",
})
}
pub fn get_no_three_ds_account_id(
&self,
currency: Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
self.card
.as_ref()
.and_then(|cards| cards.get(¤cy))
.and_then(|card| card.no_three_ds.clone())
.ok_or(errors::ConnectorError::InvalidConnectorConfig {
config: "Missing no_3ds account_id",
})
}
pub fn get_three_ds_account_id(
&self,
currency: Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
self.card
.as_ref()
.and_then(|cards| cards.get(¤cy))
.and_then(|card| card.three_ds.clone())
.ok_or(errors::ConnectorError::InvalidConnectorConfig {
config: "Missing 3ds account_id",
})
}
pub fn get_skrill_account_id(
&self,
currency: Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
self.skrill
.as_ref()
.and_then(|wallets| wallets.get(¤cy))
.and_then(|skrill| skrill.three_ds.clone())
.ok_or(errors::ConnectorError::InvalidConnectorConfig {
config: "Missing skrill account_id",
})
}
pub fn get_interac_account_id(
&self,
currency: Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
self.interac
.as_ref()
.and_then(|redirects| redirects.get(¤cy))
.and_then(|interac| interac.three_ds.clone())
.ok_or(errors::ConnectorError::InvalidConnectorConfig {
config: "Missing interac account_id",
})
}
pub fn get_paysafe_gift_card_account_id(
&self,
currency: Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
self.pay_safe_card
.as_ref()
.and_then(|gift_cards| gift_cards.get(¤cy))
.and_then(|pay_safe_card| pay_safe_card.three_ds.clone())
.ok_or(errors::ConnectorError::InvalidConnectorConfig {
config: "Missing paysafe gift card account_id",
})
}
}
fn create_paysafe_billing_details<T>(
is_customer_initiated_mandate_payment: bool,
item: &T,
) -> Result<Option<PaysafeBillingDetails>, error_stack::Report<errors::ConnectorError>>
where
T: RouterDataUtils,
{
// For customer-initiated mandate payments, zip, country and state fields are mandatory
if is_customer_initiated_mandate_payment {
Ok(Some(PaysafeBillingDetails {
nick_name: item.get_optional_billing_first_name(),
street: item.get_optional_billing_line1(),
street2: item.get_optional_billing_line2(),
city: item.get_optional_billing_city(),
zip: item.get_billing_zip()?,
country: item.get_billing_country()?,
state: item.get_billing_state_code()?,
}))
}
// For normal payments, only send billing details if billing mandatory fields are available
else if let (Some(zip), Some(country), Some(state)) = (
item.get_optional_billing_zip(),
item.get_optional_billing_country(),
item.get_optional_billing_state_code(),
) {
Ok(Some(PaysafeBillingDetails {
nick_name: item.get_optional_billing_first_name(),
street: item.get_optional_billing_line1(),
street2: item.get_optional_billing_line2(),
city: item.get_optional_billing_city(),
zip,
country,
state,
}))
} else {
Ok(None)
}
}
impl TryFrom<&PaysafeRouterData<&PaymentsPreProcessingRouterData>> for PaysafePaymentHandleRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaysafeRouterData<&PaymentsPreProcessingRouterData>,
) -> Result<Self, Self::Error> {
let metadata: PaysafeConnectorMetadataObject =
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
let amount = item.amount;
let currency_code = item.router_data.request.get_currency()?;
let redirect_url = item.router_data.request.get_router_return_url()?;
let return_links = vec![
ReturnLink {
rel: LinkType::Default,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
ReturnLink {
rel: LinkType::OnCompleted,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
ReturnLink {
rel: LinkType::OnFailed,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
ReturnLink {
rel: LinkType::OnCancelled,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
];
let settle_with_auth = matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
);
let transaction_type = TransactionType::Payment;
let billing_details = create_paysafe_billing_details(
item.router_data
.request
.is_customer_initiated_mandate_payment(),
item.router_data,
)?;
let (payment_method, payment_type, account_id) =
match item.router_data.request.get_payment_method_data()?.clone() {
PaymentMethodData::Card(req_card) => {
let card = PaysafeCard {
card_num: req_card.card_number.clone(),
card_expiry: PaysafeCardExpiry {
month: req_card.card_exp_month.clone(),
year: req_card.get_expiry_year_4_digit(),
},
cvv: if req_card.card_cvc.clone().expose().is_empty() {
None
} else {
Some(req_card.card_cvc.clone())
},
holder_name: item.router_data.get_optional_billing_full_name(),
};
let payment_method = PaysafePaymentMethod::Card { card: card.clone() };
let payment_type = PaysafePaymentType::Card;
let account_id = metadata
.account_id
.get_no_three_ds_account_id(currency_code)?;
(payment_method, payment_type, account_id)
}
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::ApplePay(applepay_data) => {
let is_encrypted = matches!(
applepay_data.payment_data,
ApplePayPaymentData::Encrypted(_)
);
let account_id = if is_encrypted {
metadata
.account_id
.get_applepay_encrypt_account_id(currency_code)?
} else {
metadata
.account_id
.get_applepay_decrypt_account_id(currency_code)?
};
let applepay_payment =
PaysafeApplepayPayment::try_from((&applepay_data, item))?;
let payment_method = PaysafePaymentMethod::ApplePay {
apple_pay: Box::new(applepay_payment),
};
let payment_type = PaysafePaymentType::Card;
(payment_method, payment_type, account_id)
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePay(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::PaypalRedirect(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::WeChatPayQr(_)
| WalletData::RevolutPay(_)
| WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paysafe"),
))?,
},
_ => Err(errors::ConnectorError::NotImplemented(
"Payment Method".to_string(),
))?,
};
Ok(Self {
merchant_ref_num: item.router_data.connector_request_reference_id.clone(),
amount,
settle_with_auth,
payment_method,
currency_code,
payment_type,
transaction_type,
return_links,
account_id,
three_ds: None,
profile: None,
billing_details,
})
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaysafeUsage {
SingleUse,
MultiUse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafePaymentHandleResponse {
pub id: String,
pub merchant_ref_num: String,
pub payment_handle_token: Secret<String>,
pub usage: Option<PaysafeUsage>,
pub status: PaysafePaymentHandleStatus,
pub links: Option<Vec<PaymentLink>>,
pub error: Option<Error>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentLink {
pub rel: String,
pub href: String,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaysafePaymentHandleStatus {
Initiated,
Payable,
#[default]
Processing,
Failed,
Expired,
Completed,
Error,
}
impl TryFrom<PaysafePaymentHandleStatus> for common_enums::AttemptStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: PaysafePaymentHandleStatus) -> Result<Self, Self::Error> {
match item {
PaysafePaymentHandleStatus::Completed => Ok(Self::Authorized),
PaysafePaymentHandleStatus::Failed
| PaysafePaymentHandleStatus::Expired
| PaysafePaymentHandleStatus::Error => Ok(Self::Failure),
// We get an `Initiated` status, with a redirection link from the connector, which indicates that further action is required by the customer,
PaysafePaymentHandleStatus::Initiated => Ok(Self::AuthenticationPending),
PaysafePaymentHandleStatus::Payable | PaysafePaymentHandleStatus::Processing => {
Ok(Self::Pending)
}
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaysafeMeta {
pub payment_handle_token: Secret<String>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
PaysafePaymentHandleResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
PaysafePaymentHandleResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::try_from(item.response.status)?,
preprocessing_id: Some(
item.response
.payment_handle_token
.to_owned()
.peek()
.to_string(),
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<F>
TryFrom<
ResponseRouterData<F, PaysafePaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
PaysafePaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let mandate_reference = item
.response
.payment_handle_token
.map(|payment_handle_token| payment_handle_token.expose())
.map(|mandate_id| MandateReference {
connector_mandate_id: Some(mandate_id),
payment_method_id: None,
mandate_metadata: Some(Secret::new(serde_json::json!(PaysafeMandateMetadata {
initial_transaction_id: item.response.id.clone()
}))),
connector_mandate_request_reference_id: None,
});
Ok(Self {
status: get_paysafe_payment_status(
item.response.status,
item.data.request.capture_method,
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
PaysafePaymentHandleResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
PaysafePaymentHandleResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.links
.as_ref()
.and_then(|links| links.first())
.map(|link| RedirectForm::Form {
endpoint: link.href.clone(),
method: Method::Get,
form_fields: Default::default(),
});
let connector_metadata = serde_json::json!(PaysafeMeta {
payment_handle_token: item.response.payment_handle_token.clone(),
});
Ok(Self {
status: common_enums::AttemptStatus::try_from(item.response.status)?,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(connector_metadata),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafePaymentsRequest {
pub merchant_ref_num: String,
pub amount: MinorUnit,
pub settle_with_auth: bool,
pub payment_handle_token: Secret<String>,
pub currency_code: Currency,
pub customer_ip: Option<Secret<String, IpAddress>>,
pub stored_credential: Option<PaysafeStoredCredential>,
#[serde(skip_serializing_if = "Option::is_none")]
pub account_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeStoredCredential {
#[serde(rename = "type")]
stored_credential_type: PaysafeStoredCredentialType,
occurrence: MandateOccurence,
#[serde(skip_serializing_if = "Option::is_none")]
initial_transaction_id: Option<String>,
}
impl PaysafeStoredCredential {
fn new_customer_initiated_transaction() -> Self {
Self {
stored_credential_type: PaysafeStoredCredentialType::Adhoc,
occurrence: MandateOccurence::Initial,
initial_transaction_id: None,
}
}
fn new_merchant_initiated_transaction(initial_transaction_id: String) -> Self {
Self {
stored_credential_type: PaysafeStoredCredentialType::Topup,
occurrence: MandateOccurence::Subsequent,
initial_transaction_id: Some(initial_transaction_id),
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum MandateOccurence {
Initial,
Subsequent,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaysafeStoredCredentialType {
Adhoc,
Topup,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeCard {
pub card_num: CardNumber,
pub card_expiry: PaysafeCardExpiry,
#[serde(skip_serializing_if = "Option::is_none")]
pub cvv: Option<Secret<String>>,
pub holder_name: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PaysafeCardExpiry {
pub month: Secret<String>,
pub year: Secret<String>,
}
#[derive(Debug, Deserialize)]
struct DecryptedApplePayTokenData {
data: Secret<String>,
signature: Secret<String>,
header: DecryptedApplePayTokenHeader,
version: Secret<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct DecryptedApplePayTokenHeader {
public_key_hash: String,
ephemeral_public_key: String,
transaction_id: String,
}
fn get_apple_pay_decrypt_data(
apple_pay_predecrypt_data: &ApplePayPredecryptData,
item: &PaysafeRouterData<&PaymentsPreProcessingRouterData>,
) -> Result<PaysafeApplePayDecryptedData, error_stack::Report<errors::ConnectorError>> {
Ok(PaysafeApplePayDecryptedData {
application_primary_account_number: apple_pay_predecrypt_data
.application_primary_account_number
.clone(),
application_expiration_date: apple_pay_predecrypt_data
.get_expiry_date_as_yymm()
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "application_expiration_date",
})?,
currency_code: Currency::iso_4217(
item.router_data
.request
.currency
.ok_or_else(missing_field_err("currency"))?,
)
.to_string(),
transaction_amount: Some(item.amount),
cardholder_name: None,
device_manufacturer_identifier: Some("Apple".to_string()),
payment_data_type: Some("3DSecure".to_string()),
payment_data: PaysafeApplePayDecryptedPaymentData {
online_payment_cryptogram: apple_pay_predecrypt_data
.payment_data
.online_payment_cryptogram
.clone(),
eci_indicator: apple_pay_predecrypt_data.payment_data.eci_indicator.clone(),
},
})
}
impl
TryFrom<(
&ApplePayWalletData,
&PaysafeRouterData<&PaymentsPreProcessingRouterData>,
)> for PaysafeApplepayPayment
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(wallet_data, item): (
&ApplePayWalletData,
&PaysafeRouterData<&PaymentsPreProcessingRouterData>,
),
) -> Result<Self, Self::Error> {
let apple_pay_payment_token = PaysafeApplePayPaymentToken {
token: PaysafeApplePayToken {
payment_data: if let Ok(PaymentMethodToken::ApplePayDecrypt(ref token)) =
item.router_data.get_payment_method_token()
{
PaysafeApplePayPaymentData::Decrypted(PaysafeApplePayDecryptedDataWrapper {
decrypted_data: get_apple_pay_decrypt_data(token, item)?,
})
} else {
match &wallet_data.payment_data {
ApplePayPaymentData::Decrypted(applepay_predecrypt_data) => {
PaysafeApplePayPaymentData::Decrypted(
PaysafeApplePayDecryptedDataWrapper {
decrypted_data: get_apple_pay_decrypt_data(
applepay_predecrypt_data,
item,
)?,
},
)
}
ApplePayPaymentData::Encrypted(applepay_encrypt_data) => {
let decoded_data = base64::prelude::BASE64_STANDARD
.decode(applepay_encrypt_data)
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "apple_pay_encrypted_data",
})?;
let apple_pay_token: DecryptedApplePayTokenData =
serde_json::from_slice(&decoded_data).change_context(
errors::ConnectorError::InvalidDataFormat {
field_name: "apple_pay_token_json",
},
)?;
PaysafeApplePayPaymentData::Encrypted(PaysafeApplePayEncryptedData {
data: apple_pay_token.data,
signature: apple_pay_token.signature,
header: PaysafeApplePayHeader {
public_key_hash: apple_pay_token.header.public_key_hash,
ephemeral_public_key: apple_pay_token
.header
.ephemeral_public_key,
transaction_id: apple_pay_token.header.transaction_id,
},
version: apple_pay_token.version,
})
}
}
},
payment_method: PaysafeApplePayPaymentMethod {
display_name: Secret::new(wallet_data.payment_method.display_name.clone()),
network: Secret::new(wallet_data.payment_method.network.clone()),
method_type: Secret::new(wallet_data.payment_method.pm_type.clone()),
},
transaction_identifier: wallet_data.transaction_identifier.clone(),
},
billing_contact: Some(PaysafeApplePayBillingContact {
address_lines: vec![
item.router_data.get_optional_billing_line1(),
item.router_data.get_optional_billing_line2(),
],
postal_code: item.router_data.get_billing_zip()?,
country_code: item.router_data.get_billing_country()?,
country: None,
family_name: None,
given_name: None,
locality: None,
phonetic_family_name: None,
phonetic_given_name: None,
sub_administrative_area: None,
administrative_area: None,
sub_locality: None,
}),
};
Ok(Self {
label: None,
request_billing_address: Some(false),
apple_pay_payment_token,
})
}
}
#[derive(Debug, Clone)]
pub struct PaysafeMandateData {
stored_credential: Option<PaysafeStoredCredential>,
payment_token: Secret<String>,
}
impl TryFrom<&PaymentsAuthorizeRouterData> for PaysafeMandateData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
match (
item.request.is_cit_mandate_payment(),
item.request.get_connector_mandate_data(),
) {
(true, _) => Ok(Self {
stored_credential: Some(
PaysafeStoredCredential::new_customer_initiated_transaction(),
),
payment_token: item.get_preprocessing_id()?.into(),
}),
(false, Some(mandate_data)) => {
let mandate_id = mandate_data
.get_connector_mandate_id()
.ok_or(errors::ConnectorError::MissingConnectorMandateID)?;
let mandate_metadata: PaysafeMandateMetadata = mandate_data
.get_mandate_metadata()
.ok_or(errors::ConnectorError::MissingConnectorMandateMetadata)?
.clone()
.parse_value("PaysafeMandateMetadata")
.change_context(errors::ConnectorError::ParsingFailed)?;
Ok(Self {
stored_credential: Some(
PaysafeStoredCredential::new_merchant_initiated_transaction(
mandate_metadata.initial_transaction_id,
),
),
payment_token: mandate_id.into(),
})
}
_ => Ok(Self {
stored_credential: None,
payment_token: item.get_preprocessing_id()?.into(),
}),
}
}
}
impl TryFrom<&PaysafeRouterData<&PaymentsAuthorizeRouterData>> for PaysafePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaysafeRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let amount = item.amount;
let customer_ip = Some(
item.router_data
.request
.get_browser_info()?
.get_ip_address()?,
);
let metadata: PaysafeConnectorMetadataObject =
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
let account_id = match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment => {
if item.router_data.is_three_ds() {
Some(
metadata
.account_id
.get_three_ds_account_id(item.router_data.request.currency)?,
)
} else {
Some(
metadata
.account_id
.get_no_three_ds_account_id(item.router_data.request.currency)?,
)
}
}
_ => None,
};
let mandate_data = PaysafeMandateData::try_from(item.router_data)?;
Ok(Self {
merchant_ref_num: item.router_data.connector_request_reference_id.clone(),
payment_handle_token: mandate_data.payment_token,
amount,
settle_with_auth: item.router_data.request.is_auto_capture()?,
currency_code: item.router_data.request.currency,
customer_ip,
stored_credential: mandate_data.stored_credential,
account_id,
})
}
}
impl TryFrom<&PaysafeRouterData<&PaymentsAuthorizeRouterData>> for PaysafePaymentHandleRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaysafeRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if item
.router_data
.request
.is_customer_initiated_mandate_payment()
{
Err(errors::ConnectorError::NotSupported {
message: format!(
"Mandate Payment with {} {}",
item.router_data.payment_method, item.router_data.auth_type
),
connector: "Paysafe",
})?
};
let metadata: PaysafeConnectorMetadataObject =
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
let redirect_url_success = item.router_data.request.get_complete_authorize_url()?;
let redirect_url = item.router_data.request.get_router_return_url()?;
let return_links = vec![
ReturnLink {
rel: LinkType::Default,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
ReturnLink {
rel: LinkType::OnCompleted,
href: redirect_url_success.clone(),
method: Method::Get.to_string(),
},
ReturnLink {
rel: LinkType::OnFailed,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
ReturnLink {
rel: LinkType::OnCancelled,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
];
let amount = item.amount;
let currency_code = item.router_data.request.currency;
let settle_with_auth = matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
);
let transaction_type = TransactionType::Payment;
let (payment_method, payment_type, account_id, three_ds, profile) =
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = PaysafeCard {
card_num: req_card.card_number.clone(),
card_expiry: PaysafeCardExpiry {
month: req_card.card_exp_month.clone(),
year: req_card.get_expiry_year_4_digit(),
},
cvv: if req_card.card_cvc.clone().expose().is_empty() {
None
} else {
Some(req_card.card_cvc.clone())
},
holder_name: item.router_data.get_optional_billing_full_name(),
};
let payment_method = PaysafePaymentMethod::Card { card: card.clone() };
let payment_type = PaysafePaymentType::Card;
let headers = item.router_data.header_payload.clone();
let platform = headers.as_ref().and_then(|h| h.x_client_platform.clone());
let device_channel = match platform {
Some(common_enums::ClientPlatform::Web)
| Some(common_enums::ClientPlatform::Unknown)
| None => DeviceChannel::Browser,
Some(common_enums::ClientPlatform::Ios)
| Some(common_enums::ClientPlatform::Android) => DeviceChannel::Sdk,
};
let account_id = metadata.account_id.get_three_ds_account_id(currency_code)?;
let three_ds = Some(ThreeDs {
merchant_url: item.router_data.request.get_router_return_url()?,
device_channel,
message_category: ThreeDsMessageCategory::Payment,
authentication_purpose: ThreeDsAuthenticationPurpose::PaymentTransaction,
requestor_challenge_preference:
ThreeDsChallengePreference::ChallengeMandated,
});
(payment_method, payment_type, account_id, three_ds, None)
}
PaymentMethodData::Wallet(WalletData::Skrill(_)) => {
let payment_method = PaysafePaymentMethod::Skrill {
skrill: SkrillWallet {
consumer_id: item.router_data.get_billing_email()?,
country_code: item.router_data.get_optional_billing_country(),
},
};
let payment_type = PaysafePaymentType::Skrill;
let account_id = metadata.account_id.get_skrill_account_id(currency_code)?;
(payment_method, payment_type, account_id, None, None)
}
PaymentMethodData::Wallet(_) => Err(errors::ConnectorError::NotImplemented(
"Payment Method".to_string(),
))?,
PaymentMethodData::BankRedirect(BankRedirectData::Interac { .. }) => {
let payment_method = PaysafePaymentMethod::Interac {
interac_etransfer: InteracBankRedirect {
consumer_id: item.router_data.get_billing_email()?,
},
};
let payment_type = PaysafePaymentType::InteracEtransfer;
let account_id = metadata.account_id.get_interac_account_id(currency_code)?;
let profile = Some(PaysafeProfile {
first_name: item.router_data.get_billing_first_name()?,
last_name: item.router_data.get_billing_last_name()?,
email: item.router_data.get_billing_email()?,
});
(payment_method, payment_type, account_id, None, profile)
}
PaymentMethodData::BankRedirect(_) => Err(errors::ConnectorError::NotImplemented(
"Payment Method".to_string(),
))?,
PaymentMethodData::GiftCard(gift_card_data) => match gift_card_data.as_ref() {
GiftCardData::PaySafeCard {} => {
let payment_method = PaysafePaymentMethod::PaysafeCard {
pay_safe_card: PaysafeGiftCard {
consumer_id: item.router_data.get_customer_id()?,
},
};
let payment_type = PaysafePaymentType::Paysafecard;
let account_id = metadata
.account_id
.get_paysafe_gift_card_account_id(currency_code)?;
(payment_method, payment_type, account_id, None, None)
}
_ => Err(errors::ConnectorError::NotImplemented(
"Payment Method".to_string(),
))?,
},
_ => Err(errors::ConnectorError::NotImplemented(
"Payment Method".to_string(),
))?,
};
let billing_details = create_paysafe_billing_details(
item.router_data
.request
.is_customer_initiated_mandate_payment(),
item.router_data,
)?;
Ok(Self {
merchant_ref_num: item.router_data.connector_request_reference_id.clone(),
amount,
settle_with_auth,
payment_method,
currency_code,
payment_type,
transaction_type,
return_links,
account_id,
three_ds,
profile,
billing_details,
})
}
}
impl TryFrom<&PaysafeRouterData<&PaymentsCompleteAuthorizeRouterData>> for PaysafePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaysafeRouterData<&PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let paysafe_meta: PaysafeMeta = to_connector_meta(
item.router_data.request.connector_meta.clone(),
)
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "connector_metadata",
})?;
let payment_handle_token = paysafe_meta.payment_handle_token;
let amount = item.amount;
let customer_ip = Some(
item.router_data
.request
.get_browser_info()?
.get_ip_address()?,
);
Ok(Self {
merchant_ref_num: item.router_data.connector_request_reference_id.clone(),
payment_handle_token,
amount,
settle_with_auth: item.router_data.request.is_auto_capture()?,
currency_code: item.router_data.request.currency,
customer_ip,
stored_credential: None,
account_id: None,
})
}
}
impl<F>
TryFrom<
ResponseRouterData<F, PaysafePaymentsResponse, CompleteAuthorizeData, PaymentsResponseData>,
> for RouterData<F, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
PaysafePaymentsResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: get_paysafe_payment_status(
item.response.status,
item.data.request.capture_method,
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
pub struct PaysafeAuthType {
pub(super) username: Secret<String>,
pub(super) password: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PaysafeAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
username: api_key.to_owned(),
password: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// Paysafe Payment Status
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaysafePaymentStatus {
Received,
Completed,
Held,
Failed,
#[default]
Pending,
Cancelled,
Processing,
}
pub fn get_paysafe_payment_status(
status: PaysafePaymentStatus,
capture_method: Option<common_enums::CaptureMethod>,
) -> common_enums::AttemptStatus {
match status {
PaysafePaymentStatus::Completed => match capture_method {
Some(common_enums::CaptureMethod::Manual) => common_enums::AttemptStatus::Authorized,
Some(common_enums::CaptureMethod::Automatic) | None => {
common_enums::AttemptStatus::Charged
}
Some(common_enums::CaptureMethod::SequentialAutomatic)
| Some(common_enums::CaptureMethod::ManualMultiple)
| Some(common_enums::CaptureMethod::Scheduled) => {
common_enums::AttemptStatus::Unresolved
}
},
PaysafePaymentStatus::Failed => common_enums::AttemptStatus::Failure,
PaysafePaymentStatus::Pending
| PaysafePaymentStatus::Processing
| PaysafePaymentStatus::Received
| PaysafePaymentStatus::Held => common_enums::AttemptStatus::Pending,
PaysafePaymentStatus::Cancelled => common_enums::AttemptStatus::Voided,
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PaysafeSyncResponse {
Payments(PaysafePaymentsSyncResponse),
PaymentHandles(PaysafePaymentHandlesSyncResponse),
}
// Paysafe Payments Response Structure
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafePaymentsSyncResponse {
pub payments: Vec<PaysafePaymentsResponse>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafePaymentHandlesSyncResponse {
pub payment_handles: Vec<PaysafePaymentHandleResponse>,
}
// Paysafe Payments Response Structure
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafePaymentsResponse {
pub id: String,
pub payment_handle_token: Option<Secret<String>>,
pub merchant_ref_num: Option<String>,
pub status: PaysafePaymentStatus,
pub error: Option<Error>,
}
// Paysafe Mandate Metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct PaysafeMandateMetadata {
pub initial_transaction_id: String,
}
// Paysafe Customer Response Structure
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeCustomerResponse {
pub id: String,
pub status: Option<String>,
pub merchant_customer_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeSettlementResponse {
pub merchant_ref_num: Option<String>,
pub id: String,
pub status: PaysafeSettlementStatus,
}
impl<F, T> TryFrom<ResponseRouterData<F, PaysafeCustomerResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaysafeCustomerResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(item.response.id),
)),
..item.data
})
}
}
impl<F> TryFrom<ResponseRouterData<F, PaysafeSyncResponse, PaymentsSyncData, PaymentsResponseData>>
for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaysafeSyncResponse, PaymentsSyncData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = match &item.response {
PaysafeSyncResponse::Payments(sync_response) => {
let payment_response = sync_response
.payments
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
get_paysafe_payment_status(
payment_response.status,
item.data.request.capture_method,
)
}
PaysafeSyncResponse::PaymentHandles(sync_response) => {
let payment_handle_response = sync_response
.payment_handles
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
common_enums::AttemptStatus::try_from(payment_handle_response.status)?
}
};
let response = if utils::is_payment_failure(status) {
let (code, message, reason, connector_transaction_id) = match &item.response {
PaysafeSyncResponse::Payments(sync_response) => {
let payment_response = sync_response
.payments
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
match &payment_response.error {
Some(err) => (
err.code.clone(),
err.message.clone(),
err.details
.as_ref()
.and_then(|d| d.first().cloned())
.or_else(|| Some(err.message.clone())),
payment_response.id.clone(),
),
None => (
consts::NO_ERROR_CODE.to_string(),
consts::NO_ERROR_MESSAGE.to_string(),
None,
payment_response.id.clone(),
),
}
}
PaysafeSyncResponse::PaymentHandles(sync_response) => {
let payment_handle_response = sync_response
.payment_handles
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
match &payment_handle_response.error {
Some(err) => (
err.code.clone(),
err.message.clone(),
err.details
.as_ref()
.and_then(|d| d.first().cloned())
.or_else(|| Some(err.message.clone())),
payment_handle_response.id.clone(),
),
None => (
consts::NO_ERROR_CODE.to_string(),
consts::NO_ERROR_MESSAGE.to_string(),
None,
payment_handle_response.id.clone(),
),
}
}
};
Err(hyperswitch_domain_models::router_data::ErrorResponse {
code,
message,
reason,
attempt_status: None,
connector_transaction_id: Some(connector_transaction_id),
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeCaptureRequest {
pub merchant_ref_num: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub amount: Option<MinorUnit>,
}
impl TryFrom<&PaysafeRouterData<&PaymentsCaptureRouterData>> for PaysafeCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaysafeRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let amount = Some(item.amount);
Ok(Self {
merchant_ref_num: item.router_data.connector_request_reference_id.clone(),
amount,
})
}
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaysafeSettlementStatus {
Received,
Initiated,
Completed,
Expired,
Failed,
#[default]
Pending,
Cancelled,
}
impl From<PaysafeSettlementStatus> for common_enums::AttemptStatus {
fn from(item: PaysafeSettlementStatus) -> Self {
match item {
PaysafeSettlementStatus::Completed
| PaysafeSettlementStatus::Pending
| PaysafeSettlementStatus::Received => Self::Charged,
PaysafeSettlementStatus::Failed | PaysafeSettlementStatus::Expired => Self::Failure,
PaysafeSettlementStatus::Cancelled => Self::Voided,
PaysafeSettlementStatus::Initiated => Self::Pending,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, PaysafeSettlementResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaysafeSettlementResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<&PaysafeRouterData<&PaymentsCancelRouterData>> for PaysafeCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaysafeRouterData<&PaymentsCancelRouterData>) -> Result<Self, Self::Error> {
let amount = Some(item.amount);
Ok(Self {
merchant_ref_num: item.router_data.connector_request_reference_id.clone(),
amount,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct VoidResponse {
pub merchant_ref_num: Option<String>,
pub id: String,
pub status: PaysafeVoidStatus,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaysafeVoidStatus {
Received,
Completed,
Held,
Failed,
#[default]
Pending,
Cancelled,
}
impl From<PaysafeVoidStatus> for common_enums::AttemptStatus {
fn from(item: PaysafeVoidStatus) -> Self {
match item {
PaysafeVoidStatus::Completed
| PaysafeVoidStatus::Pending
| PaysafeVoidStatus::Received => Self::Voided,
PaysafeVoidStatus::Failed | PaysafeVoidStatus::Held => Self::Failure,
PaysafeVoidStatus::Cancelled => Self::Voided,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, VoidResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, VoidResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeRefundRequest {
pub merchant_ref_num: String,
pub amount: MinorUnit,
}
impl<F> TryFrom<&PaysafeRouterData<&RefundsRouterData<F>>> for PaysafeRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaysafeRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let amount = item.amount;
Ok(Self {
merchant_ref_num: item.router_data.request.refund_id.clone(),
amount,
})
}
}
// Type definition for Refund Response
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Received,
Initiated,
Completed,
Expired,
Failed,
#[default]
Pending,
Cancelled,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Received | RefundStatus::Completed => Self::Success,
RefundStatus::Failed | RefundStatus::Cancelled | RefundStatus::Expired => Self::Failure,
RefundStatus::Pending | RefundStatus::Initiated => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaysafeErrorResponse {
pub error: Error,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Error {
pub code: String,
pub message: String,
pub details: Option<Vec<String>>,
#[serde(rename = "fieldErrors")]
pub field_errors: Option<Vec<FieldError>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldError {
pub field: Option<String>,
pub error: String,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 14096
}
|
large_file_-1894719119556957550
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
</path>
<file>
use common_enums::{enums, AttemptStatus, BankNames};
use common_utils::{
errors::ParsingError,
pii::{Email, IpAddress},
request::Method,
types::{FloatMajorUnit, MinorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankRedirectData, PayLaterData, PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{self},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, CardData as _, PaymentsAuthorizeRequestData, RouterData as _,
},
};
#[derive(Debug, Serialize)]
pub struct MultisafepayRouterData<T> {
amount: MinorUnit,
router_data: T,
}
impl<T> From<(MinorUnit, T)> for MultisafepayRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Type {
Direct,
Redirect,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Gateway {
Amex,
CreditCard,
Discover,
Maestro,
MasterCard,
Visa,
Klarna,
Googlepay,
Paypal,
Ideal,
Giropay,
Trustly,
Alipay,
#[serde(rename = "WECHAT")]
WeChatPay,
Eps,
MbWay,
#[serde(rename = "DIRECTBANK")]
Sofort,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Coupons {
pub allow: Option<Vec<Secret<String>>>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Mistercash {
pub mobile_pay_button_position: Option<String>,
pub disable_mobile_pay_button: Option<String>,
pub qr_only: Option<String>,
pub qr_size: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub struct Gateways {
pub mistercash: Option<Mistercash>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Settings {
pub coupons: Option<Coupons>,
pub gateways: Option<Gateways>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct PaymentOptions {
pub notification_url: Option<String>,
pub notification_method: Option<String>,
pub redirect_url: String,
pub cancel_url: String,
pub close_window: Option<bool>,
pub settings: Option<Settings>,
pub template_id: Option<String>,
pub allowed_countries: Option<Vec<String>>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Browser {
pub javascript_enabled: Option<bool>,
pub java_enabled: Option<bool>,
pub cookies_enabled: Option<bool>,
pub language: Option<String>,
pub screen_color_depth: Option<i32>,
pub screen_height: Option<i32>,
pub screen_width: Option<i32>,
pub time_zone: Option<i32>,
pub user_agent: Option<String>,
pub platform: Option<String>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Customer {
pub browser: Option<Browser>,
pub locale: Option<String>,
pub ip_address: Option<Secret<String, IpAddress>>,
pub forward_ip: Option<Secret<String, IpAddress>>,
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub gender: Option<Secret<String>>,
pub birthday: Option<Secret<String>>,
pub address1: Option<Secret<String>>,
pub address2: Option<Secret<String>>,
pub house_number: Option<Secret<String>>,
pub zip_code: Option<Secret<String>>,
pub city: Option<String>,
pub state: Option<String>,
pub country: Option<String>,
pub phone: Option<Secret<String>>,
pub email: Option<Email>,
pub user_agent: Option<String>,
pub referrer: Option<String>,
pub reference: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct CardInfo {
pub card_number: Option<cards::CardNumber>,
pub card_holder_name: Option<Secret<String>>,
pub card_expiry_date: Option<Secret<i32>>,
pub card_cvc: Option<Secret<String>>,
pub flexible_3d: Option<bool>,
pub moto: Option<bool>,
pub term_url: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct GpayInfo {
pub payment_token: Option<Secret<String>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct PayLaterInfo {
pub email: Option<Email>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum GatewayInfo {
Card(CardInfo),
Wallet(WalletInfo),
PayLater(PayLaterInfo),
BankRedirect(BankRedirectInfo),
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum WalletInfo {
GooglePay(GpayInfo),
Alipay(AlipayInfo),
WeChatPay(WeChatPayInfo),
MbWay(MbWayInfo),
}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct MbWayInfo {}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct WeChatPayInfo {}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct AlipayInfo {}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum BankRedirectInfo {
Ideal(IdealInfo),
Trustly(TrustlyInfo),
Eps(EpsInfo),
Sofort(SofortInfo),
}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct SofortInfo {}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct EpsInfo {}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct TrustlyInfo {}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct IdealInfo {
pub issuer_id: MultisafepayBankNames,
}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub enum MultisafepayBankNames {
#[serde(rename = "0031")]
AbnAmro,
#[serde(rename = "0761")]
AsnBank,
#[serde(rename = "4371")]
Bunq,
#[serde(rename = "0721")]
Ing,
#[serde(rename = "0801")]
Knab,
#[serde(rename = "9926")]
N26,
#[serde(rename = "9927")]
NationaleNederlanden,
#[serde(rename = "0021")]
Rabobank,
#[serde(rename = "0771")]
Regiobank,
#[serde(rename = "1099")]
Revolut,
#[serde(rename = "0751")]
SnsBank,
#[serde(rename = "0511")]
TriodosBank,
#[serde(rename = "0161")]
VanLanschot,
#[serde(rename = "0806")]
Yoursafe,
#[serde(rename = "1235")]
Handelsbanken,
}
impl TryFrom<&BankNames> for MultisafepayBankNames {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(bank: &BankNames) -> Result<Self, Self::Error> {
match bank {
BankNames::AbnAmro => Ok(Self::AbnAmro),
BankNames::AsnBank => Ok(Self::AsnBank),
BankNames::Bunq => Ok(Self::Bunq),
BankNames::Ing => Ok(Self::Ing),
BankNames::Knab => Ok(Self::Knab),
BankNames::N26 => Ok(Self::N26),
BankNames::NationaleNederlanden => Ok(Self::NationaleNederlanden),
BankNames::Rabobank => Ok(Self::Rabobank),
BankNames::Regiobank => Ok(Self::Regiobank),
BankNames::Revolut => Ok(Self::Revolut),
BankNames::SnsBank => Ok(Self::SnsBank),
BankNames::TriodosBank => Ok(Self::TriodosBank),
BankNames::VanLanschot => Ok(Self::VanLanschot),
BankNames::Yoursafe => Ok(Self::Yoursafe),
BankNames::Handelsbanken => Ok(Self::Handelsbanken),
BankNames::AmericanExpress
| BankNames::AffinBank
| BankNames::AgroBank
| BankNames::AllianceBank
| BankNames::AmBank
| BankNames::BankOfAmerica
| BankNames::BankOfChina
| BankNames::BankIslam
| BankNames::BankMuamalat
| BankNames::BankRakyat
| BankNames::BankSimpananNasional
| BankNames::Barclays
| BankNames::BlikPSP
| BankNames::CapitalOne
| BankNames::Chase
| BankNames::Citi
| BankNames::CimbBank
| BankNames::Discover
| BankNames::NavyFederalCreditUnion
| BankNames::PentagonFederalCreditUnion
| BankNames::SynchronyBank
| BankNames::WellsFargo
| BankNames::HongLeongBank
| BankNames::HsbcBank
| BankNames::KuwaitFinanceHouse
| BankNames::Moneyou
| BankNames::ArzteUndApothekerBank
| BankNames::AustrianAnadiBankAg
| BankNames::BankAustria
| BankNames::Bank99Ag
| BankNames::BankhausCarlSpangler
| BankNames::BankhausSchelhammerUndSchatteraAg
| BankNames::BankMillennium
| BankNames::BankPEKAOSA
| BankNames::BawagPskAg
| BankNames::BksBankAg
| BankNames::BrullKallmusBankAg
| BankNames::BtvVierLanderBank
| BankNames::CapitalBankGraweGruppeAg
| BankNames::CeskaSporitelna
| BankNames::Dolomitenbank
| BankNames::EasybankAg
| BankNames::EPlatbyVUB
| BankNames::ErsteBankUndSparkassen
| BankNames::FrieslandBank
| BankNames::HypoAlpeadriabankInternationalAg
| BankNames::HypoNoeLbFurNiederosterreichUWien
| BankNames::HypoOberosterreichSalzburgSteiermark
| BankNames::HypoTirolBankAg
| BankNames::HypoVorarlbergBankAg
| BankNames::HypoBankBurgenlandAktiengesellschaft
| BankNames::KomercniBanka
| BankNames::MBank
| BankNames::MarchfelderBank
| BankNames::Maybank
| BankNames::OberbankAg
| BankNames::OsterreichischeArzteUndApothekerbank
| BankNames::OcbcBank
| BankNames::PayWithING
| BankNames::PlaceZIPKO
| BankNames::PlatnoscOnlineKartaPlatnicza
| BankNames::PosojilnicaBankEGen
| BankNames::PostovaBanka
| BankNames::PublicBank
| BankNames::RaiffeisenBankengruppeOsterreich
| BankNames::RhbBank
| BankNames::SchelhammerCapitalBankAg
| BankNames::StandardCharteredBank
| BankNames::SchoellerbankAg
| BankNames::SpardaBankWien
| BankNames::SporoPay
| BankNames::SantanderPrzelew24
| BankNames::TatraPay
| BankNames::Viamo
| BankNames::VolksbankGruppe
| BankNames::VolkskreditbankAg
| BankNames::VrBankBraunau
| BankNames::UobBank
| BankNames::PayWithAliorBank
| BankNames::BankiSpoldzielcze
| BankNames::PayWithInteligo
| BankNames::BNPParibasPoland
| BankNames::BankNowySA
| BankNames::CreditAgricole
| BankNames::PayWithBOS
| BankNames::PayWithCitiHandlowy
| BankNames::PayWithPlusBank
| BankNames::ToyotaBank
| BankNames::VeloBank
| BankNames::ETransferPocztowy24
| BankNames::PlusBank
| BankNames::EtransferPocztowy24
| BankNames::BankiSpbdzielcze
| BankNames::BankNowyBfgSa
| BankNames::GetinBank
| BankNames::Blik
| BankNames::NoblePay
| BankNames::IdeaBank
| BankNames::EnveloBank
| BankNames::NestPrzelew
| BankNames::MbankMtransfer
| BankNames::Inteligo
| BankNames::PbacZIpko
| BankNames::BnpParibas
| BankNames::BankPekaoSa
| BankNames::VolkswagenBank
| BankNames::AliorBank
| BankNames::Boz
| BankNames::BangkokBank
| BankNames::KrungsriBank
| BankNames::KrungThaiBank
| BankNames::TheSiamCommercialBank
| BankNames::KasikornBank
| BankNames::OpenBankSuccess
| BankNames::OpenBankFailure
| BankNames::OpenBankCancelled
| BankNames::Aib
| BankNames::BankOfScotland
| BankNames::DanskeBank
| BankNames::FirstDirect
| BankNames::FirstTrust
| BankNames::Halifax
| BankNames::Lloyds
| BankNames::Monzo
| BankNames::NatWest
| BankNames::NationwideBank
| BankNames::RoyalBankOfScotland
| BankNames::Starling
| BankNames::TsbBank
| BankNames::TescoBank
| BankNames::UlsterBank => Err(Into::into(errors::ConnectorError::NotSupported {
message: String::from("BankRedirect"),
connector: "Multisafepay",
})),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct DeliveryObject {
first_name: Secret<String>,
last_name: Secret<String>,
address1: Secret<String>,
house_number: Secret<String>,
zip_code: Secret<String>,
city: String,
country: api_models::enums::CountryAlpha2,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct DefaultObject {
shipping_taxed: bool,
rate: f64,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct TaxObject {
pub default: DefaultObject,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct CheckoutOptions {
pub validate_cart: Option<bool>,
pub tax_tables: TaxObject,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct Item {
pub name: String,
pub unit_price: FloatMajorUnit,
pub description: Option<String>,
pub quantity: i64,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct ShoppingCart {
pub items: Vec<Item>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct MultisafepayPaymentsRequest {
#[serde(rename = "type")]
pub payment_type: Type,
pub gateway: Option<Gateway>,
pub order_id: String,
pub currency: String,
pub amount: MinorUnit,
pub description: String,
pub payment_options: Option<PaymentOptions>,
pub customer: Option<Customer>,
pub gateway_info: Option<GatewayInfo>,
pub delivery: Option<DeliveryObject>,
pub checkout_options: Option<CheckoutOptions>,
pub shopping_cart: Option<ShoppingCart>,
pub items: Option<String>,
pub recurring_model: Option<MandateType>,
pub recurring_id: Option<Secret<String>>,
pub capture: Option<String>,
pub days_active: Option<i32>,
pub seconds_active: Option<i32>,
pub var1: Option<String>,
pub var2: Option<String>,
pub var3: Option<String>,
}
impl TryFrom<utils::CardIssuer> for Gateway {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(issuer: utils::CardIssuer) -> Result<Self, Self::Error> {
match issuer {
utils::CardIssuer::AmericanExpress => Ok(Self::Amex),
utils::CardIssuer::Master => Ok(Self::MasterCard),
utils::CardIssuer::Maestro => Ok(Self::Maestro),
utils::CardIssuer::Discover => Ok(Self::Discover),
utils::CardIssuer::Visa => Ok(Self::Visa),
utils::CardIssuer::DinersClub
| utils::CardIssuer::JCB
| utils::CardIssuer::CarteBlanche
| utils::CardIssuer::UnionPay
| utils::CardIssuer::CartesBancaires => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Multisafe pay"),
)
.into()),
}
}
}
impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
for MultisafepayPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payment_type = match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref _ccard) => Type::Direct,
PaymentMethodData::MandatePayment => Type::Direct,
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletData::GooglePay(_) => Type::Direct,
WalletData::PaypalRedirect(_) => Type::Redirect,
WalletData::AliPayRedirect(_) => Type::Redirect,
WalletData::WeChatPayRedirect(_) => Type::Redirect,
WalletData::MbWayRedirect(_) => Type::Redirect,
WalletData::AliPayQr(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
},
PaymentMethodData::BankRedirect(ref bank_data) => match bank_data {
BankRedirectData::Giropay { .. } => Type::Redirect,
BankRedirectData::Ideal { .. } => Type::Direct,
BankRedirectData::Trustly { .. } => Type::Redirect,
BankRedirectData::Eps { .. } => Type::Redirect,
BankRedirectData::Sofort { .. } => Type::Redirect,
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Bizum { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?
}
},
PaymentMethodData::PayLater(ref _paylater) => Type::Redirect,
_ => Type::Redirect,
};
let gateway = match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => {
Some(Gateway::try_from(ccard.get_card_issuer()?)?)
}
PaymentMethodData::Wallet(ref wallet_data) => Some(match wallet_data {
WalletData::GooglePay(_) => Gateway::Googlepay,
WalletData::PaypalRedirect(_) => Gateway::Paypal,
WalletData::AliPayRedirect(_) => Gateway::Alipay,
WalletData::WeChatPayRedirect(_) => Gateway::WeChatPay,
WalletData::MbWayRedirect(_) => Gateway::MbWay,
WalletData::AliPayQr(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
}),
PaymentMethodData::BankRedirect(ref bank_data) => Some(match bank_data {
BankRedirectData::Giropay { .. } => Gateway::Giropay,
BankRedirectData::Ideal { .. } => Gateway::Ideal,
BankRedirectData::Trustly { .. } => Gateway::Trustly,
BankRedirectData::Eps { .. } => Gateway::Eps,
BankRedirectData::Sofort { .. } => Gateway::Sofort,
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Bizum { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?
}
}),
PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect {}) => Some(Gateway::Klarna),
PaymentMethodData::MandatePayment => None,
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?
}
};
let description = item.router_data.get_description()?;
let payment_options = PaymentOptions {
notification_url: None,
redirect_url: item.router_data.request.get_router_return_url()?,
cancel_url: item.router_data.request.get_router_return_url()?,
close_window: None,
notification_method: None,
settings: None,
template_id: None,
allowed_countries: None,
};
let customer = Customer {
browser: None,
locale: None,
ip_address: None,
forward_ip: None,
first_name: None,
last_name: None,
gender: None,
birthday: None,
address1: None,
address2: None,
house_number: None,
zip_code: None,
city: None,
state: None,
country: None,
phone: None,
email: item.router_data.request.email.clone(),
user_agent: None,
referrer: None,
reference: Some(item.router_data.connector_request_reference_id.clone()),
};
let billing_address = item
.router_data
.get_billing()?
.address
.as_ref()
.ok_or_else(utils::missing_field_err("billing.address"))?;
let first_name = billing_address.get_first_name()?;
let delivery = DeliveryObject {
first_name: first_name.clone(),
last_name: billing_address
.get_last_name()
.unwrap_or(first_name)
.clone(),
address1: billing_address.get_line1()?.to_owned(),
house_number: billing_address.get_line2()?.to_owned(),
zip_code: billing_address.get_zip()?.to_owned(),
city: billing_address.get_city()?.to_owned(),
country: billing_address.get_country()?.to_owned(),
};
let gateway_info = match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => Some(GatewayInfo::Card(CardInfo {
card_number: Some(ccard.card_number.clone()),
card_expiry_date: Some(Secret::new(
(format!(
"{}{}",
ccard.get_card_expiry_year_2_digit()?.expose(),
ccard.card_exp_month.clone().expose()
))
.parse::<i32>()
.unwrap_or_default(),
)),
card_cvc: Some(ccard.card_cvc.clone()),
card_holder_name: None,
flexible_3d: None,
moto: None,
term_url: None,
})),
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletData::GooglePay(ref google_pay) => {
Some(GatewayInfo::Wallet(WalletInfo::GooglePay({
GpayInfo {
payment_token: Some(Secret::new(
google_pay
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "google_pay_token",
})?
.clone(),
)),
}
})))
}
WalletData::AliPayRedirect(_) => {
Some(GatewayInfo::Wallet(WalletInfo::Alipay(AlipayInfo {})))
}
WalletData::PaypalRedirect(_) => None,
WalletData::WeChatPayRedirect(_) => {
Some(GatewayInfo::Wallet(WalletInfo::WeChatPay(WeChatPayInfo {})))
}
WalletData::MbWayRedirect(_) => {
Some(GatewayInfo::Wallet(WalletInfo::MbWay(MbWayInfo {})))
}
WalletData::AliPayQr(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
},
PaymentMethodData::PayLater(ref paylater) => {
Some(GatewayInfo::PayLater(PayLaterInfo {
email: Some(match paylater {
PayLaterData::KlarnaRedirect {} => item.router_data.get_billing_email()?,
PayLaterData::KlarnaSdk { token: _ }
| PayLaterData::AffirmRedirect {}
| PayLaterData::FlexitiRedirect {}
| PayLaterData::AfterpayClearpayRedirect {}
| PayLaterData::PayBrightRedirect {}
| PayLaterData::WalleyRedirect {}
| PayLaterData::AlmaRedirect {}
| PayLaterData::AtomeRedirect {}
| PayLaterData::BreadpayRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"multisafepay",
),
))?
}
}),
}))
}
PaymentMethodData::BankRedirect(ref bank_redirect_data) => match bank_redirect_data {
BankRedirectData::Ideal { bank_name, .. } => Some(GatewayInfo::BankRedirect(
BankRedirectInfo::Ideal(IdealInfo {
issuer_id: MultisafepayBankNames::try_from(&bank_name.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "ideal.bank_name",
},
)?)?,
}),
)),
BankRedirectData::Trustly { .. } => Some(GatewayInfo::BankRedirect(
BankRedirectInfo::Trustly(TrustlyInfo {}),
)),
BankRedirectData::Eps { .. } => {
Some(GatewayInfo::BankRedirect(BankRedirectInfo::Eps(EpsInfo {})))
}
BankRedirectData::Sofort { .. } => Some(GatewayInfo::BankRedirect(
BankRedirectInfo::Sofort(SofortInfo {}),
)),
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Bizum { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Giropay { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {} => None,
},
PaymentMethodData::MandatePayment => None,
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?
}
};
Ok(Self {
payment_type,
gateway,
order_id: item.router_data.connector_request_reference_id.to_string(),
currency: item.router_data.request.currency.to_string(),
amount: item.amount,
description,
payment_options: Some(payment_options),
customer: Some(customer),
delivery: Some(delivery),
gateway_info,
checkout_options: None,
shopping_cart: None,
capture: None,
items: None,
recurring_model: if item.router_data.request.is_mandate_payment() {
Some(MandateType::Unscheduled)
} else {
None
},
recurring_id: item
.router_data
.request
.mandate_id
.clone()
.and_then(|mandate_ids| match mandate_ids.mandate_reference_id {
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_ids,
)) => connector_mandate_ids
.get_connector_mandate_id()
.map(Secret::new),
_ => None,
}),
days_active: Some(30),
seconds_active: Some(259200),
var1: None,
var2: None,
var3: None,
})
}
}
// Auth Struct
pub struct MultisafepayAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for MultisafepayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::HeaderKey { api_key } = auth_type {
Ok(Self {
api_key: api_key.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Default, Eq, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum MultisafepayPaymentStatus {
Completed,
Declined,
#[default]
Initialized,
Void,
Uncleared,
}
#[derive(Debug, Clone, Eq, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum MandateType {
Unscheduled,
}
impl From<MultisafepayPaymentStatus> for AttemptStatus {
fn from(item: MultisafepayPaymentStatus) -> Self {
match item {
MultisafepayPaymentStatus::Completed => Self::Charged,
MultisafepayPaymentStatus::Declined => Self::Failure,
MultisafepayPaymentStatus::Initialized => Self::AuthenticationPending,
MultisafepayPaymentStatus::Uncleared => Self::Pending,
MultisafepayPaymentStatus::Void => Self::Voided,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Data {
#[serde(rename = "type")]
pub payment_type: Option<String>,
pub order_id: String,
pub currency: Option<String>,
pub amount: Option<MinorUnit>,
pub description: Option<String>,
pub capture: Option<String>,
pub payment_url: Option<Url>,
pub status: Option<MultisafepayPaymentStatus>,
pub reason: Option<String>,
pub reason_code: Option<String>,
pub payment_details: Option<MultisafepayPaymentDetails>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub struct MultisafepayPaymentDetails {
pub account_holder_name: Option<Secret<String>>,
pub account_id: Option<Secret<String>>,
pub card_expiry_date: Option<Secret<String>>,
pub external_transaction_id: Option<serde_json::Value>,
pub last4: Option<Secret<String>>,
pub recurring_flow: Option<String>,
pub recurring_id: Option<Secret<String>>,
pub recurring_model: Option<String>,
#[serde(rename = "type")]
pub payment_type: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct MultisafepayPaymentsResponse {
pub success: bool,
pub data: Data,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[serde(untagged)]
pub enum MultisafepayAuthResponse {
ErrorResponse(MultisafepayErrorResponse),
PaymentResponse(Box<MultisafepayPaymentsResponse>),
}
impl<F, T> TryFrom<ResponseRouterData<F, MultisafepayAuthResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ParsingError>;
fn try_from(
item: ResponseRouterData<F, MultisafepayAuthResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
MultisafepayAuthResponse::PaymentResponse(payment_response) => {
let redirection_data = payment_response
.data
.payment_url
.clone()
.map(|url| RedirectForm::from((url, Method::Get)));
let default_status = if payment_response.success {
MultisafepayPaymentStatus::Initialized
} else {
MultisafepayPaymentStatus::Declined
};
let status =
AttemptStatus::from(payment_response.data.status.unwrap_or(default_status));
Ok(Self {
status,
response: if utils::is_payment_failure(status) {
Err(populate_error_reason(
payment_response.data.reason_code,
payment_response.data.reason.clone(),
payment_response.data.reason,
item.http_code,
Some(status),
Some(payment_response.data.order_id),
))
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
payment_response.data.order_id.clone(),
),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(
payment_response
.data
.payment_details
.and_then(|payment_details| payment_details.recurring_id)
.map(|id| MandateReference {
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}),
),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
payment_response.data.order_id.clone(),
),
incremental_authorization_allowed: None,
charges: None,
})
},
..item.data
})
}
MultisafepayAuthResponse::ErrorResponse(error_response) => {
let attempt_status = Option::<AttemptStatus>::from(error_response.clone());
Ok(Self {
response: Err(populate_error_reason(
Some(error_response.error_code.to_string()),
Some(error_response.error_info.clone()),
Some(error_response.error_info),
item.http_code,
attempt_status,
None,
)),
..item.data
})
}
}
}
}
pub fn populate_error_reason(
code: Option<String>,
message: Option<String>,
reason: Option<String>,
http_code: u16,
attempt_status: Option<AttemptStatus>,
connector_transaction_id: Option<String>,
) -> ErrorResponse {
ErrorResponse {
code: code.unwrap_or(NO_ERROR_CODE.to_string()),
message: message.clone().unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason,
status_code: http_code,
attempt_status,
connector_transaction_id,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
pub struct MultisafepayRefundRequest {
pub currency: enums::Currency,
pub amount: MinorUnit,
pub description: Option<String>,
pub refund_order_id: Option<String>,
pub checkout_data: Option<ShoppingCart>,
}
impl<F> TryFrom<&MultisafepayRouterData<&types::RefundsRouterData<F>>>
for MultisafepayRefundRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &MultisafepayRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
currency: item.router_data.request.currency,
amount: item.amount,
description: item.router_data.description.clone(),
refund_order_id: Some(item.router_data.request.refund_id.clone()),
checkout_data: None,
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundData {
pub transaction_id: i64,
pub refund_id: i64,
pub order_id: Option<String>,
pub error_code: Option<i32>,
pub error_info: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
pub success: bool,
pub data: RefundData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MultisafepayRefundResponse {
ErrorResponse(MultisafepayErrorResponse),
RefundResponse(RefundResponse),
}
impl TryFrom<RefundsResponseRouterData<Execute, MultisafepayRefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<ParsingError>;
fn try_from(
item: RefundsResponseRouterData<Execute, MultisafepayRefundResponse>,
) -> Result<Self, Self::Error> {
match item.response {
MultisafepayRefundResponse::RefundResponse(refund_data) => {
let refund_status = if refund_data.success {
RefundStatus::Succeeded
} else {
RefundStatus::Failed
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: refund_data.data.refund_id.to_string(),
refund_status: enums::RefundStatus::from(refund_status),
}),
..item.data
})
}
MultisafepayRefundResponse::ErrorResponse(error_response) => {
let attempt_status = Option::<AttemptStatus>::from(error_response.clone());
Ok(Self {
response: Err(ErrorResponse {
code: error_response.error_code.to_string(),
message: error_response.error_info.clone(),
reason: Some(error_response.error_info),
status_code: item.http_code,
attempt_status,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
}
impl TryFrom<RefundsResponseRouterData<RSync, MultisafepayRefundResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<ParsingError>;
fn try_from(
item: RefundsResponseRouterData<RSync, MultisafepayRefundResponse>,
) -> Result<Self, Self::Error> {
match item.response {
MultisafepayRefundResponse::RefundResponse(refund_data) => {
let refund_status = if refund_data.success {
RefundStatus::Succeeded
} else {
RefundStatus::Failed
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: refund_data.data.refund_id.to_string(),
refund_status: enums::RefundStatus::from(refund_status),
}),
..item.data
})
}
MultisafepayRefundResponse::ErrorResponse(error_response) => Ok(Self {
response: Err(populate_error_reason(
Some(error_response.error_code.to_string()),
Some(error_response.error_info.clone()),
Some(error_response.error_info),
item.http_code,
None,
None,
)),
..item.data
}),
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct MultisafepayErrorResponse {
pub error_code: i32,
pub error_info: String,
}
impl From<MultisafepayErrorResponse> for Option<AttemptStatus> {
fn from(error_data: MultisafepayErrorResponse) -> Self {
match error_data.error_code {
10001 // InvalidAmount
| 1002 // InvalidCurrency
| 1003 // InvalidAccountID
| 1004 // InvalidSiteID
| 1005 // InvalidSecurityCode
| 1006 // InvalidTransactionID
| 1007 // InvalidIPAddress
| 1008 // InvalidDescription
| 1010 // InvalidVariable
| 1011 // InvalidCustomerAccountID
| 1012 // InvalidCustomerSecurityCode
| 1013 // InvalidSignature
| 1015 //UnknownAccountID
| 1016 // MissingData
| 1018 // InvalidCountryCode
| 1025 // MultisafepayErrorCodes::IncorrectCustomerIPAddress
| 1026 // MultisafepayErrorCodes::MultipleCurrenciesInCart
| 1027 // MultisafepayErrorCodes::CartCurrencyDifferentToOrderCurrency
| 1028 // IncorrectCustomTaxRate
| 1029 // IncorrectItemTaxRate
| 1030 // IncorrectItemCurrency
| 1031 // IncorrectItemPrice
| 1035 // InvalidSignatureRefund
| 1036 // InvalidIdealIssuerID
| 5001 // CartDataNotValidated
| 1032 // InvalidAPIKey
=> {
Some(AttemptStatus::AuthenticationFailed)
}
1034 // CannotRefundTransaction
| 1022 // CannotInitiateTransaction
| 1024 //TransactionDeclined
=> Some(AttemptStatus::Failure),
1017 // InsufficientFunds
=> Some(AttemptStatus::AuthorizationFailed),
_ => None,
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 11096
}
|
large_file_-7155116912310070103
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs
</path>
<file>
use cards::CardNumber;
use common_enums::{enums, AttemptStatus, CaptureMethod, Currency, PaymentMethod};
use common_utils::{errors::ParsingError, ext_traits::Encode};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::Execute,
router_request_types::ResponseId,
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{api::CurrencyUnit, errors::ConnectorError};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
get_amount_as_string, get_unimplemented_payment_method_error_message, to_connector_meta,
CardData, CardIssuer, RouterData as _,
},
};
#[derive(Debug, Serialize)]
pub struct PayeezyRouterData<T> {
pub amount: String,
pub router_data: T,
}
impl<T> TryFrom<(&CurrencyUnit, Currency, i64, T)> for PayeezyRouterData<T> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
(currency_unit, currency, amount, router_data): (&CurrencyUnit, Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = get_amount_as_string(currency_unit, amount, currency)?;
Ok(Self {
amount,
router_data,
})
}
}
#[derive(Serialize, Debug)]
pub struct PayeezyCard {
#[serde(rename = "type")]
pub card_type: PayeezyCardType,
pub cardholder_name: Secret<String>,
pub card_number: CardNumber,
pub exp_date: Secret<String>,
pub cvv: Secret<String>,
}
#[derive(Serialize, Debug)]
pub enum PayeezyCardType {
#[serde(rename = "American Express")]
AmericanExpress,
Visa,
Mastercard,
Discover,
}
impl TryFrom<CardIssuer> for PayeezyCardType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(issuer: CardIssuer) -> Result<Self, Self::Error> {
match issuer {
CardIssuer::AmericanExpress => Ok(Self::AmericanExpress),
CardIssuer::Master => Ok(Self::Mastercard),
CardIssuer::Discover => Ok(Self::Discover),
CardIssuer::Visa => Ok(Self::Visa),
CardIssuer::Maestro
| CardIssuer::DinersClub
| CardIssuer::JCB
| CardIssuer::CarteBlanche
| CardIssuer::UnionPay
| CardIssuer::CartesBancaires => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Payeezy"),
))?,
}
}
}
#[derive(Serialize, Debug)]
#[serde(untagged)]
pub enum PayeezyPaymentMethod {
PayeezyCard(PayeezyCard),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PayeezyPaymentMethodType {
CreditCard,
}
#[derive(Serialize, Debug)]
pub struct PayeezyPaymentsRequest {
pub merchant_ref: String,
pub transaction_type: PayeezyTransactionType,
pub method: PayeezyPaymentMethodType,
pub amount: String,
pub currency_code: String,
pub credit_card: PayeezyPaymentMethod,
pub stored_credentials: Option<StoredCredentials>,
pub reference: String,
}
#[derive(Serialize, Debug)]
pub struct StoredCredentials {
pub sequence: Sequence,
pub initiator: Initiator,
pub is_scheduled: bool,
pub cardbrand_original_transaction_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Sequence {
First,
Subsequent,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Initiator {
Merchant,
CardHolder,
}
impl TryFrom<&PayeezyRouterData<&PaymentsAuthorizeRouterData>> for PayeezyPaymentsRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &PayeezyRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.payment_method {
PaymentMethod::Card => get_card_specific_payment_data(item),
PaymentMethod::CardRedirect
| PaymentMethod::PayLater
| PaymentMethod::Wallet
| PaymentMethod::BankRedirect
| PaymentMethod::BankTransfer
| PaymentMethod::Crypto
| PaymentMethod::BankDebit
| PaymentMethod::Reward
| PaymentMethod::RealTimePayment
| PaymentMethod::MobilePayment
| PaymentMethod::Upi
| PaymentMethod::Voucher
| PaymentMethod::OpenBanking
| PaymentMethod::GiftCard => {
Err(ConnectorError::NotImplemented("Payment methods".to_string()).into())
}
}
}
}
fn get_card_specific_payment_data(
item: &PayeezyRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<PayeezyPaymentsRequest, error_stack::Report<ConnectorError>> {
let merchant_ref = item.router_data.attempt_id.to_string();
let method = PayeezyPaymentMethodType::CreditCard;
let amount = item.amount.clone();
let currency_code = item.router_data.request.currency.to_string();
let credit_card = get_payment_method_data(item)?;
let (transaction_type, stored_credentials) =
get_transaction_type_and_stored_creds(item.router_data)?;
Ok(PayeezyPaymentsRequest {
merchant_ref,
transaction_type,
method,
amount,
currency_code,
credit_card,
stored_credentials,
reference: item.router_data.connector_request_reference_id.clone(),
})
}
fn get_transaction_type_and_stored_creds(
item: &PaymentsAuthorizeRouterData,
) -> Result<(PayeezyTransactionType, Option<StoredCredentials>), error_stack::Report<ConnectorError>>
{
let connector_mandate_id = item.request.mandate_id.as_ref().and_then(|mandate_ids| {
match mandate_ids.mandate_reference_id.clone() {
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_ids,
)) => connector_mandate_ids.get_connector_mandate_id(),
_ => None,
}
});
let (transaction_type, stored_credentials) =
if is_mandate_payment(item, connector_mandate_id.as_ref()) {
// Mandate payment
(
PayeezyTransactionType::Recurring,
Some(StoredCredentials {
// connector_mandate_id is not present then it is a First payment, else it is a Subsequent mandate payment
sequence: match connector_mandate_id.is_some() {
true => Sequence::Subsequent,
false => Sequence::First,
},
// off_session true denotes the customer not present during the checkout process. In other cases customer present at the checkout.
initiator: match item.request.off_session {
Some(true) => Initiator::Merchant,
_ => Initiator::CardHolder,
},
is_scheduled: true,
// In case of first mandate payment connector_mandate_id would be None, otherwise holds some value
cardbrand_original_transaction_id: connector_mandate_id.map(Secret::new),
}),
)
} else {
match item.request.capture_method {
Some(CaptureMethod::Manual) => Ok((PayeezyTransactionType::Authorize, None)),
Some(CaptureMethod::SequentialAutomatic) | Some(CaptureMethod::Automatic) => {
Ok((PayeezyTransactionType::Purchase, None))
}
Some(CaptureMethod::ManualMultiple) | Some(CaptureMethod::Scheduled) | None => {
Err(ConnectorError::FlowNotSupported {
flow: item.request.capture_method.unwrap_or_default().to_string(),
connector: "Payeezy".to_string(),
})
}
}?
};
Ok((transaction_type, stored_credentials))
}
fn is_mandate_payment(
item: &PaymentsAuthorizeRouterData,
connector_mandate_id: Option<&String>,
) -> bool {
item.request.setup_mandate_details.is_some() || connector_mandate_id.is_some()
}
fn get_payment_method_data(
item: &PayeezyRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<PayeezyPaymentMethod, error_stack::Report<ConnectorError>> {
match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref card) => {
let card_type = PayeezyCardType::try_from(card.get_card_issuer()?)?;
let payeezy_card = PayeezyCard {
card_type,
cardholder_name: item
.router_data
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string())),
card_number: card.card_number.clone(),
exp_date: card.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?,
cvv: card.card_cvc.clone(),
};
Ok(PayeezyPaymentMethod::PayeezyCard(payeezy_card))
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Payeezy"),
))?
}
}
}
// Auth Struct
pub struct PayeezyAuthType {
pub(super) api_key: Secret<String>,
pub(super) api_secret: Secret<String>,
pub(super) merchant_token: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PayeezyAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = item
{
Ok(Self {
api_key: api_key.to_owned(),
api_secret: api_secret.to_owned(),
merchant_token: key1.to_owned(),
})
} else {
Err(ConnectorError::FailedToObtainAuthType.into())
}
}
}
// PaymentsResponse
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum PayeezyPaymentStatus {
Approved,
Declined,
#[default]
#[serde(rename = "Not Processed")]
NotProcessed,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PayeezyPaymentsResponse {
pub correlation_id: String,
pub transaction_status: PayeezyPaymentStatus,
pub validation_status: String,
pub transaction_type: PayeezyTransactionType,
pub transaction_id: String,
pub transaction_tag: Option<String>,
pub method: Option<String>,
pub amount: String,
pub currency: String,
pub bank_resp_code: String,
pub bank_message: String,
pub gateway_resp_code: String,
pub gateway_message: String,
pub stored_credentials: Option<PaymentsStoredCredentials>,
pub reference: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaymentsStoredCredentials {
cardbrand_original_transaction_id: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct PayeezyCaptureOrVoidRequest {
transaction_tag: String,
transaction_type: PayeezyTransactionType,
amount: String,
currency_code: String,
}
impl TryFrom<&PayeezyRouterData<&PaymentsCaptureRouterData>> for PayeezyCaptureOrVoidRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PayeezyRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let metadata: PayeezyPaymentsMetadata =
to_connector_meta(item.router_data.request.connector_meta.clone())
.change_context(ConnectorError::RequestEncodingFailed)?;
Ok(Self {
transaction_type: PayeezyTransactionType::Capture,
amount: item.amount.clone(),
currency_code: item.router_data.request.currency.to_string(),
transaction_tag: metadata.transaction_tag,
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for PayeezyCaptureOrVoidRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let metadata: PayeezyPaymentsMetadata =
to_connector_meta(item.request.connector_meta.clone())
.change_context(ConnectorError::RequestEncodingFailed)?;
Ok(Self {
transaction_type: PayeezyTransactionType::Void,
amount: item
.request
.amount
.ok_or(ConnectorError::RequestEncodingFailed)?
.to_string(),
currency_code: item.request.currency.unwrap_or_default().to_string(),
transaction_tag: metadata.transaction_tag,
})
}
}
#[derive(Debug, Deserialize, Serialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum PayeezyTransactionType {
Authorize,
Capture,
Purchase,
Recurring,
Void,
Refund,
#[default]
Pending,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PayeezyPaymentsMetadata {
transaction_tag: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PayeezyPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PayeezyPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let metadata = item
.response
.transaction_tag
.map(|txn_tag| construct_payeezy_payments_metadata(txn_tag).encode_to_value())
.transpose()
.change_context(ConnectorError::ResponseHandlingFailed)?;
let mandate_reference = item
.response
.stored_credentials
.map(|credentials| credentials.cardbrand_original_transaction_id)
.map(|id| MandateReference {
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
let status = get_status(
item.response.transaction_status,
item.response.transaction_type,
);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: metadata,
network_txn_id: None,
connector_response_reference_id: Some(
item.response
.reference
.unwrap_or(item.response.transaction_id),
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
fn get_status(status: PayeezyPaymentStatus, method: PayeezyTransactionType) -> AttemptStatus {
match status {
PayeezyPaymentStatus::Approved => match method {
PayeezyTransactionType::Authorize => AttemptStatus::Authorized,
PayeezyTransactionType::Capture
| PayeezyTransactionType::Purchase
| PayeezyTransactionType::Recurring => AttemptStatus::Charged,
PayeezyTransactionType::Void => AttemptStatus::Voided,
PayeezyTransactionType::Refund | PayeezyTransactionType::Pending => {
AttemptStatus::Pending
}
},
PayeezyPaymentStatus::Declined | PayeezyPaymentStatus::NotProcessed => match method {
PayeezyTransactionType::Capture => AttemptStatus::CaptureFailed,
PayeezyTransactionType::Authorize
| PayeezyTransactionType::Purchase
| PayeezyTransactionType::Recurring => AttemptStatus::AuthorizationFailed,
PayeezyTransactionType::Void => AttemptStatus::VoidFailed,
PayeezyTransactionType::Refund | PayeezyTransactionType::Pending => {
AttemptStatus::Pending
}
},
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
pub struct PayeezyRefundRequest {
transaction_tag: String,
transaction_type: PayeezyTransactionType,
amount: String,
currency_code: String,
}
impl<F> TryFrom<&PayeezyRouterData<&RefundsRouterData<F>>> for PayeezyRefundRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PayeezyRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let metadata: PayeezyPaymentsMetadata =
to_connector_meta(item.router_data.request.connector_metadata.clone())
.change_context(ConnectorError::RequestEncodingFailed)?;
Ok(Self {
transaction_type: PayeezyTransactionType::Refund,
amount: item.amount.clone(),
currency_code: item.router_data.request.currency.to_string(),
transaction_tag: metadata.transaction_tag,
})
}
}
// Type definition for Refund Response
#[derive(Debug, Deserialize, Default, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum RefundStatus {
Approved,
Declined,
#[default]
#[serde(rename = "Not Processed")]
NotProcessed,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Approved => Self::Success,
RefundStatus::Declined => Self::Failure,
RefundStatus::NotProcessed => Self::Pending,
}
}
}
#[derive(Deserialize, Debug, Serialize)]
pub struct RefundResponse {
pub correlation_id: String,
pub transaction_status: RefundStatus,
pub validation_status: String,
pub transaction_type: String,
pub transaction_id: String,
pub transaction_tag: Option<String>,
pub method: Option<String>,
pub amount: String,
pub currency: String,
pub bank_resp_code: String,
pub bank_message: String,
pub gateway_resp_code: String,
pub gateway_message: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<ParsingError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.transaction_status),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Message {
pub code: String,
pub description: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PayeezyError {
pub messages: Vec<Message>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PayeezyErrorResponse {
pub transaction_status: String,
#[serde(rename = "Error")]
pub error: PayeezyError,
}
fn construct_payeezy_payments_metadata(transaction_tag: String) -> PayeezyPaymentsMetadata {
PayeezyPaymentsMetadata { transaction_tag }
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4349
}
|
large_file_8453606732442574990
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs
</path>
<file>
use api_models;
use common_enums::{enums, Currency};
use common_utils::{ext_traits::OptionExt as _, pii::Email};
use error_stack::ResultExt;
use hyperswitch_domain_models::types::{PayoutsResponseData, PayoutsRouterData};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use super::ErrorDetails;
use crate::{
types::{PayoutIndividualDetailsExt as _, PayoutsResponseRouterData},
utils::{CustomerDetails as _, PayoutsData as _, RouterData},
};
type Error = error_stack::Report<errors::ConnectorError>;
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StripeConnectPayoutStatus {
Canceled,
Failed,
InTransit,
Paid,
Pending,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StripeConnectErrorResponse {
pub error: ErrorDetails,
}
// Payouts
#[derive(Clone, Debug, Serialize)]
pub struct StripeConnectPayoutCreateRequest {
amount: i64,
currency: Currency,
destination: String,
transfer_group: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StripeConnectPayoutCreateResponse {
id: String,
description: Option<String>,
source_transaction: Option<String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct TransferReversals {
object: String,
has_more: bool,
total_count: i32,
url: String,
}
#[derive(Clone, Debug, Serialize)]
pub struct StripeConnectPayoutFulfillRequest {
amount: i64,
currency: Currency,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StripeConnectPayoutFulfillResponse {
id: String,
currency: String,
description: Option<String>,
failure_balance_transaction: Option<String>,
failure_code: Option<String>,
failure_message: Option<String>,
original_payout: Option<String>,
reversed_by: Option<String>,
statement_descriptor: Option<String>,
status: StripeConnectPayoutStatus,
}
#[derive(Clone, Debug, Serialize)]
pub struct StripeConnectReversalRequest {
amount: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StripeConnectReversalResponse {
id: String,
source_refund: Option<String>,
}
#[derive(Clone, Debug, Serialize)]
pub struct StripeConnectRecipientCreateRequest {
#[serde(rename = "type")]
account_type: String,
country: Option<enums::CountryAlpha2>,
email: Option<Email>,
#[serde(rename = "capabilities[card_payments][requested]")]
capabilities_card_payments: Option<bool>,
#[serde(rename = "capabilities[transfers][requested]")]
capabilities_transfers: Option<bool>,
#[serde(rename = "tos_acceptance[date]")]
tos_acceptance_date: Option<i64>,
#[serde(rename = "tos_acceptance[ip]")]
tos_acceptance_ip: Option<Secret<String>>,
business_type: String,
#[serde(rename = "business_profile[mcc]")]
business_profile_mcc: Option<i32>,
#[serde(rename = "business_profile[url]")]
business_profile_url: Option<String>,
#[serde(rename = "business_profile[name]")]
business_profile_name: Option<Secret<String>>,
#[serde(rename = "company[name]")]
company_name: Option<Secret<String>>,
#[serde(rename = "company[address][line1]")]
company_address_line1: Option<Secret<String>>,
#[serde(rename = "company[address][line2]")]
company_address_line2: Option<Secret<String>>,
#[serde(rename = "company[address][postal_code]")]
company_address_postal_code: Option<Secret<String>>,
#[serde(rename = "company[address][city]")]
company_address_city: Option<Secret<String>>,
#[serde(rename = "company[address][state]")]
company_address_state: Option<Secret<String>>,
#[serde(rename = "company[phone]")]
company_phone: Option<Secret<String>>,
#[serde(rename = "company[tax_id]")]
company_tax_id: Option<Secret<String>>,
#[serde(rename = "company[owners_provided]")]
company_owners_provided: Option<bool>,
#[serde(rename = "individual[first_name]")]
individual_first_name: Option<Secret<String>>,
#[serde(rename = "individual[last_name]")]
individual_last_name: Option<Secret<String>>,
#[serde(rename = "individual[dob][day]")]
individual_dob_day: Option<Secret<String>>,
#[serde(rename = "individual[dob][month]")]
individual_dob_month: Option<Secret<String>>,
#[serde(rename = "individual[dob][year]")]
individual_dob_year: Option<Secret<String>>,
#[serde(rename = "individual[address][line1]")]
individual_address_line1: Option<Secret<String>>,
#[serde(rename = "individual[address][line2]")]
individual_address_line2: Option<Secret<String>>,
#[serde(rename = "individual[address][postal_code]")]
individual_address_postal_code: Option<Secret<String>>,
#[serde(rename = "individual[address][city]")]
individual_address_city: Option<String>,
#[serde(rename = "individual[address][state]")]
individual_address_state: Option<Secret<String>>,
#[serde(rename = "individual[email]")]
individual_email: Option<Email>,
#[serde(rename = "individual[phone]")]
individual_phone: Option<Secret<String>>,
#[serde(rename = "individual[id_number]")]
individual_id_number: Option<Secret<String>>,
#[serde(rename = "individual[ssn_last_4]")]
individual_ssn_last_4: Option<Secret<String>>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct StripeConnectRecipientCreateResponse {
id: String,
}
#[derive(Clone, Debug, Serialize)]
#[serde(untagged)]
pub enum StripeConnectRecipientAccountCreateRequest {
Bank(RecipientBankAccountRequest),
Card(RecipientCardAccountRequest),
Token(RecipientTokenRequest),
}
#[derive(Clone, Debug, Serialize)]
pub struct RecipientTokenRequest {
external_account: String,
}
#[derive(Clone, Debug, Serialize)]
pub struct RecipientCardAccountRequest {
#[serde(rename = "external_account[object]")]
external_account_object: String,
#[serde(rename = "external_account[number]")]
external_account_number: Secret<String>,
#[serde(rename = "external_account[exp_month]")]
external_account_exp_month: Secret<String>,
#[serde(rename = "external_account[exp_year]")]
external_account_exp_year: Secret<String>,
}
#[derive(Clone, Debug, Serialize)]
pub struct RecipientBankAccountRequest {
#[serde(rename = "external_account[object]")]
external_account_object: String,
#[serde(rename = "external_account[country]")]
external_account_country: enums::CountryAlpha2,
#[serde(rename = "external_account[currency]")]
external_account_currency: Currency,
#[serde(rename = "external_account[account_holder_name]")]
external_account_account_holder_name: Secret<String>,
#[serde(rename = "external_account[account_number]")]
external_account_account_number: Secret<String>,
#[serde(rename = "external_account[account_holder_type]")]
external_account_account_holder_type: String,
#[serde(rename = "external_account[routing_number]")]
external_account_routing_number: Secret<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StripeConnectRecipientAccountCreateResponse {
id: String,
}
// Payouts create/transfer request transform
impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectPayoutCreateRequest {
type Error = Error;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
let connector_customer_id = item.get_connector_customer_id()?;
Ok(Self {
amount: request.amount,
currency: request.destination_currency,
destination: connector_customer_id,
transfer_group: item.connector_request_reference_id.clone(),
})
}
}
// Payouts create response transform
impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectPayoutCreateResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, StripeConnectPayoutCreateResponse>,
) -> Result<Self, Self::Error> {
let response: StripeConnectPayoutCreateResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::RequiresFulfillment),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
// Payouts fulfill request transform
impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectPayoutFulfillRequest {
type Error = Error;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
Ok(Self {
amount: request.amount,
currency: request.destination_currency,
})
}
}
// Payouts fulfill response transform
impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectPayoutFulfillResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, StripeConnectPayoutFulfillResponse>,
) -> Result<Self, Self::Error> {
let response: StripeConnectPayoutFulfillResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::from(response.status)),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
// Payouts reversal request transform
impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectReversalRequest {
type Error = Error;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.request.amount,
})
}
}
// Payouts reversal response transform
impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectReversalResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, StripeConnectReversalResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::Cancelled),
connector_payout_id: item.data.request.connector_payout_id.clone(),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
// Recipient creation request transform
impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectRecipientCreateRequest {
type Error = Error;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
let customer_details = request.get_customer_details()?;
let customer_email = customer_details.get_customer_email()?;
let address = item.get_billing_address()?.clone();
let payout_vendor_details = request.get_vendor_details()?;
let (vendor_details, individual_details) = (
payout_vendor_details.vendor_details,
payout_vendor_details.individual_details,
);
Ok(Self {
account_type: vendor_details.account_type,
country: address.country,
email: Some(customer_email.clone()),
capabilities_card_payments: vendor_details.capabilities_card_payments,
capabilities_transfers: vendor_details.capabilities_transfers,
tos_acceptance_date: individual_details.tos_acceptance_date,
tos_acceptance_ip: individual_details.tos_acceptance_ip,
business_type: vendor_details.business_type,
business_profile_mcc: vendor_details.business_profile_mcc,
business_profile_url: vendor_details.business_profile_url,
business_profile_name: vendor_details.business_profile_name.clone(),
company_name: vendor_details.business_profile_name,
company_address_line1: vendor_details.company_address_line1,
company_address_line2: vendor_details.company_address_line2,
company_address_postal_code: vendor_details.company_address_postal_code,
company_address_city: vendor_details.company_address_city,
company_address_state: vendor_details.company_address_state,
company_phone: vendor_details.company_phone,
company_tax_id: vendor_details.company_tax_id,
company_owners_provided: vendor_details.company_owners_provided,
individual_first_name: address.first_name,
individual_last_name: address.last_name,
individual_dob_day: individual_details.individual_dob_day,
individual_dob_month: individual_details.individual_dob_month,
individual_dob_year: individual_details.individual_dob_year,
individual_address_line1: address.line1,
individual_address_line2: address.line2,
individual_address_postal_code: address.zip,
individual_address_city: address.city,
individual_address_state: address.state,
individual_email: Some(customer_email),
individual_phone: customer_details.phone,
individual_id_number: individual_details.individual_id_number,
individual_ssn_last_4: individual_details.individual_ssn_last_4,
})
}
}
// Recipient creation response transform
impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectRecipientCreateResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, StripeConnectRecipientCreateResponse>,
) -> Result<Self, Self::Error> {
let response: StripeConnectRecipientCreateResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::RequiresVendorAccountCreation),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: true,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
// Recipient account's creation request
impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectRecipientAccountCreateRequest {
type Error = Error;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
let payout_method_data = item.get_payout_method_data()?;
let customer_details = request.get_customer_details()?;
let customer_name = customer_details.get_customer_name()?;
let payout_vendor_details = request.get_vendor_details()?;
match payout_method_data {
api_models::payouts::PayoutMethodData::Card(_) => {
Ok(Self::Token(RecipientTokenRequest {
external_account: "tok_visa_debit".to_string(),
}))
}
api_models::payouts::PayoutMethodData::Bank(bank) => match bank {
api_models::payouts::Bank::Ach(bank_details) => {
Ok(Self::Bank(RecipientBankAccountRequest {
external_account_object: "bank_account".to_string(),
external_account_country: bank_details
.bank_country_code
.get_required_value("bank_country_code")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "bank_country_code",
})?,
external_account_currency: request.destination_currency.to_owned(),
external_account_account_holder_name: customer_name,
external_account_account_holder_type: payout_vendor_details
.individual_details
.get_external_account_account_holder_type()?,
external_account_account_number: bank_details.bank_account_number,
external_account_routing_number: bank_details.bank_routing_number,
}))
}
api_models::payouts::Bank::Bacs(_) => Err(errors::ConnectorError::NotSupported {
message: "BACS payouts are not supported".to_string(),
connector: "stripe",
}
.into()),
api_models::payouts::Bank::Sepa(_) => Err(errors::ConnectorError::NotSupported {
message: "SEPA payouts are not supported".to_string(),
connector: "stripe",
}
.into()),
api_models::payouts::Bank::Pix(_) => Err(errors::ConnectorError::NotSupported {
message: "PIX payouts are not supported".to_string(),
connector: "stripe",
}
.into()),
},
api_models::payouts::PayoutMethodData::Wallet(_) => {
Err(errors::ConnectorError::NotSupported {
message: "Payouts via wallets are not supported".to_string(),
connector: "stripe",
}
.into())
}
api_models::payouts::PayoutMethodData::BankRedirect(_) => {
Err(errors::ConnectorError::NotSupported {
message: "Payouts via BankRedirect are not supported".to_string(),
connector: "stripe",
}
.into())
}
}
}
}
// Recipient account's creation response
impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectRecipientAccountCreateResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, StripeConnectRecipientAccountCreateResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::RequiresCreation),
connector_payout_id: item.data.request.connector_payout_id.clone(),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
impl From<StripeConnectPayoutStatus> for enums::PayoutStatus {
fn from(stripe_connect_status: StripeConnectPayoutStatus) -> Self {
match stripe_connect_status {
StripeConnectPayoutStatus::Paid => Self::Success,
StripeConnectPayoutStatus::Failed => Self::Failed,
StripeConnectPayoutStatus::Canceled => Self::Cancelled,
StripeConnectPayoutStatus::Pending | StripeConnectPayoutStatus::InTransit => {
Self::Pending
}
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4013
}
|
large_file_-2480413339519163688
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs
</path>
<file>
use common_enums::enums;
use common_utils::types::MinorUnit;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::{
PaymentsAuthorizeData, PaymentsCaptureData, PaymentsSyncData, RefundsData, ResponseId,
SetupMandateRequestData,
},
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::ResponseRouterData,
utils::{self, CardData as _, PaymentsAuthorizeRequestData, RouterData as _},
};
type Error = error_stack::Report<errors::ConnectorError>;
pub struct BamboraapacRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for BamboraapacRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BamboraapacMeta {
pub authorize_id: String,
}
// request body in soap format
pub fn get_payment_body(
req: &BamboraapacRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Vec<u8>, Error> {
let transaction_data = get_transaction_body(req)?;
let body = format!(
r#"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Body>
<dts:SubmitSinglePayment>
<dts:trnXML>
<![CDATA[
{transaction_data}
]]>
</dts:trnXML>
</dts:SubmitSinglePayment>
</soapenv:Body>
</soapenv:Envelope>
"#,
);
Ok(body.as_bytes().to_vec())
}
fn get_transaction_body(
req: &BamboraapacRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<String, Error> {
let auth_details = BamboraapacAuthType::try_from(&req.router_data.connector_auth_type)?;
let transaction_type = get_transaction_type(req.router_data.request.capture_method)?;
let card_info = get_card_data(req.router_data)?;
let transaction_data = format!(
r#"
<Transaction>
<CustRef>{}</CustRef>
<Amount>{}</Amount>
<TrnType>{}</TrnType>
<AccountNumber>{}</AccountNumber>
{}
<Security>
<UserName>{}</UserName>
<Password>{}</Password>
</Security>
</Transaction>
"#,
req.router_data.connector_request_reference_id.to_owned(),
req.amount,
transaction_type,
auth_details.account_number.peek(),
card_info,
auth_details.username.peek(),
auth_details.password.peek(),
);
Ok(transaction_data)
}
fn get_card_data(req: &types::PaymentsAuthorizeRouterData) -> Result<String, Error> {
let card_data = match &req.request.payment_method_data {
PaymentMethodData::Card(card) => {
let card_holder_name = req.get_billing_full_name()?;
if req.request.setup_future_usage == Some(enums::FutureUsage::OffSession) {
format!(
r#"
<CreditCard Registered="False">
<TokeniseAlgorithmID>2</TokeniseAlgorithmID>
<CardNumber>{}</CardNumber>
<ExpM>{}</ExpM>
<ExpY>{}</ExpY>
<CVN>{}</CVN>
<CardHolderName>{}</CardHolderName>
</CreditCard>
"#,
card.card_number.get_card_no(),
card.card_exp_month.peek(),
card.get_expiry_year_4_digit().peek(),
card.card_cvc.peek(),
card_holder_name.peek(),
)
} else {
format!(
r#"
<CreditCard Registered="False">
<CardNumber>{}</CardNumber>
<ExpM>{}</ExpM>
<ExpY>{}</ExpY>
<CVN>{}</CVN>
<CardHolderName>{}</CardHolderName>
</CreditCard>
"#,
card.card_number.get_card_no(),
card.card_exp_month.peek(),
card.get_expiry_year_4_digit().peek(),
card.card_cvc.peek(),
card_holder_name.peek(),
)
}
}
PaymentMethodData::MandatePayment => {
format!(
r#"
<CreditCard>
<TokeniseAlgorithmID>2</TokeniseAlgorithmID>
<CardNumber>{}</CardNumber>
</CreditCard>
"#,
req.request.get_connector_mandate_id()?
)
}
_ => {
return Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Bambora APAC"),
))?
}
};
Ok(card_data)
}
fn get_transaction_type(capture_method: Option<enums::CaptureMethod>) -> Result<u8, Error> {
match capture_method {
Some(enums::CaptureMethod::Automatic) | None => Ok(1),
Some(enums::CaptureMethod::Manual) => Ok(2),
_ => Err(errors::ConnectorError::CaptureMethodNotSupported)?,
}
}
pub struct BamboraapacAuthType {
username: Secret<String>,
password: Secret<String>,
account_number: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BamboraapacAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
username: api_key.to_owned(),
password: api_secret.to_owned(),
account_number: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Envelope")]
#[serde(rename_all = "PascalCase")]
pub struct BamboraapacPaymentsResponse {
body: BodyResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct BodyResponse {
submit_single_payment_response: SubmitSinglePaymentResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSinglePaymentResponse {
submit_single_payment_result: SubmitSinglePaymentResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSinglePaymentResult {
response: PaymentResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PaymentResponse {
response_code: u8,
receipt: String,
credit_card_token: Option<String>,
declined_code: Option<String>,
declined_message: Option<String>,
}
fn get_attempt_status(
response_code: u8,
capture_method: Option<enums::CaptureMethod>,
) -> enums::AttemptStatus {
match response_code {
0 => match capture_method {
Some(enums::CaptureMethod::Automatic) | None => enums::AttemptStatus::Charged,
Some(enums::CaptureMethod::Manual) => enums::AttemptStatus::Authorized,
_ => enums::AttemptStatus::Pending,
},
1 => enums::AttemptStatus::Failure,
_ => enums::AttemptStatus::Pending,
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BamboraapacPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BamboraapacPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_code = item
.response
.body
.submit_single_payment_response
.submit_single_payment_result
.response
.response_code;
let connector_transaction_id = item
.response
.body
.submit_single_payment_response
.submit_single_payment_result
.response
.receipt;
let mandate_reference =
if item.data.request.setup_future_usage == Some(enums::FutureUsage::OffSession) {
let connector_mandate_id = item
.response
.body
.submit_single_payment_response
.submit_single_payment_result
.response
.credit_card_token;
Some(MandateReference {
connector_mandate_id,
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})
} else {
None
};
// transaction approved
if response_code == 0 {
Ok(Self {
status: get_attempt_status(response_code, item.data.request.capture_method),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
connector_transaction_id.to_owned(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(connector_transaction_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
// transaction failed
else {
let code = item
.response
.body
.submit_single_payment_response
.submit_single_payment_result
.response
.declined_code
.unwrap_or(NO_ERROR_CODE.to_string());
let declined_message = item
.response
.body
.submit_single_payment_response
.submit_single_payment_result
.response
.declined_message
.unwrap_or(NO_ERROR_MESSAGE.to_string());
Ok(Self {
status: get_attempt_status(response_code, item.data.request.capture_method),
response: Err(ErrorResponse {
status_code: item.http_code,
code,
message: declined_message.to_owned(),
reason: Some(declined_message),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
pub fn get_setup_mandate_body(req: &types::SetupMandateRouterData) -> Result<Vec<u8>, Error> {
let card_holder_name = req.get_billing_full_name()?;
let auth_details = BamboraapacAuthType::try_from(&req.connector_auth_type)?;
let body = match &req.request.payment_method_data {
PaymentMethodData::Card(card) => {
format!(
r#"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:sipp="http://www.ippayments.com.au/interface/api/sipp">
<soapenv:Header/>
<soapenv:Body>
<sipp:TokeniseCreditCard>
<sipp:tokeniseCreditCardXML>
<![CDATA[
<TokeniseCreditCard>
<CardNumber>{}</CardNumber>
<ExpM>{}</ExpM>
<ExpY>{}</ExpY>
<CardHolderName>{}</CardHolderName>
<TokeniseAlgorithmID>2</TokeniseAlgorithmID>
<UserName>{}</UserName>
<Password>{}</Password>
</TokeniseCreditCard>
]]>
</sipp:tokeniseCreditCardXML>
</sipp:TokeniseCreditCard>
</soapenv:Body>
</soapenv:Envelope>
"#,
card.card_number.get_card_no(),
card.card_exp_month.peek(),
card.get_expiry_year_4_digit().peek(),
card_holder_name.peek(),
auth_details.username.peek(),
auth_details.password.peek(),
)
}
_ => {
return Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Bambora APAC"),
))?;
}
};
Ok(body.as_bytes().to_vec())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Envelope")]
#[serde(rename_all = "PascalCase")]
pub struct BamboraapacMandateResponse {
body: MandateBodyResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct MandateBodyResponse {
tokenise_credit_card_response: TokeniseCreditCardResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct TokeniseCreditCardResponse {
tokenise_credit_card_result: TokeniseCreditCardResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct TokeniseCreditCardResult {
tokenise_credit_card_response: MandateResponseBody,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct MandateResponseBody {
return_value: u8,
token: Option<String>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BamboraapacMandateResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
> for RouterData<F, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BamboraapacMandateResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_code = item
.response
.body
.tokenise_credit_card_response
.tokenise_credit_card_result
.tokenise_credit_card_response
.return_value;
let connector_mandate_id = item
.response
.body
.tokenise_credit_card_response
.tokenise_credit_card_result
.tokenise_credit_card_response
.token
.ok_or(errors::ConnectorError::MissingConnectorMandateID)?;
// transaction approved
if response_code == 0 {
Ok(Self {
status: enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(Some(MandateReference {
connector_mandate_id: Some(connector_mandate_id),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
// transaction failed
else {
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
status_code: item.http_code,
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
// capture body in soap format
pub fn get_capture_body(
req: &BamboraapacRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Vec<u8>, Error> {
let receipt = req.router_data.request.connector_transaction_id.to_owned();
let auth_details = BamboraapacAuthType::try_from(&req.router_data.connector_auth_type)?;
let body = format!(
r#"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Body>
<dts:SubmitSingleCapture>
<dts:trnXML>
<![CDATA[
<Capture>
<Receipt>{}</Receipt>
<Amount>{}</Amount>
<Security>
<UserName>{}</UserName>
<Password>{}</Password>
</Security>
</Capture>
]]>
</dts:trnXML>
</dts:SubmitSingleCapture>
</soapenv:Body>
</soapenv:Envelope>
"#,
receipt,
req.amount,
auth_details.username.peek(),
auth_details.password.peek(),
);
Ok(body.as_bytes().to_vec())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Envelope")]
#[serde(rename_all = "PascalCase")]
pub struct BamboraapacCaptureResponse {
body: CaptureBodyResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CaptureBodyResponse {
submit_single_capture_response: SubmitSingleCaptureResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSingleCaptureResponse {
submit_single_capture_result: SubmitSingleCaptureResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSingleCaptureResult {
response: CaptureResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CaptureResponse {
response_code: u8,
receipt: String,
declined_code: Option<String>,
declined_message: Option<String>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BamboraapacCaptureResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BamboraapacCaptureResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_code = item
.response
.body
.submit_single_capture_response
.submit_single_capture_result
.response
.response_code;
let connector_transaction_id = item
.response
.body
.submit_single_capture_response
.submit_single_capture_result
.response
.receipt;
// storing receipt_id of authorize to metadata for future usage
let connector_metadata = Some(serde_json::json!(BamboraapacMeta {
authorize_id: item.data.request.connector_transaction_id.to_owned()
}));
// transaction approved
if response_code == 0 {
Ok(Self {
status: enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
connector_transaction_id.to_owned(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(connector_transaction_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
// transaction failed
else {
let code = item
.response
.body
.submit_single_capture_response
.submit_single_capture_result
.response
.declined_code
.unwrap_or(NO_ERROR_CODE.to_string());
let declined_message = item
.response
.body
.submit_single_capture_response
.submit_single_capture_result
.response
.declined_message
.unwrap_or(NO_ERROR_MESSAGE.to_string());
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
status_code: item.http_code,
code,
message: declined_message.to_owned(),
reason: Some(declined_message),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
// refund body in soap format
pub fn get_refund_body(
req: &BamboraapacRouterData<&types::RefundExecuteRouterData>,
) -> Result<Vec<u8>, Error> {
let receipt = req.router_data.request.connector_transaction_id.to_owned();
let auth_details = BamboraapacAuthType::try_from(&req.router_data.connector_auth_type)?;
let body = format!(
r#"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Header/>
<soapenv:Body>
<dts:SubmitSingleRefund>
<dts:trnXML>
<![CDATA[
<Refund>
<CustRef>{}</CustRef>
<Receipt>{}</Receipt>
<Amount>{}</Amount>
<Security>
<UserName>{}</UserName>
<Password>{}</Password>
</Security>
</Refund>
]]>
</dts:trnXML>
</dts:SubmitSingleRefund>
</soapenv:Body>
</soapenv:Envelope>
"#,
req.router_data.request.refund_id.to_owned(),
receipt,
req.amount,
auth_details.username.peek(),
auth_details.password.peek(),
);
Ok(body.as_bytes().to_vec())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Envelope")]
#[serde(rename_all = "PascalCase")]
pub struct BamboraapacRefundsResponse {
body: RefundBodyResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct RefundBodyResponse {
submit_single_refund_response: SubmitSingleRefundResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSingleRefundResponse {
submit_single_refund_result: SubmitSingleRefundResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSingleRefundResult {
response: RefundResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct RefundResponse {
response_code: u8,
receipt: String,
declined_code: Option<String>,
declined_message: Option<String>,
}
fn get_status(item: u8) -> enums::RefundStatus {
match item {
0 => enums::RefundStatus::Success,
1 => enums::RefundStatus::Failure,
_ => enums::RefundStatus::Pending,
}
}
impl<F> TryFrom<ResponseRouterData<F, BamboraapacRefundsResponse, RefundsData, RefundsResponseData>>
for RouterData<F, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BamboraapacRefundsResponse, RefundsData, RefundsResponseData>,
) -> Result<Self, Self::Error> {
let response_code = item
.response
.body
.submit_single_refund_response
.submit_single_refund_result
.response
.response_code;
let connector_refund_id = item
.response
.body
.submit_single_refund_response
.submit_single_refund_result
.response
.receipt;
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: connector_refund_id.to_owned(),
refund_status: get_status(response_code),
}),
..item.data
})
}
}
pub fn get_payment_sync_body(req: &types::PaymentsSyncRouterData) -> Result<Vec<u8>, Error> {
let auth_details = BamboraapacAuthType::try_from(&req.connector_auth_type)?;
let connector_transaction_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
let body = format!(
r#"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Header/>
<soapenv:Body>
<dts:QueryTransaction>
<dts:queryXML>
<![CDATA[
<QueryTransaction>
<Criteria>
<AccountNumber>{}</AccountNumber>
<TrnStartTimestamp>2024-06-23 00:00:00</TrnStartTimestamp>
<TrnEndTimestamp>2099-12-31 23:59:59</TrnEndTimestamp>
<Receipt>{}</Receipt>
</Criteria>
<Security>
<UserName>{}</UserName>
<Password>{}</Password>
</Security>
</QueryTransaction>
]]>
</dts:queryXML>
</dts:QueryTransaction>
</soapenv:Body>
</soapenv:Envelope>
"#,
auth_details.account_number.peek(),
connector_transaction_id,
auth_details.username.peek(),
auth_details.password.peek(),
);
Ok(body.as_bytes().to_vec())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Envelope")]
#[serde(rename_all = "PascalCase")]
pub struct BamboraapacSyncResponse {
body: SyncBodyResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SyncBodyResponse {
query_transaction_response: QueryTransactionResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct QueryTransactionResponse {
query_transaction_result: QueryTransactionResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct QueryTransactionResult {
query_response: QueryResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct QueryResponse {
response: SyncResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SyncResponse {
response_code: u8,
receipt: String,
declined_code: Option<String>,
declined_message: Option<String>,
}
impl<F>
TryFrom<ResponseRouterData<F, BamboraapacSyncResponse, PaymentsSyncData, PaymentsResponseData>>
for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BamboraapacSyncResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_code = item
.response
.body
.query_transaction_response
.query_transaction_result
.query_response
.response
.response_code;
let connector_transaction_id = item
.response
.body
.query_transaction_response
.query_transaction_result
.query_response
.response
.receipt;
// transaction approved
if response_code == 0 {
Ok(Self {
status: get_attempt_status(response_code, item.data.request.capture_method),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
connector_transaction_id.to_owned(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(connector_transaction_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
// transaction failed
else {
let code = item
.response
.body
.query_transaction_response
.query_transaction_result
.query_response
.response
.declined_code
.unwrap_or(NO_ERROR_CODE.to_string());
let declined_message = item
.response
.body
.query_transaction_response
.query_transaction_result
.query_response
.response
.declined_message
.unwrap_or(NO_ERROR_MESSAGE.to_string());
Ok(Self {
status: get_attempt_status(response_code, item.data.request.capture_method),
response: Err(ErrorResponse {
status_code: item.http_code,
code,
message: declined_message.to_owned(),
reason: Some(declined_message),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
pub fn get_refund_sync_body(req: &types::RefundSyncRouterData) -> Result<Vec<u8>, Error> {
let auth_details = BamboraapacAuthType::try_from(&req.connector_auth_type)?;
let body = format!(
r#"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Header/>
<soapenv:Body>
<dts:QueryTransaction>
<dts:queryXML>
<![CDATA[
<QueryTransaction>
<Criteria>
<AccountNumber>{}</AccountNumber>
<TrnStartTimestamp>2024-06-23 00:00:00</TrnStartTimestamp>
<TrnEndTimestamp>2099-12-31 23:59:59</TrnEndTimestamp>
<CustRef>{}</CustRef>
</Criteria>
<Security>
<UserName>{}</UserName>
<Password>{}</Password>
</Security>
</QueryTransaction>
]]>
</dts:queryXML>
</dts:QueryTransaction>
</soapenv:Body>
</soapenv:Envelope>
"#,
auth_details.account_number.peek(),
req.request.refund_id,
auth_details.username.peek(),
auth_details.password.peek(),
);
Ok(body.as_bytes().to_vec())
}
impl<F> TryFrom<ResponseRouterData<F, BamboraapacSyncResponse, RefundsData, RefundsResponseData>>
for RouterData<F, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BamboraapacSyncResponse, RefundsData, RefundsResponseData>,
) -> Result<Self, Self::Error> {
let response_code = item
.response
.body
.query_transaction_response
.query_transaction_result
.query_response
.response
.response_code;
let connector_refund_id = item
.response
.body
.query_transaction_response
.query_transaction_result
.query_response
.response
.receipt;
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: connector_refund_id.to_owned(),
refund_status: get_status(response_code),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct BamboraapacErrorResponse {
pub declined_code: Option<String>,
pub declined_message: Option<String>,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 7096
}
|
large_file_191637130357022892
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs
</path>
<file>
use std::collections::HashMap;
use common_enums::{enums, CaptureMethod};
use common_utils::{errors::CustomResult, pii, types::StringMajorUnit};
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::{consts, errors};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{is_refund_failure, RouterData as _},
};
pub struct AmazonpayRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for AmazonpayRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmazonpayFinalizeRequest {
charge_amount: ChargeAmount,
shipping_address: AddressDetails,
payment_intent: PaymentIntent,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ChargeAmount {
amount: StringMajorUnit,
currency_code: common_enums::Currency,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AddressDetails {
name: Secret<String>,
address_line_1: Secret<String>,
address_line_2: Option<Secret<String>>,
address_line_3: Option<Secret<String>>,
city: String,
state_or_region: Secret<String>,
postal_code: Secret<String>,
country_code: Option<common_enums::CountryAlpha2>,
phone_number: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq)]
pub enum PaymentIntent {
AuthorizeWithCapture,
}
fn get_amazonpay_capture_type(
item: Option<CaptureMethod>,
) -> CustomResult<PaymentIntent, errors::ConnectorError> {
match item {
Some(CaptureMethod::Automatic) | None => Ok(PaymentIntent::AuthorizeWithCapture),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
impl TryFrom<&AmazonpayRouterData<&PaymentsAuthorizeRouterData>> for AmazonpayFinalizeRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AmazonpayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let charge_amount = ChargeAmount {
amount: item.amount.clone(),
currency_code: item.router_data.request.currency,
};
let shipping_address = AddressDetails {
name: item.router_data.get_required_shipping_full_name()?,
address_line_1: item.router_data.get_required_shipping_line1()?,
address_line_2: item.router_data.get_optional_shipping_line2(),
address_line_3: item.router_data.get_optional_shipping_line3(),
city: item.router_data.get_required_shipping_city()?,
state_or_region: item.router_data.get_required_shipping_state()?,
postal_code: item.router_data.get_required_shipping_zip()?,
country_code: item.router_data.get_optional_shipping_country(),
phone_number: item.router_data.get_required_shipping_phone_number()?,
};
let payment_intent = get_amazonpay_capture_type(item.router_data.request.capture_method)?;
Ok(Self {
charge_amount,
shipping_address,
payment_intent,
})
}
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmazonpayFinalizeResponse {
checkout_session_id: String,
web_checkout_details: WebCheckoutDetails,
product_type: Option<String>,
payment_details: Option<PaymentDetails>,
cart_details: CartDetails,
charge_permission_type: String,
order_type: Option<String>,
recurring_metadata: Option<RecurringMetadata>,
payment_method_on_file_metadata: Option<String>,
processor_specifications: Option<String>,
merchant_details: Option<String>,
merchant_metadata: Option<MerchantMetadata>,
supplementary_data: Option<String>,
buyer: Option<BuyerDetails>,
billing_address: Option<AddressDetails>,
payment_preferences: Option<String>,
status_details: FinalizeStatusDetails,
shipping_address: Option<AddressDetails>,
platform_id: Option<String>,
charge_permission_id: String,
charge_id: String,
constraints: Option<String>,
creation_timestamp: String,
expiration_timestamp: Option<String>,
store_id: Option<String>,
provider_metadata: Option<ProviderMetadata>,
release_environment: Option<ReleaseEnvironment>,
checkout_button_text: Option<String>,
delivery_specifications: Option<DeliverySpecifications>,
tokens: Option<String>,
disbursement_details: Option<String>,
channel_type: Option<String>,
payment_processing_meta_data: PaymentProcessingMetaData,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct WebCheckoutDetails {
checkout_review_return_url: Option<String>,
checkout_result_return_url: Option<String>,
amazon_pay_redirect_url: Option<String>,
authorize_result_return_url: Option<String>,
sign_in_return_url: Option<String>,
sign_in_cancel_url: Option<String>,
checkout_error_url: Option<String>,
sign_in_error_url: Option<String>,
amazon_pay_decline_url: Option<String>,
checkout_cancel_url: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentDetails {
payment_intent: String,
can_handle_pending_authorization: bool,
charge_amount: ChargeAmount,
total_order_amount: ChargeAmount,
presentment_currency: String,
soft_descriptor: String,
allow_overcharge: bool,
extend_expiration: bool,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CartDetails {
line_items: Vec<String>,
delivery_options: Vec<DeliveryOptions>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DeliveryOptions {
id: String,
price: ChargeAmount,
shipping_method: ShippingMethod,
is_default: bool,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ShippingMethod {
shipping_method_name: String,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RecurringMetadata {
frequency: Frequency,
amount: ChargeAmount,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Frequency {
unit: String,
value: String,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct BuyerDetails {
buyer_id: Secret<String>,
name: Secret<String>,
email: pii::Email,
phone_number: Secret<String>,
prime_membership_types: Vec<String>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FinalizeStatusDetails {
state: FinalizeState,
reason_code: Option<String>,
reason_description: Option<String>,
last_updated_timestamp: String,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub enum FinalizeState {
Open,
Completed,
Canceled,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DeliverySpecifications {
special_restrictions: Vec<String>,
address_restrictions: AddressRestrictions,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AddressRestrictions {
r#type: String,
restrictions: HashMap<String, Restriction>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Restriction {
pub states_or_regions: Vec<Secret<String>>,
pub zip_codes: Vec<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentProcessingMetaData {
payment_processing_model: String,
}
impl From<FinalizeState> for common_enums::AttemptStatus {
fn from(item: FinalizeState) -> Self {
match item {
FinalizeState::Open => Self::Pending,
FinalizeState::Completed => Self::Charged,
FinalizeState::Canceled => Self::Failure,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AmazonpayFinalizeResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AmazonpayFinalizeResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.status_details.state {
FinalizeState::Canceled => {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "Checkout was not successfully completed".to_owned(),
reason: Some("Checkout was not successfully completed due to buyer abandoment, payment decline, or because checkout wasn't confirmed with Finalize Checkout Session.".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.checkout_session_id),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
FinalizeState::Open
| FinalizeState::Completed => {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status_details.state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.charge_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.checkout_session_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
}
}
pub struct AmazonpayAuthType {
pub(super) public_key: Secret<String>,
pub(super) private_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AmazonpayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
public_key: api_key.to_owned(),
private_key: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub enum AmazonpayPaymentStatus {
AuthorizationInitiated,
Authorized,
Canceled,
Captured,
CaptureInitiated,
Declined,
}
impl From<AmazonpayPaymentStatus> for common_enums::AttemptStatus {
fn from(item: AmazonpayPaymentStatus) -> Self {
match item {
AmazonpayPaymentStatus::AuthorizationInitiated => Self::Pending,
AmazonpayPaymentStatus::Authorized => Self::Authorized,
AmazonpayPaymentStatus::Canceled => Self::Voided,
AmazonpayPaymentStatus::Captured => Self::Charged,
AmazonpayPaymentStatus::CaptureInitiated => Self::CaptureInitiated,
AmazonpayPaymentStatus::Declined => Self::CaptureFailed,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmazonpayPaymentsResponse {
charge_id: String,
charge_amount: ChargeAmount,
charge_permission_id: String,
capture_amount: Option<ChargeAmount>,
refunded_amount: Option<ChargeAmount>,
soft_descriptor: Option<String>,
provider_metadata: Option<ProviderMetadata>,
converted_amount: Option<ChargeAmount>,
conversion_rate: Option<f64>,
channel: Option<String>,
charge_initiator: Option<String>,
status_details: PaymentsStatusDetails,
creation_timestamp: String,
expiration_timestamp: String,
release_environment: Option<ReleaseEnvironment>,
merchant_metadata: Option<MerchantMetadata>,
platform_id: Option<String>,
web_checkout_details: Option<WebCheckoutDetails>,
disbursement_details: Option<String>,
payment_method: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ProviderMetadata {
provider_reference_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentsStatusDetails {
state: AmazonpayPaymentStatus,
reason_code: Option<String>,
reason_description: Option<String>,
last_updated_timestamp: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ReleaseEnvironment {
Sandbox,
Live,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MerchantMetadata {
merchant_reference_id: Option<String>,
merchant_store_name: Option<String>,
note_to_buyer: Option<String>,
custom_information: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, AmazonpayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AmazonpayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.status_details.state {
AmazonpayPaymentStatus::Canceled => {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "Charge was canceled by Amazon or by the merchant".to_owned(),
reason: Some("Charge was canceled due to expiration, Amazon, buyer, merchant action, or charge permission cancellation.".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.charge_id),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
AmazonpayPaymentStatus::Declined => {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "The authorization or capture was declined".to_owned(),
reason: Some("Charge was declined due to soft/hard decline, Amazon rejection, or internal processing failure.".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.charge_id),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
_ => {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status_details.state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.charge_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AmazonpayRefundRequest {
pub refund_amount: ChargeAmount,
pub charge_id: String,
}
impl<F> TryFrom<&AmazonpayRouterData<&RefundsRouterData<F>>> for AmazonpayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AmazonpayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let refund_amount = ChargeAmount {
amount: item.amount.clone(),
currency_code: item.router_data.request.currency,
};
let charge_id = item.router_data.request.connector_transaction_id.clone();
Ok(Self {
refund_amount,
charge_id,
})
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum RefundStatus {
RefundInitiated,
Refunded,
Declined,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::RefundInitiated => Self::Pending,
RefundStatus::Refunded => Self::Success,
RefundStatus::Declined => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
refund_id: String,
charge_id: String,
creation_timestamp: String,
refund_amount: ChargeAmount,
status_details: RefundStatusDetails,
soft_descriptor: String,
release_environment: ReleaseEnvironment,
disbursement_details: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundStatusDetails {
state: RefundStatus,
reason_code: Option<String>,
reason_description: Option<String>,
last_updated_timestamp: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
match item.response.status_details.state {
RefundStatus::Declined => {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "Amazon has declined the refund.".to_owned(),
reason: Some("Amazon has declined the refund because maximum amount has been refunded or there was some other issue.".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.charge_id),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
_ => {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund_id,
refund_status: enums::RefundStatus::from(item.response.status_details.state),
}),
..item.data
})
}
}
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status_details.state);
let response = if is_refund_failure(refund_status) {
Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "Amazon has declined the refund.".to_owned(),
reason: Some("Amazon has declined the refund because maximum amount has been refunded or there was some other issue.".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.refund_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.refund_id.to_string(),
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmazonpayErrorResponse {
pub reason_code: String,
pub message: String,
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4425
}
|
large_file_-5839966231066513473
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: smithy
File: crates/smithy/src/lib.rs
</path>
<file>
// crates/smithy/lib.rs - Fixed with proper optional type handling in flattening
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use smithy_core::{SmithyConstraint, SmithyEnumVariant, SmithyField};
use syn::{parse_macro_input, Attribute, DeriveInput, Fields, Lit, Meta, Variant};
/// Derive macro for generating Smithy models from Rust structs and enums
#[proc_macro_derive(SmithyModel, attributes(smithy))]
pub fn derive_smithy_model(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
match generate_smithy_impl(&input) {
Ok(tokens) => tokens.into(),
Err(err) => err.to_compile_error().into(),
}
}
fn generate_smithy_impl(input: &DeriveInput) -> syn::Result<TokenStream2> {
let name = &input.ident;
let (namespace, is_mixin) = extract_namespace_and_mixin(&input.attrs)?;
match &input.data {
syn::Data::Struct(data_struct) => {
generate_struct_impl(name, &namespace, data_struct, &input.attrs, is_mixin)
}
syn::Data::Enum(data_enum) => generate_enum_impl(name, &namespace, data_enum, &input.attrs),
_ => Err(syn::Error::new_spanned(
input,
"SmithyModel can only be derived for structs and enums",
)),
}
}
fn generate_struct_impl(
name: &syn::Ident,
namespace: &str,
data_struct: &syn::DataStruct,
attrs: &[Attribute],
is_mixin: bool,
) -> syn::Result<TokenStream2> {
let fields = extract_fields(&data_struct.fields)?;
let struct_doc = extract_documentation(attrs);
let struct_doc_expr = struct_doc
.as_ref()
.map(|doc| quote! { Some(#doc.to_string()) })
.unwrap_or(quote! { None });
let field_implementations = fields.iter().map(|field| {
let field_name = &field.name;
let value_type = &field.value_type;
let documentation = &field.documentation;
let constraints = &field.constraints;
let optional = field.optional;
let flatten = field.flatten;
if flatten {
// Extract the inner type from Option<T> if it's an optional type
let inner_type = if value_type.starts_with("Option<") && value_type.ends_with('>') {
let start_idx = "Option<".len();
let end_idx = value_type.len() - 1;
&value_type[start_idx..end_idx]
} else {
value_type
};
let inner_type_ident = syn::parse_str::<syn::Type>(inner_type).unwrap();
// For flattened fields, we merge the fields from the inner type
// but we don't add the field itself to the structure
quote! {
{
let flattened_model = <#inner_type_ident as smithy_core::SmithyModelGenerator>::generate_smithy_model();
let flattened_struct_name = stringify!(#inner_type_ident).to_string();
for (shape_name, shape) in flattened_model.shapes {
if shape_name == flattened_struct_name {
match shape {
smithy_core::SmithyShape::Structure { members: flattened_members, .. } |
smithy_core::SmithyShape::Union { members: flattened_members, .. } => {
members.extend(flattened_members);
}
_ => {
// Potentially handle other shapes or log a warning
}
}
} else {
shapes.insert(shape_name, shape);
}
}
}
}
} else {
let field_doc = documentation
.as_ref()
.map(|doc| quote! { Some(#doc.to_string()) })
.unwrap_or(quote! { None });
let mut all_constraints = constraints.clone();
if !optional && !all_constraints.iter().any(|c| matches!(c, SmithyConstraint::Required)) {
all_constraints.push(SmithyConstraint::Required);
}
let traits = if all_constraints.is_empty() {
quote! { vec![] }
} else {
let trait_tokens = all_constraints
.iter()
.map(|constraint| match constraint {
SmithyConstraint::Pattern(pattern) => quote! {
smithy_core::SmithyTrait::Pattern { pattern: #pattern.to_string() }
},
SmithyConstraint::Range(min, max) => {
let min_expr = min.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None });
let max_expr = max.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None });
quote! {
smithy_core::SmithyTrait::Range {
min: #min_expr,
max: #max_expr
}
}
},
SmithyConstraint::Length(min, max) => {
let min_expr = min.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None });
let max_expr = max.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None });
quote! {
smithy_core::SmithyTrait::Length {
min: #min_expr,
max: #max_expr
}
}
},
SmithyConstraint::Required => quote! {
smithy_core::SmithyTrait::Required
},
SmithyConstraint::HttpLabel => quote! {
smithy_core::SmithyTrait::HttpLabel
},
SmithyConstraint::HttpQuery(name) => quote! {
smithy_core::SmithyTrait::HttpQuery { name: #name.to_string() }
},
})
.collect::<Vec<_>>();
quote! { vec![#(#trait_tokens),*] }
};
quote! {
{
let (target_type, new_shapes) = smithy_core::types::resolve_type_and_generate_shapes(#value_type, &mut shapes).unwrap();
shapes.extend(new_shapes);
members.insert(#field_name.to_string(), smithy_core::SmithyMember {
target: target_type,
documentation: #field_doc,
traits: #traits,
});
}
}
}
});
let traits_expr = if is_mixin {
quote! { vec![smithy_core::SmithyTrait::Mixin] }
} else {
quote! { vec![] }
};
let expanded = quote! {
impl smithy_core::SmithyModelGenerator for #name {
fn generate_smithy_model() -> smithy_core::SmithyModel {
let mut shapes = std::collections::HashMap::new();
let mut members = std::collections::HashMap::new();
#(#field_implementations;)*
let shape = smithy_core::SmithyShape::Structure {
members,
documentation: #struct_doc_expr,
traits: #traits_expr
};
shapes.insert(stringify!(#name).to_string(), shape);
smithy_core::SmithyModel {
namespace: #namespace.to_string(),
shapes
}
}
}
};
Ok(expanded)
}
fn generate_enum_impl(
name: &syn::Ident,
namespace: &str,
data_enum: &syn::DataEnum,
attrs: &[Attribute],
) -> syn::Result<TokenStream2> {
let variants = extract_enum_variants(&data_enum.variants)?;
let serde_enum_attrs = parse_serde_enum_attributes(attrs)?;
let enum_doc = extract_documentation(attrs);
let enum_doc_expr = enum_doc
.as_ref()
.map(|doc| quote! { Some(#doc.to_string()) })
.unwrap_or(quote! { None });
// Check if this is a string enum (all variants are unit variants) or a union
let is_string_enum = variants.iter().all(|v| v.fields.is_empty());
if is_string_enum {
// Generate as Smithy enum
let variant_implementations = variants
.iter()
.map(|variant| {
let variant_name = &variant.name;
let variant_doc = variant
.documentation
.as_ref()
.map(|doc| quote! { Some(#doc.to_string()) })
.unwrap_or(quote! { None });
// Apply serde rename transformation if specified
let rename_all = serde_enum_attrs.rename_all.as_deref();
let transformed_name = if let Some(rename_pattern) = rename_all {
// Generate the transformation at compile time
let transformed = transform_variant_name(variant_name, Some(rename_pattern));
quote! { #transformed.to_string() }
} else {
quote! { #variant_name.to_string() }
};
quote! {
enum_values.insert(#transformed_name, smithy_core::SmithyEnumValue {
name: #transformed_name,
documentation: #variant_doc,
is_default: false,
});
}
})
.collect::<Vec<_>>();
let expanded = quote! {
impl smithy_core::SmithyModelGenerator for #name {
fn generate_smithy_model() -> smithy_core::SmithyModel {
let mut shapes = std::collections::HashMap::new();
let mut enum_values = std::collections::HashMap::new();
#(#variant_implementations)*
let shape = smithy_core::SmithyShape::Enum {
values: enum_values,
documentation: #enum_doc_expr,
traits: vec![]
};
shapes.insert(stringify!(#name).to_string(), shape);
smithy_core::SmithyModel {
namespace: #namespace.to_string(),
shapes
}
}
}
};
Ok(expanded)
} else {
// Generate as Smithy union
let variant_implementations = variants
.iter()
.filter_map(|variant| {
let variant_name = &variant.name;
let variant_doc = variant
.documentation
.as_ref()
.map(|doc| quote! { Some(#doc.to_string()) })
.unwrap_or(quote! { None });
let target_type_expr = if variant.fields.is_empty() {
// If there are no fields with `value_type`, this variant should be skipped.
return None;
} else if variant.fields.len() == 1 {
// Single field - reference the type directly instead of creating a wrapper
let field = &variant.fields[0];
let field_value_type = &field.value_type;
if field_value_type.is_empty() {
return None;
}
quote! {
{
let (target_type, new_shapes) = smithy_core::types::resolve_type_and_generate_shapes(#field_value_type, &mut shapes).unwrap();
shapes.extend(new_shapes);
target_type
}
}
} else {
// Multiple fields - create an inline structure
let inline_struct_members = variant.fields.iter().map(|field| {
let field_name = &field.name;
let field_value_type = &field.value_type;
let field_doc = field
.documentation
.as_ref()
.map(|doc| quote! { Some(#doc.to_string()) })
.unwrap_or(quote! { None });
let mut field_constraints = field.constraints.clone();
if !field.optional && !field_constraints.iter().any(|c| matches!(c, SmithyConstraint::Required)) {
field_constraints.push(SmithyConstraint::Required);
}
let field_traits = if field_constraints.is_empty() {
quote! { vec![] }
} else {
let trait_tokens = field_constraints
.iter()
.map(|constraint| match constraint {
SmithyConstraint::Pattern(pattern) => quote! {
smithy_core::SmithyTrait::Pattern { pattern: #pattern.to_string() }
},
SmithyConstraint::Range(min, max) => {
let min_expr = min.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None });
let max_expr = max.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None });
quote! {
smithy_core::SmithyTrait::Range {
min: #min_expr,
max: #max_expr
}
}
},
SmithyConstraint::Length(min, max) => {
let min_expr = min.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None });
let max_expr = max.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None });
quote! {
smithy_core::SmithyTrait::Length {
min: #min_expr,
max: #max_expr
}
}
},
SmithyConstraint::Required => quote! {
smithy_core::SmithyTrait::Required
},
SmithyConstraint::HttpLabel => quote! {
smithy_core::SmithyTrait::HttpLabel
},
SmithyConstraint::HttpQuery(name) => quote! {
smithy_core::SmithyTrait::HttpQuery { name: #name.to_string() }
},
})
.collect::<Vec<_>>();
quote! { vec![#(#trait_tokens),*] }
};
quote! {
{
let (field_target, field_shapes) = smithy_core::types::resolve_type_and_generate_shapes(#field_value_type, &mut shapes).unwrap();
shapes.extend(field_shapes);
inline_members.insert(#field_name.to_string(), smithy_core::SmithyMember {
target: field_target,
documentation: #field_doc,
traits: #field_traits,
});
}
}
});
quote! {
{
let inline_struct_name = format!("{}{}Data", stringify!(#name), #variant_name);
let mut inline_members = std::collections::HashMap::new();
#(#inline_struct_members)*
let inline_shape = smithy_core::SmithyShape::Structure {
members: inline_members,
documentation: None,
traits: vec![],
};
shapes.insert(inline_struct_name.clone(), inline_shape);
inline_struct_name
}
}
};
// Apply serde rename transformation if specified
let rename_all = serde_enum_attrs.rename_all.as_deref();
let transformed_name = if let Some(rename_pattern) = rename_all {
// Generate the transformation at compile time
let transformed = transform_variant_name(variant_name, Some(rename_pattern));
quote! { #transformed.to_string() }
} else {
quote! { #variant_name.to_string() }
};
Some(quote! {
let target_type = #target_type_expr;
members.insert(#transformed_name, smithy_core::SmithyMember {
target: target_type,
documentation: #variant_doc,
traits: vec![]
});
})
})
.collect::<Vec<_>>();
let expanded = quote! {
impl smithy_core::SmithyModelGenerator for #name {
fn generate_smithy_model() -> smithy_core::SmithyModel {
let mut shapes = std::collections::HashMap::new();
let mut members = std::collections::HashMap::new();
#(#variant_implementations;)*
let shape = smithy_core::SmithyShape::Union {
members,
documentation: #enum_doc_expr,
traits: vec![]
};
shapes.insert(stringify!(#name).to_string(), shape);
smithy_core::SmithyModel {
namespace: #namespace.to_string(),
shapes
}
}
}
};
Ok(expanded)
}
}
fn extract_namespace_and_mixin(attrs: &[Attribute]) -> syn::Result<(String, bool)> {
for attr in attrs {
if attr.path().is_ident("smithy") {
let mut namespace = None;
let mut mixin = false;
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("namespace") {
if let Ok(value) = meta.value() {
if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() {
namespace = Some(lit_str.value());
}
}
} else if meta.path.is_ident("mixin") {
if let Ok(value) = meta.value() {
if let Ok(Lit::Bool(lit_bool)) = value.parse::<Lit>() {
mixin = lit_bool.value;
}
}
}
Ok(())
})?; // Propagate parsing errors
return Ok((
namespace.unwrap_or_else(|| "com.hyperswitch.default".to_string()),
mixin,
));
}
}
Ok(("com.hyperswitch.default".to_string(), false))
}
fn extract_fields(fields: &Fields) -> syn::Result<Vec<SmithyField>> {
let mut smithy_fields = Vec::new();
match fields {
Fields::Named(fields_named) => {
for field in &fields_named.named {
let field_name = field.ident.as_ref().unwrap().to_string();
let field_attrs = parse_smithy_field_attributes(&field.attrs)?;
let serde_attrs = parse_serde_attributes(&field.attrs)?;
if let Some(value_type) = field_attrs.value_type {
let documentation = extract_documentation(&field.attrs);
let optional = value_type.trim().starts_with("Option<");
smithy_fields.push(SmithyField {
name: field_name,
value_type,
constraints: field_attrs.constraints,
documentation,
optional,
flatten: serde_attrs.flatten,
});
}
}
}
_ => {
return Err(syn::Error::new_spanned(
fields,
"Only named fields are supported",
))
}
}
Ok(smithy_fields)
}
fn extract_enum_variants(
variants: &syn::punctuated::Punctuated<Variant, syn::token::Comma>,
) -> syn::Result<Vec<SmithyEnumVariant>> {
let mut smithy_variants = Vec::new();
for variant in variants {
let variant_name = variant.ident.to_string();
let documentation = extract_documentation(&variant.attrs);
let variant_attrs = parse_smithy_field_attributes(&variant.attrs)?;
// Extract fields from the variant
let fields = match &variant.fields {
Fields::Unit => Vec::new(),
Fields::Named(fields_named) => {
let mut variant_fields = Vec::new();
for field in &fields_named.named {
let field_name = field.ident.as_ref().unwrap().to_string();
let field_attrs = parse_smithy_field_attributes(&field.attrs)?;
if let Some(value_type) = field_attrs.value_type {
let field_documentation = extract_documentation(&field.attrs);
let optional = value_type.trim().starts_with("Option<");
variant_fields.push(SmithyField {
name: field_name,
value_type,
constraints: field_attrs.constraints,
documentation: field_documentation,
optional,
flatten: false,
});
}
}
variant_fields
}
Fields::Unnamed(fields_unnamed) => {
let mut variant_fields = Vec::new();
for (index, field) in fields_unnamed.unnamed.iter().enumerate() {
let field_name = format!("field_{}", index);
let field_attrs = parse_smithy_field_attributes(&field.attrs)?;
// For single unnamed fields, use the variant attribute if field doesn't have one
let value_type = field_attrs
.value_type
.or_else(|| variant_attrs.value_type.clone());
if let Some(value_type) = value_type {
let field_documentation = extract_documentation(&field.attrs);
let optional = value_type.trim().starts_with("Option<");
variant_fields.push(SmithyField {
name: field_name,
value_type,
constraints: field_attrs.constraints,
documentation: field_documentation,
optional,
flatten: false,
});
}
}
variant_fields
}
};
smithy_variants.push(SmithyEnumVariant {
name: variant_name,
fields,
constraints: variant_attrs.constraints,
documentation,
});
}
Ok(smithy_variants)
}
#[derive(Default)]
struct SmithyFieldAttributes {
value_type: Option<String>,
constraints: Vec<SmithyConstraint>,
}
#[derive(Default)]
struct SerdeAttributes {
flatten: bool,
}
#[derive(Default)]
struct SerdeEnumAttributes {
rename_all: Option<String>,
}
fn parse_serde_attributes(attrs: &[Attribute]) -> syn::Result<SerdeAttributes> {
let mut serde_attributes = SerdeAttributes::default();
for attr in attrs {
if attr.path().is_ident("serde") {
if let Ok(list) = attr.meta.require_list() {
if list.path.is_ident("serde") {
for item in list.tokens.clone() {
if let Some(ident) = item.to_string().split_whitespace().next() {
if ident == "flatten" {
serde_attributes.flatten = true;
}
}
}
}
}
}
}
Ok(serde_attributes)
}
fn parse_serde_enum_attributes(attrs: &[Attribute]) -> syn::Result<SerdeEnumAttributes> {
let mut serde_enum_attributes = SerdeEnumAttributes::default();
for attr in attrs {
if attr.path().is_ident("serde") {
// Use more robust parsing that handles all serde attributes
let parse_result = attr.parse_nested_meta(|meta| {
if meta.path.is_ident("rename_all") {
if let Ok(value) = meta.value() {
if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() {
serde_enum_attributes.rename_all = Some(lit_str.value());
}
}
} else if meta.path.is_ident("tag") {
// Parse and ignore the tag attribute
if let Ok(value) = meta.value() {
let _ = value.parse::<Lit>();
}
} else if meta.path.is_ident("content") {
// Parse and ignore the content attribute
if let Ok(value) = meta.value() {
let _ = value.parse::<Lit>();
}
} else if meta.path.is_ident("rename") {
// Parse and ignore the rename attribute (used for enum renaming)
if let Ok(value) = meta.value() {
let _ = value.parse::<Lit>();
}
} else if meta.path.is_ident("deny_unknown_fields") {
// Handle deny_unknown_fields (no value needed)
// This is a flag attribute with no value
} else if meta.path.is_ident("skip_serializing") {
// Handle skip_serializing
} else if meta.path.is_ident("skip_deserializing") {
// Handle skip_deserializing
} else if meta.path.is_ident("skip_serializing_if") {
// Handle skip_serializing_if
if let Ok(value) = meta.value() {
let _ = value.parse::<syn::Expr>();
}
} else if meta.path.is_ident("default") {
// Handle default attribute
// Could have a value or be a flag
if meta.value().is_ok() {
let _ = meta.value().and_then(|v| v.parse::<syn::Expr>());
}
} else if meta.path.is_ident("flatten") {
// Handle flatten (flag attribute)
} else if meta.path.is_ident("untagged") {
// Handle untagged (flag attribute)
} else if meta.path.is_ident("bound") {
// Handle bound attribute
if let Ok(value) = meta.value() {
let _ = value.parse::<Lit>();
}
}
// Silently ignore any other serde attributes to prevent parsing errors
Ok(())
});
// If parsing failed, provide a more helpful error message
if let Err(e) = parse_result {
return Err(syn::Error::new_spanned(
attr,
format!("Failed to parse serde attribute: {}. This may be due to multiple serde attributes on separate lines. Consider consolidating them into a single #[serde(...)] attribute.", e)
));
}
}
}
Ok(serde_enum_attributes)
}
fn transform_variant_name(name: &str, rename_all: Option<&str>) -> String {
match rename_all {
Some("snake_case") => to_snake_case(name),
Some("camelCase") => to_camel_case(name),
Some("kebab-case") => to_kebab_case(name),
Some("PascalCase") => name.to_string(), // No change for PascalCase
Some("SCREAMING_SNAKE_CASE") => to_screaming_snake_case(name),
Some("lowercase") => name.to_lowercase(),
Some("UPPERCASE") => name.to_uppercase(),
_ => name.to_string(), // No transformation if no rename_all or unknown pattern
}
}
fn to_snake_case(input: &str) -> String {
let mut result = String::new();
let chars = input.chars();
for ch in chars {
if ch.is_uppercase() && !result.is_empty() {
// Add underscore before uppercase letters (except the first character)
result.push('_');
}
result.push(ch.to_lowercase().next().unwrap());
}
result
}
fn to_camel_case(input: &str) -> String {
let mut result = String::new();
let mut chars = input.chars();
// First character should be lowercase
if let Some(ch) = chars.next() {
result.push(ch.to_lowercase().next().unwrap());
}
// Rest of the characters remain the same
for ch in chars {
result.push(ch);
}
result
}
fn to_kebab_case(input: &str) -> String {
let mut result = String::new();
for ch in input.chars() {
if ch.is_uppercase() && !result.is_empty() {
// Add hyphen before uppercase letters (except the first character)
result.push('-');
}
result.push(ch.to_lowercase().next().unwrap());
}
result
}
fn to_screaming_snake_case(input: &str) -> String {
let mut result = String::new();
for ch in input.chars() {
if ch.is_uppercase() && !result.is_empty() {
// Add underscore before uppercase letters (except the first character)
result.push('_');
}
result.push(ch.to_uppercase().next().unwrap());
}
result
}
fn parse_smithy_field_attributes(attrs: &[Attribute]) -> syn::Result<SmithyFieldAttributes> {
let mut field_attributes = SmithyFieldAttributes::default();
for attr in attrs {
if attr.path().is_ident("smithy") {
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("value_type") {
if let Ok(value) = meta.value() {
if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() {
field_attributes.value_type = Some(lit_str.value());
}
}
} else if meta.path.is_ident("pattern") {
if let Ok(value) = meta.value() {
if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() {
field_attributes
.constraints
.push(SmithyConstraint::Pattern(lit_str.value()));
}
}
} else if meta.path.is_ident("range") {
if let Ok(value) = meta.value() {
if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() {
let range_str = lit_str.value();
match parse_range(&range_str) {
Ok((min, max)) => {
field_attributes
.constraints
.push(SmithyConstraint::Range(min, max));
}
Err(e) => {
return Err(syn::Error::new_spanned(
&meta.path,
format!("Invalid range: {}", e),
));
}
}
}
}
} else if meta.path.is_ident("length") {
if let Ok(value) = meta.value() {
if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() {
let length_str = lit_str.value();
match parse_length(&length_str) {
Ok((min, max)) => {
field_attributes
.constraints
.push(SmithyConstraint::Length(min, max));
}
Err(e) => {
return Err(syn::Error::new_spanned(
&meta.path,
format!("Invalid length: {}", e),
));
}
}
}
}
} else if meta.path.is_ident("required") {
field_attributes
.constraints
.push(SmithyConstraint::Required);
} else if meta.path.is_ident("http_label") {
field_attributes
.constraints
.push(SmithyConstraint::HttpLabel);
} else if meta.path.is_ident("http_query") {
if let Ok(value) = meta.value() {
if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() {
field_attributes
.constraints
.push(SmithyConstraint::HttpQuery(lit_str.value()));
}
}
}
Ok(())
})?;
}
}
// Automatically add Required for http_label fields
if field_attributes
.constraints
.iter()
.any(|c| matches!(c, SmithyConstraint::HttpLabel))
&& !field_attributes
.constraints
.iter()
.any(|c| matches!(c, SmithyConstraint::Required))
{
field_attributes
.constraints
.push(SmithyConstraint::Required);
}
Ok(field_attributes)
}
fn extract_documentation(attrs: &[Attribute]) -> Option<String> {
let mut docs = Vec::new();
for attr in attrs {
if attr.path().is_ident("doc") {
if let Meta::NameValue(meta_name_value) = &attr.meta {
if let syn::Expr::Lit(expr_lit) = &meta_name_value.value {
if let Lit::Str(lit_str) = &expr_lit.lit {
docs.push(lit_str.value().trim().to_string());
}
}
}
}
}
if docs.is_empty() {
None
} else {
Some(docs.join(" "))
}
}
fn parse_range(range_str: &str) -> Result<(Option<i64>, Option<i64>), String> {
if range_str.contains("..=") {
let parts: Vec<&str> = range_str.split("..=").collect();
if parts.len() != 2 {
return Err(
"Invalid range format: must be 'min..=max', '..=max', or 'min..='".to_string(),
);
}
let min = if parts[0].is_empty() {
None
} else {
Some(
parts[0]
.parse()
.map_err(|_| format!("Invalid range min: '{}'", parts[0]))?,
)
};
let max = if parts[1].is_empty() {
None
} else {
Some(
parts[1]
.parse()
.map_err(|_| format!("Invalid range max: '{}'", parts[1]))?,
)
};
Ok((min, max))
} else if range_str.contains("..") {
let parts: Vec<&str> = range_str.split("..").collect();
if parts.len() != 2 {
return Err(
"Invalid range format: must be 'min..max', '..max', or 'min..'".to_string(),
);
}
let min = if parts[0].is_empty() {
None
} else {
Some(
parts[0]
.parse()
.map_err(|_| format!("Invalid range min: '{}'", parts[0]))?,
)
};
let max = if parts[1].is_empty() {
None
} else {
Some(
parts[1]
.parse::<i64>()
.map_err(|_| format!("Invalid range max: '{}'", parts[1]))?
- 1,
)
};
Ok((min, max))
} else {
Err("Invalid range format: must contain '..' or '..='".to_string())
}
}
fn parse_length(length_str: &str) -> Result<(Option<u64>, Option<u64>), String> {
if length_str.contains("..=") {
let parts: Vec<&str> = length_str.split("..=").collect();
if parts.len() != 2 {
return Err(
"Invalid length format: must be 'min..=max', '..=max', or 'min..='".to_string(),
);
}
let min = if parts[0].is_empty() {
None
} else {
Some(
parts[0]
.parse()
.map_err(|_| format!("Invalid length min: '{}'", parts[0]))?,
)
};
let max = if parts[1].is_empty() {
None
} else {
Some(
parts[1]
.parse()
.map_err(|_| format!("Invalid length max: '{}'", parts[1]))?,
)
};
Ok((min, max))
} else if length_str.contains("..") {
let parts: Vec<&str> = length_str.split("..").collect();
if parts.len() != 2 {
return Err(
"Invalid length format: must be 'min..max', '..max', or 'min..'".to_string(),
);
}
let min = if parts[0].is_empty() {
None
} else {
Some(
parts[0]
.parse()
.map_err(|_| format!("Invalid length min: '{}'", parts[0]))?,
)
};
let max = if parts[1].is_empty() {
None
} else {
Some(
parts[1]
.parse::<u64>()
.map_err(|_| format!("Invalid length max: '{}'", parts[1]))?
- 1,
)
};
Ok((min, max))
} else {
Err("Invalid length format: must contain '..' or '..='".to_string())
}
}
</file>
|
{
"crate": "smithy",
"file": "crates/smithy/src/lib.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 7365
}
|
large_file_5148659623146563632
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_enums
File: crates/common_enums/src/connector_enums.rs
</path>
<file>
use std::collections::HashSet;
use utoipa::ToSchema;
pub use super::enums::{PaymentMethod, PayoutType};
pub use crate::PaymentMethodType;
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
strum::VariantNames,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
/// RoutableConnectors are the subset of Connectors that are eligible for payments routing
pub enum RoutableConnectors {
Authipay,
Adyenplatform,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "stripe_billing_test")]
#[strum(serialize = "stripe_billing_test")]
DummyBillingConnector,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "phonypay")]
#[strum(serialize = "phonypay")]
DummyConnector1,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "fauxpay")]
#[strum(serialize = "fauxpay")]
DummyConnector2,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "pretendpay")]
#[strum(serialize = "pretendpay")]
DummyConnector3,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "stripe_test")]
#[strum(serialize = "stripe_test")]
DummyConnector4,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "adyen_test")]
#[strum(serialize = "adyen_test")]
DummyConnector5,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "checkout_test")]
#[strum(serialize = "checkout_test")]
DummyConnector6,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "paypal_test")]
#[strum(serialize = "paypal_test")]
DummyConnector7,
Aci,
Adyen,
Affirm,
Airwallex,
Amazonpay,
Archipel,
Authorizedotnet,
Bankofamerica,
Barclaycard,
Billwerk,
Bitpay,
Bambora,
Blackhawknetwork,
Bamboraapac,
Bluesnap,
#[serde(alias = "bluecode")]
Calida,
Boku,
Braintree,
Breadpay,
Cashtocode,
Celero,
Chargebee,
Custombilling,
Checkbook,
Checkout,
Coinbase,
Coingate,
Cryptopay,
Cybersource,
Datatrans,
Deutschebank,
Digitalvirgo,
Dlocal,
Dwolla,
Ebanx,
Elavon,
Facilitapay,
Finix,
Fiserv,
Fiservemea,
Fiuu,
Flexiti,
Forte,
Getnet,
Gigadat,
Globalpay,
Globepay,
Gocardless,
Hipay,
Helcim,
Iatapay,
Inespay,
Itaubank,
Jpmorgan,
Klarna,
Loonio,
Mifinity,
Mollie,
Moneris,
Multisafepay,
Nexinets,
Nexixpay,
Nmi,
Nomupay,
Noon,
Nordea,
Novalnet,
Nuvei,
// Opayo, added as template code for future usage
Opennode,
// Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage
Paybox,
Payme,
Payload,
Payone,
Paypal,
Paysafe,
Paystack,
Paytm,
Payu,
Peachpayments,
Phonepe,
Placetopay,
Powertranz,
Prophetpay,
Rapyd,
Razorpay,
Recurly,
Redsys,
Riskified,
Santander,
Shift4,
Signifyd,
Silverflow,
Square,
Stax,
Stripe,
Stripebilling,
Tesouro,
// Taxjar,
Trustpay,
Trustpayments,
// Thunes
Tokenio,
// Tsys,
Tsys,
// UnifiedAuthenticationService,
// Vgs
Volt,
Wellsfargo,
// Wellsfargopayout,
Wise,
Worldline,
Worldpay,
Worldpayvantiv,
Worldpayxml,
Xendit,
Zen,
Plaid,
Zsl,
}
// A connector is an integration to fulfill payments
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
ToSchema,
serde::Deserialize,
serde::Serialize,
strum::VariantNames,
strum::EnumIter,
strum::Display,
strum::EnumString,
Hash,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum Connector {
Authipay,
Adyenplatform,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "stripe_billing_test")]
#[strum(serialize = "stripe_billing_test")]
DummyBillingConnector,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "phonypay")]
#[strum(serialize = "phonypay")]
DummyConnector1,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "fauxpay")]
#[strum(serialize = "fauxpay")]
DummyConnector2,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "pretendpay")]
#[strum(serialize = "pretendpay")]
DummyConnector3,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "stripe_test")]
#[strum(serialize = "stripe_test")]
DummyConnector4,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "adyen_test")]
#[strum(serialize = "adyen_test")]
DummyConnector5,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "checkout_test")]
#[strum(serialize = "checkout_test")]
DummyConnector6,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "paypal_test")]
#[strum(serialize = "paypal_test")]
DummyConnector7,
Aci,
Adyen,
Affirm,
Airwallex,
Amazonpay,
Archipel,
Authorizedotnet,
Bambora,
Bamboraapac,
Bankofamerica,
Barclaycard,
Billwerk,
Bitpay,
Bluesnap,
Blackhawknetwork,
#[serde(alias = "bluecode")]
Calida,
Boku,
Braintree,
Breadpay,
Cardinal,
Cashtocode,
Celero,
Chargebee,
Checkbook,
Checkout,
Coinbase,
Coingate,
Custombilling,
Cryptopay,
CtpMastercard,
CtpVisa,
Cybersource,
Datatrans,
Deutschebank,
Digitalvirgo,
Dlocal,
Dwolla,
Ebanx,
Elavon,
Facilitapay,
Finix,
Fiserv,
Fiservemea,
Fiuu,
Flexiti,
Forte,
Getnet,
Gigadat,
Globalpay,
Globepay,
Gocardless,
Gpayments,
Hipay,
Helcim,
HyperswitchVault,
// Hyperwallet, added as template code for future usage
Inespay,
Iatapay,
Itaubank,
Jpmorgan,
Juspaythreedsserver,
Klarna,
Loonio,
Mifinity,
Mollie,
Moneris,
Multisafepay,
Netcetera,
Nexinets,
Nexixpay,
Nmi,
Nomupay,
Noon,
Nordea,
Novalnet,
Nuvei,
// Opayo, added as template code for future usage
Opennode,
Paybox,
// Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage
Payload,
Payme,
Payone,
Paypal,
Paysafe,
Paystack,
Paytm,
Payu,
Peachpayments,
Phonepe,
Placetopay,
Powertranz,
Prophetpay,
Rapyd,
Razorpay,
Recurly,
Redsys,
Santander,
Shift4,
Silverflow,
Square,
Stax,
Stripe,
Stripebilling,
Taxjar,
Threedsecureio,
// Tokenio,
//Thunes,
Tesouro,
Tokenex,
Tokenio,
Trustpay,
Trustpayments,
Tsys,
// UnifiedAuthenticationService,
Vgs,
Volt,
Wellsfargo,
// Wellsfargopayout,
Wise,
Worldline,
Worldpay,
Worldpayvantiv,
Worldpayxml,
Signifyd,
Plaid,
Riskified,
Xendit,
Zen,
Zsl,
}
impl Connector {
#[cfg(feature = "payouts")]
pub fn supports_instant_payout(self, payout_method: Option<PayoutType>) -> bool {
matches!(
(self, payout_method),
(Self::Paypal, Some(PayoutType::Wallet))
| (_, Some(PayoutType::Card))
| (Self::Adyenplatform, _)
| (Self::Nomupay, _)
| (Self::Loonio, _)
| (Self::Worldpay, Some(PayoutType::Wallet))
)
}
#[cfg(feature = "payouts")]
pub fn supports_create_recipient(self, payout_method: Option<PayoutType>) -> bool {
matches!((self, payout_method), (_, Some(PayoutType::Bank)))
}
#[cfg(feature = "payouts")]
pub fn supports_payout_eligibility(self, payout_method: Option<PayoutType>) -> bool {
matches!((self, payout_method), (_, Some(PayoutType::Card)))
}
#[cfg(feature = "payouts")]
pub fn is_payout_quote_call_required(self) -> bool {
matches!(self, Self::Wise | Self::Gigadat)
}
#[cfg(feature = "payouts")]
pub fn supports_access_token_for_payout(self, payout_method: Option<PayoutType>) -> bool {
matches!((self, payout_method), (Self::Paypal, _))
}
#[cfg(feature = "payouts")]
pub fn supports_vendor_disburse_account_create_for_payout(self) -> bool {
matches!(self, Self::Stripe | Self::Nomupay)
}
pub fn supports_access_token(self, payment_method: PaymentMethod) -> bool {
matches!(
(self, payment_method),
(Self::Airwallex, _)
| (Self::Deutschebank, _)
| (Self::Globalpay, _)
| (Self::Jpmorgan, _)
| (Self::Moneris, _)
| (Self::Nordea, _)
| (Self::Paypal, _)
| (Self::Payu, _)
| (
Self::Trustpay,
PaymentMethod::BankRedirect | PaymentMethod::BankTransfer
)
| (Self::Tesouro, _)
| (Self::Iatapay, _)
| (Self::Volt, _)
| (Self::Itaubank, _)
| (Self::Facilitapay, _)
| (Self::Dwolla, _)
)
}
pub fn requires_order_creation_before_payment(self, payment_method: PaymentMethod) -> bool {
matches!((self, payment_method), (Self::Razorpay, PaymentMethod::Upi))
}
pub fn supports_file_storage_module(self) -> bool {
matches!(self, Self::Stripe | Self::Checkout | Self::Worldpayvantiv)
}
pub fn requires_defend_dispute(self) -> bool {
matches!(self, Self::Checkout)
}
pub fn is_separate_authentication_supported(self) -> bool {
match self {
#[cfg(feature = "dummy_connector")]
Self::DummyBillingConnector => false,
#[cfg(feature = "dummy_connector")]
Self::DummyConnector1
| Self::DummyConnector2
| Self::DummyConnector3
| Self::DummyConnector4
| Self::DummyConnector5
| Self::DummyConnector6
| Self::DummyConnector7 => false,
Self::Aci
// Add Separate authentication support for connectors
| Self::Authipay
| Self::Adyen
| Self::Affirm
| Self::Adyenplatform
| Self::Airwallex
| Self::Amazonpay
| Self::Authorizedotnet
| Self::Bambora
| Self::Bamboraapac
| Self::Bankofamerica
| Self::Barclaycard
| Self::Billwerk
| Self::Bitpay
| Self::Bluesnap
| Self::Blackhawknetwork
| Self::Calida
| Self::Boku
| Self::Braintree
| Self::Breadpay
| Self::Cashtocode
| Self::Celero
| Self::Chargebee
| Self::Checkbook
| Self::Coinbase
| Self::Coingate
| Self::Cryptopay
| Self::Custombilling
| Self::Deutschebank
| Self::Digitalvirgo
| Self::Dlocal
| Self::Dwolla
| Self::Ebanx
| Self::Elavon
| Self::Facilitapay
| Self::Finix
| Self::Fiserv
| Self::Fiservemea
| Self::Fiuu
| Self::Flexiti
| Self::Forte
| Self::Getnet
| Self::Gigadat
| Self::Globalpay
| Self::Globepay
| Self::Gocardless
| Self::Gpayments
| Self::Hipay
| Self::Helcim
| Self::HyperswitchVault
| Self::Iatapay
| Self::Inespay
| Self::Itaubank
| Self::Jpmorgan
| Self::Juspaythreedsserver
| Self::Klarna
| Self::Loonio
| Self::Mifinity
| Self::Mollie
| Self::Moneris
| Self::Multisafepay
| Self::Nexinets
| Self::Nexixpay
| Self::Nomupay
| Self::Nordea
| Self::Novalnet
| Self::Opennode
| Self::Paybox
| Self::Payload
| Self::Payme
| Self::Payone
| Self::Paypal
| Self::Paysafe
| Self::Paystack
| Self::Payu
| Self::Peachpayments
| Self::Placetopay
| Self::Powertranz
| Self::Prophetpay
| Self::Rapyd
| Self::Recurly
| Self::Redsys
| Self::Santander
| Self::Shift4
| Self::Silverflow
| Self::Square
| Self::Stax
| Self::Stripebilling
| Self::Taxjar
| Self::Tesouro
// | Self::Thunes
| Self::Trustpay
| Self::Trustpayments
// | Self::Tokenio
| Self::Tsys
// | Self::UnifiedAuthenticationService
| Self::Vgs
| Self::Volt
| Self::Wellsfargo
// | Self::Wellsfargopayout
| Self::Wise
| Self::Worldline
| Self::Worldpay
| Self::Worldpayvantiv
| Self::Worldpayxml
| Self::Xendit
| Self::Zen
| Self::Zsl
| Self::Signifyd
| Self::Plaid
| Self::Razorpay
| Self::Riskified
| Self::Threedsecureio
| Self::Netcetera
| Self::CtpMastercard
| Self::Cardinal
| Self::CtpVisa
| Self::Noon
| Self::Tokenex
| Self::Tokenio
| Self::Stripe
| Self::Datatrans
| Self::Paytm
| Self::Phonepe => false,
Self::Checkout | Self::Nmi |Self::Cybersource | Self::Archipel | Self::Nuvei => true,
}
}
pub fn is_pre_processing_required_before_authorize(self) -> bool {
matches!(self, Self::Airwallex)
}
pub fn get_payment_methods_supporting_extended_authorization(self) -> HashSet<PaymentMethod> {
HashSet::from([PaymentMethod::Card])
}
pub fn get_payment_method_types_supporting_extended_authorization(
self,
) -> HashSet<PaymentMethodType> {
HashSet::from([PaymentMethodType::Credit, PaymentMethodType::Debit])
}
pub fn is_overcapture_supported_by_connector(self) -> bool {
matches!(self, Self::Stripe | Self::Adyen)
}
pub fn should_acknowledge_webhook_for_resource_not_found_errors(self) -> bool {
matches!(self, Self::Adyenplatform | Self::Adyen)
}
/// Validates if dummy connector can be created
/// Dummy connectors can be created only if dummy_connector feature is enabled in the configs
#[cfg(feature = "dummy_connector")]
pub fn validate_dummy_connector_create(self, is_dummy_connector_enabled: bool) -> bool {
matches!(
self,
Self::DummyConnector1
| Self::DummyConnector2
| Self::DummyConnector3
| Self::DummyConnector4
| Self::DummyConnector5
| Self::DummyConnector6
| Self::DummyConnector7
) && !is_dummy_connector_enabled
}
}
/// Convert the RoutableConnectors to Connector
impl From<RoutableConnectors> for Connector {
fn from(routable_connector: RoutableConnectors) -> Self {
match routable_connector {
RoutableConnectors::Authipay => Self::Authipay,
RoutableConnectors::Adyenplatform => Self::Adyenplatform,
#[cfg(feature = "dummy_connector")]
RoutableConnectors::DummyBillingConnector => Self::DummyBillingConnector,
#[cfg(feature = "dummy_connector")]
RoutableConnectors::DummyConnector1 => Self::DummyConnector1,
#[cfg(feature = "dummy_connector")]
RoutableConnectors::DummyConnector2 => Self::DummyConnector2,
#[cfg(feature = "dummy_connector")]
RoutableConnectors::DummyConnector3 => Self::DummyConnector3,
#[cfg(feature = "dummy_connector")]
RoutableConnectors::DummyConnector4 => Self::DummyConnector4,
#[cfg(feature = "dummy_connector")]
RoutableConnectors::DummyConnector5 => Self::DummyConnector5,
#[cfg(feature = "dummy_connector")]
RoutableConnectors::DummyConnector6 => Self::DummyConnector6,
#[cfg(feature = "dummy_connector")]
RoutableConnectors::DummyConnector7 => Self::DummyConnector7,
RoutableConnectors::Aci => Self::Aci,
RoutableConnectors::Adyen => Self::Adyen,
RoutableConnectors::Affirm => Self::Affirm,
RoutableConnectors::Airwallex => Self::Airwallex,
RoutableConnectors::Amazonpay => Self::Amazonpay,
RoutableConnectors::Archipel => Self::Archipel,
RoutableConnectors::Authorizedotnet => Self::Authorizedotnet,
RoutableConnectors::Bankofamerica => Self::Bankofamerica,
RoutableConnectors::Barclaycard => Self::Barclaycard,
RoutableConnectors::Billwerk => Self::Billwerk,
RoutableConnectors::Bitpay => Self::Bitpay,
RoutableConnectors::Bambora => Self::Bambora,
RoutableConnectors::Bamboraapac => Self::Bamboraapac,
RoutableConnectors::Bluesnap => Self::Bluesnap,
RoutableConnectors::Blackhawknetwork => Self::Blackhawknetwork,
RoutableConnectors::Calida => Self::Calida,
RoutableConnectors::Boku => Self::Boku,
RoutableConnectors::Braintree => Self::Braintree,
RoutableConnectors::Breadpay => Self::Breadpay,
RoutableConnectors::Cashtocode => Self::Cashtocode,
RoutableConnectors::Celero => Self::Celero,
RoutableConnectors::Chargebee => Self::Chargebee,
RoutableConnectors::Custombilling => Self::Custombilling,
RoutableConnectors::Checkbook => Self::Checkbook,
RoutableConnectors::Checkout => Self::Checkout,
RoutableConnectors::Coinbase => Self::Coinbase,
RoutableConnectors::Cryptopay => Self::Cryptopay,
RoutableConnectors::Cybersource => Self::Cybersource,
RoutableConnectors::Datatrans => Self::Datatrans,
RoutableConnectors::Deutschebank => Self::Deutschebank,
RoutableConnectors::Digitalvirgo => Self::Digitalvirgo,
RoutableConnectors::Dlocal => Self::Dlocal,
RoutableConnectors::Dwolla => Self::Dwolla,
RoutableConnectors::Ebanx => Self::Ebanx,
RoutableConnectors::Elavon => Self::Elavon,
RoutableConnectors::Facilitapay => Self::Facilitapay,
RoutableConnectors::Finix => Self::Finix,
RoutableConnectors::Fiserv => Self::Fiserv,
RoutableConnectors::Fiservemea => Self::Fiservemea,
RoutableConnectors::Fiuu => Self::Fiuu,
RoutableConnectors::Flexiti => Self::Flexiti,
RoutableConnectors::Forte => Self::Forte,
RoutableConnectors::Getnet => Self::Getnet,
RoutableConnectors::Gigadat => Self::Gigadat,
RoutableConnectors::Globalpay => Self::Globalpay,
RoutableConnectors::Globepay => Self::Globepay,
RoutableConnectors::Gocardless => Self::Gocardless,
RoutableConnectors::Helcim => Self::Helcim,
RoutableConnectors::Iatapay => Self::Iatapay,
RoutableConnectors::Itaubank => Self::Itaubank,
RoutableConnectors::Jpmorgan => Self::Jpmorgan,
RoutableConnectors::Klarna => Self::Klarna,
RoutableConnectors::Loonio => Self::Loonio,
RoutableConnectors::Mifinity => Self::Mifinity,
RoutableConnectors::Mollie => Self::Mollie,
RoutableConnectors::Moneris => Self::Moneris,
RoutableConnectors::Multisafepay => Self::Multisafepay,
RoutableConnectors::Nexinets => Self::Nexinets,
RoutableConnectors::Nexixpay => Self::Nexixpay,
RoutableConnectors::Nmi => Self::Nmi,
RoutableConnectors::Nomupay => Self::Nomupay,
RoutableConnectors::Noon => Self::Noon,
RoutableConnectors::Nordea => Self::Nordea,
RoutableConnectors::Novalnet => Self::Novalnet,
RoutableConnectors::Nuvei => Self::Nuvei,
RoutableConnectors::Opennode => Self::Opennode,
RoutableConnectors::Paybox => Self::Paybox,
RoutableConnectors::Payload => Self::Payload,
RoutableConnectors::Payme => Self::Payme,
RoutableConnectors::Payone => Self::Payone,
RoutableConnectors::Paypal => Self::Paypal,
RoutableConnectors::Paysafe => Self::Paysafe,
RoutableConnectors::Paystack => Self::Paystack,
RoutableConnectors::Payu => Self::Payu,
RoutableConnectors::Peachpayments => Self::Peachpayments,
RoutableConnectors::Placetopay => Self::Placetopay,
RoutableConnectors::Powertranz => Self::Powertranz,
RoutableConnectors::Prophetpay => Self::Prophetpay,
RoutableConnectors::Rapyd => Self::Rapyd,
RoutableConnectors::Razorpay => Self::Razorpay,
RoutableConnectors::Recurly => Self::Recurly,
RoutableConnectors::Redsys => Self::Redsys,
RoutableConnectors::Riskified => Self::Riskified,
RoutableConnectors::Santander => Self::Santander,
RoutableConnectors::Shift4 => Self::Shift4,
RoutableConnectors::Signifyd => Self::Signifyd,
RoutableConnectors::Silverflow => Self::Silverflow,
RoutableConnectors::Square => Self::Square,
RoutableConnectors::Stax => Self::Stax,
RoutableConnectors::Stripe => Self::Stripe,
RoutableConnectors::Stripebilling => Self::Stripebilling,
RoutableConnectors::Tesouro => Self::Tesouro,
RoutableConnectors::Tokenio => Self::Tokenio,
RoutableConnectors::Trustpay => Self::Trustpay,
RoutableConnectors::Trustpayments => Self::Trustpayments,
// RoutableConnectors::Tokenio => Self::Tokenio,
RoutableConnectors::Tsys => Self::Tsys,
RoutableConnectors::Volt => Self::Volt,
RoutableConnectors::Wellsfargo => Self::Wellsfargo,
RoutableConnectors::Wise => Self::Wise,
RoutableConnectors::Worldline => Self::Worldline,
RoutableConnectors::Worldpay => Self::Worldpay,
RoutableConnectors::Worldpayvantiv => Self::Worldpayvantiv,
RoutableConnectors::Worldpayxml => Self::Worldpayxml,
RoutableConnectors::Zen => Self::Zen,
RoutableConnectors::Plaid => Self::Plaid,
RoutableConnectors::Zsl => Self::Zsl,
RoutableConnectors::Xendit => Self::Xendit,
RoutableConnectors::Inespay => Self::Inespay,
RoutableConnectors::Coingate => Self::Coingate,
RoutableConnectors::Hipay => Self::Hipay,
RoutableConnectors::Paytm => Self::Paytm,
RoutableConnectors::Phonepe => Self::Phonepe,
}
}
}
impl TryFrom<Connector> for RoutableConnectors {
type Error = &'static str;
fn try_from(connector: Connector) -> Result<Self, Self::Error> {
match connector {
Connector::Authipay => Ok(Self::Authipay),
Connector::Adyenplatform => Ok(Self::Adyenplatform),
#[cfg(feature = "dummy_connector")]
Connector::DummyBillingConnector => Ok(Self::DummyBillingConnector),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector1 => Ok(Self::DummyConnector1),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector2 => Ok(Self::DummyConnector2),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector3 => Ok(Self::DummyConnector3),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector4 => Ok(Self::DummyConnector4),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector5 => Ok(Self::DummyConnector5),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector6 => Ok(Self::DummyConnector6),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector7 => Ok(Self::DummyConnector7),
Connector::Aci => Ok(Self::Aci),
Connector::Adyen => Ok(Self::Adyen),
Connector::Affirm => Ok(Self::Affirm),
Connector::Airwallex => Ok(Self::Airwallex),
Connector::Amazonpay => Ok(Self::Amazonpay),
Connector::Archipel => Ok(Self::Archipel),
Connector::Authorizedotnet => Ok(Self::Authorizedotnet),
Connector::Bankofamerica => Ok(Self::Bankofamerica),
Connector::Barclaycard => Ok(Self::Barclaycard),
Connector::Billwerk => Ok(Self::Billwerk),
Connector::Bitpay => Ok(Self::Bitpay),
Connector::Bambora => Ok(Self::Bambora),
Connector::Bamboraapac => Ok(Self::Bamboraapac),
Connector::Bluesnap => Ok(Self::Bluesnap),
Connector::Blackhawknetwork => Ok(Self::Blackhawknetwork),
Connector::Calida => Ok(Self::Calida),
Connector::Boku => Ok(Self::Boku),
Connector::Braintree => Ok(Self::Braintree),
Connector::Breadpay => Ok(Self::Breadpay),
Connector::Cashtocode => Ok(Self::Cashtocode),
Connector::Celero => Ok(Self::Celero),
Connector::Chargebee => Ok(Self::Chargebee),
Connector::Checkbook => Ok(Self::Checkbook),
Connector::Checkout => Ok(Self::Checkout),
Connector::Coinbase => Ok(Self::Coinbase),
Connector::Coingate => Ok(Self::Coingate),
Connector::Cryptopay => Ok(Self::Cryptopay),
Connector::Custombilling => Ok(Self::Custombilling),
Connector::Cybersource => Ok(Self::Cybersource),
Connector::Datatrans => Ok(Self::Datatrans),
Connector::Deutschebank => Ok(Self::Deutschebank),
Connector::Digitalvirgo => Ok(Self::Digitalvirgo),
Connector::Dlocal => Ok(Self::Dlocal),
Connector::Dwolla => Ok(Self::Dwolla),
Connector::Ebanx => Ok(Self::Ebanx),
Connector::Elavon => Ok(Self::Elavon),
Connector::Facilitapay => Ok(Self::Facilitapay),
Connector::Finix => Ok(Self::Finix),
Connector::Fiserv => Ok(Self::Fiserv),
Connector::Fiservemea => Ok(Self::Fiservemea),
Connector::Fiuu => Ok(Self::Fiuu),
Connector::Flexiti => Ok(Self::Flexiti),
Connector::Forte => Ok(Self::Forte),
Connector::Globalpay => Ok(Self::Globalpay),
Connector::Globepay => Ok(Self::Globepay),
Connector::Gocardless => Ok(Self::Gocardless),
Connector::Helcim => Ok(Self::Helcim),
Connector::Iatapay => Ok(Self::Iatapay),
Connector::Itaubank => Ok(Self::Itaubank),
Connector::Jpmorgan => Ok(Self::Jpmorgan),
Connector::Klarna => Ok(Self::Klarna),
Connector::Loonio => Ok(Self::Loonio),
Connector::Mifinity => Ok(Self::Mifinity),
Connector::Mollie => Ok(Self::Mollie),
Connector::Moneris => Ok(Self::Moneris),
Connector::Multisafepay => Ok(Self::Multisafepay),
Connector::Nexinets => Ok(Self::Nexinets),
Connector::Nexixpay => Ok(Self::Nexixpay),
Connector::Nmi => Ok(Self::Nmi),
Connector::Nomupay => Ok(Self::Nomupay),
Connector::Noon => Ok(Self::Noon),
Connector::Nordea => Ok(Self::Nordea),
Connector::Novalnet => Ok(Self::Novalnet),
Connector::Nuvei => Ok(Self::Nuvei),
Connector::Opennode => Ok(Self::Opennode),
Connector::Paybox => Ok(Self::Paybox),
Connector::Payload => Ok(Self::Payload),
Connector::Payme => Ok(Self::Payme),
Connector::Payone => Ok(Self::Payone),
Connector::Paypal => Ok(Self::Paypal),
Connector::Paysafe => Ok(Self::Paysafe),
Connector::Paystack => Ok(Self::Paystack),
Connector::Payu => Ok(Self::Payu),
Connector::Peachpayments => Ok(Self::Peachpayments),
Connector::Placetopay => Ok(Self::Placetopay),
Connector::Powertranz => Ok(Self::Powertranz),
Connector::Prophetpay => Ok(Self::Prophetpay),
Connector::Rapyd => Ok(Self::Rapyd),
Connector::Razorpay => Ok(Self::Razorpay),
Connector::Riskified => Ok(Self::Riskified),
Connector::Santander => Ok(Self::Santander),
Connector::Shift4 => Ok(Self::Shift4),
Connector::Signifyd => Ok(Self::Signifyd),
Connector::Silverflow => Ok(Self::Silverflow),
Connector::Square => Ok(Self::Square),
Connector::Stax => Ok(Self::Stax),
Connector::Stripe => Ok(Self::Stripe),
Connector::Stripebilling => Ok(Self::Stripebilling),
Connector::Tokenio => Ok(Self::Tokenio),
Connector::Tesouro => Ok(Self::Tesouro),
Connector::Trustpay => Ok(Self::Trustpay),
Connector::Trustpayments => Ok(Self::Trustpayments),
Connector::Tsys => Ok(Self::Tsys),
Connector::Volt => Ok(Self::Volt),
Connector::Wellsfargo => Ok(Self::Wellsfargo),
Connector::Wise => Ok(Self::Wise),
Connector::Worldline => Ok(Self::Worldline),
Connector::Worldpay => Ok(Self::Worldpay),
Connector::Worldpayvantiv => Ok(Self::Worldpayvantiv),
Connector::Worldpayxml => Ok(Self::Worldpayxml),
Connector::Xendit => Ok(Self::Xendit),
Connector::Zen => Ok(Self::Zen),
Connector::Plaid => Ok(Self::Plaid),
Connector::Zsl => Ok(Self::Zsl),
Connector::Recurly => Ok(Self::Recurly),
Connector::Getnet => Ok(Self::Getnet),
Connector::Gigadat => Ok(Self::Gigadat),
Connector::Hipay => Ok(Self::Hipay),
Connector::Inespay => Ok(Self::Inespay),
Connector::Redsys => Ok(Self::Redsys),
Connector::Paytm => Ok(Self::Paytm),
Connector::Phonepe => Ok(Self::Phonepe),
Connector::CtpMastercard
| Connector::Gpayments
| Connector::HyperswitchVault
| Connector::Juspaythreedsserver
| Connector::Netcetera
| Connector::Taxjar
| Connector::Threedsecureio
| Connector::Vgs
| Connector::CtpVisa
| Connector::Cardinal
| Connector::Tokenex => Err("Invalid conversion. Not a routable connector"),
}
}
}
// Enum representing different status an invoice can have.
#[derive(
Debug,
Clone,
PartialEq,
Eq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum InvoiceStatus {
InvoiceCreated,
PaymentPending,
PaymentPendingTimeout,
PaymentSucceeded,
PaymentFailed,
PaymentCanceled,
InvoicePaid,
ManualReview,
Voided,
}
</file>
|
{
"crate": "common_enums",
"file": "crates/common_enums/src/connector_enums.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 8113
}
|
large_file_5614017290183080477
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_constraint_graph
File: crates/hyperswitch_constraint_graph/src/graph.rs
</path>
<file>
use std::sync::{Arc, Weak};
use rustc_hash::{FxHashMap, FxHashSet};
use crate::{
builder,
dense_map::DenseMap,
error::{self, AnalysisTrace, GraphError},
types::{
CheckingContext, CycleCheck, DomainId, DomainIdentifier, DomainInfo, Edge, EdgeId,
Memoization, Metadata, Node, NodeId, NodeType, NodeValue, Relation, RelationResolution,
Strength, ValueNode,
},
};
#[derive(Debug)]
struct CheckNodeContext<'a, V: ValueNode, C: CheckingContext<Value = V>> {
ctx: &'a C,
node: &'a Node<V>,
node_id: NodeId,
relation: Relation,
strength: Strength,
memo: &'a mut Memoization<V>,
cycle_map: &'a mut CycleCheck,
domains: Option<&'a [DomainId]>,
}
#[derive(Debug)]
pub struct ConstraintGraph<V: ValueNode> {
pub domain: DenseMap<DomainId, DomainInfo>,
pub domain_identifier_map: FxHashMap<DomainIdentifier, DomainId>,
pub nodes: DenseMap<NodeId, Node<V>>,
pub edges: DenseMap<EdgeId, Edge>,
pub value_map: FxHashMap<NodeValue<V>, NodeId>,
pub node_info: DenseMap<NodeId, Option<&'static str>>,
pub node_metadata: DenseMap<NodeId, Option<Arc<dyn Metadata>>>,
}
impl<V> ConstraintGraph<V>
where
V: ValueNode,
{
fn get_predecessor_edges_by_domain(
&self,
node_id: NodeId,
domains: Option<&[DomainId]>,
) -> Result<Vec<&Edge>, GraphError<V>> {
let node = self.nodes.get(node_id).ok_or(GraphError::NodeNotFound)?;
let mut final_list = Vec::new();
for &pred in &node.preds {
let edge = self.edges.get(pred).ok_or(GraphError::EdgeNotFound)?;
if let Some((domain_id, domains)) = edge.domain.zip(domains) {
if domains.contains(&domain_id) {
final_list.push(edge);
}
} else if edge.domain.is_none() {
final_list.push(edge);
}
}
Ok(final_list)
}
#[allow(clippy::too_many_arguments)]
pub fn check_node<C>(
&self,
ctx: &C,
node_id: NodeId,
relation: Relation,
strength: Strength,
memo: &mut Memoization<V>,
cycle_map: &mut CycleCheck,
domains: Option<&[String]>,
) -> Result<(), GraphError<V>>
where
C: CheckingContext<Value = V>,
{
let domains = domains
.map(|domain_idents| {
domain_idents
.iter()
.map(|domain_ident| {
self.domain_identifier_map
.get(&DomainIdentifier::new(domain_ident.to_string()))
.copied()
.ok_or(GraphError::DomainNotFound)
})
.collect::<Result<Vec<_>, _>>()
})
.transpose()?;
self.check_node_inner(
ctx,
node_id,
relation,
strength,
memo,
cycle_map,
domains.as_deref(),
)
}
#[allow(clippy::too_many_arguments)]
pub fn check_node_inner<C>(
&self,
ctx: &C,
node_id: NodeId,
relation: Relation,
strength: Strength,
memo: &mut Memoization<V>,
cycle_map: &mut CycleCheck,
domains: Option<&[DomainId]>,
) -> Result<(), GraphError<V>>
where
C: CheckingContext<Value = V>,
{
let node = self.nodes.get(node_id).ok_or(GraphError::NodeNotFound)?;
if let Some(already_memo) = memo.get(&(node_id, relation, strength)) {
already_memo
.clone()
.map_err(|err| GraphError::AnalysisError(Arc::downgrade(&err)))
} else if let Some((initial_strength, initial_relation)) = cycle_map.get(&node_id).copied()
{
let strength_relation = Strength::get_resolved_strength(initial_strength, strength);
let relation_resolve =
RelationResolution::get_resolved_relation(initial_relation, relation.into());
cycle_map.entry(node_id).and_modify(|value| {
value.0 = strength_relation;
value.1 = relation_resolve
});
Ok(())
} else {
let check_node_context = CheckNodeContext {
node,
node_id,
relation,
strength,
memo,
cycle_map,
ctx,
domains,
};
match &node.node_type {
NodeType::AllAggregator => self.validate_all_aggregator(check_node_context),
NodeType::AnyAggregator => self.validate_any_aggregator(check_node_context),
NodeType::InAggregator(expected) => {
self.validate_in_aggregator(check_node_context, expected)
}
NodeType::Value(val) => self.validate_value_node(check_node_context, val),
}
}
}
fn validate_all_aggregator<C>(
&self,
vald: CheckNodeContext<'_, V, C>,
) -> Result<(), GraphError<V>>
where
C: CheckingContext<Value = V>,
{
let mut unsatisfied = Vec::<Weak<AnalysisTrace<V>>>::new();
for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? {
vald.cycle_map
.insert(vald.node_id, (vald.strength, vald.relation.into()));
if let Err(e) = self.check_node_inner(
vald.ctx,
edge.pred,
edge.relation,
edge.strength,
vald.memo,
vald.cycle_map,
vald.domains,
) {
unsatisfied.push(e.get_analysis_trace()?);
}
if let Some((_resolved_strength, resolved_relation)) =
vald.cycle_map.remove(&vald.node_id)
{
if resolved_relation == RelationResolution::Contradiction {
let err = Arc::new(AnalysisTrace::Contradiction {
relation: resolved_relation,
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
return Err(GraphError::AnalysisError(Arc::downgrade(&err)));
}
}
}
if !unsatisfied.is_empty() {
let err = Arc::new(AnalysisTrace::AllAggregation {
unsatisfied,
info: self.node_info.get(vald.node_id).copied().flatten(),
metadata: self.node_metadata.get(vald.node_id).cloned().flatten(),
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
Err(GraphError::AnalysisError(Arc::downgrade(&err)))
} else {
vald.memo
.insert((vald.node_id, vald.relation, vald.strength), Ok(()));
Ok(())
}
}
fn validate_any_aggregator<C>(
&self,
vald: CheckNodeContext<'_, V, C>,
) -> Result<(), GraphError<V>>
where
C: CheckingContext<Value = V>,
{
let mut unsatisfied = Vec::<Weak<AnalysisTrace<V>>>::new();
let mut matched_one = false;
for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? {
vald.cycle_map
.insert(vald.node_id, (vald.strength, vald.relation.into()));
if let Err(e) = self.check_node_inner(
vald.ctx,
edge.pred,
edge.relation,
edge.strength,
vald.memo,
vald.cycle_map,
vald.domains,
) {
unsatisfied.push(e.get_analysis_trace()?);
} else {
matched_one = true;
}
if let Some((_resolved_strength, resolved_relation)) =
vald.cycle_map.remove(&vald.node_id)
{
if resolved_relation == RelationResolution::Contradiction {
let err = Arc::new(AnalysisTrace::Contradiction {
relation: resolved_relation,
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
return Err(GraphError::AnalysisError(Arc::downgrade(&err)));
}
}
}
if matched_one || vald.node.preds.is_empty() {
vald.memo
.insert((vald.node_id, vald.relation, vald.strength), Ok(()));
Ok(())
} else {
let err = Arc::new(AnalysisTrace::AnyAggregation {
unsatisfied: unsatisfied.clone(),
info: self.node_info.get(vald.node_id).copied().flatten(),
metadata: self.node_metadata.get(vald.node_id).cloned().flatten(),
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
Err(GraphError::AnalysisError(Arc::downgrade(&err)))
}
}
fn validate_in_aggregator<C>(
&self,
vald: CheckNodeContext<'_, V, C>,
expected: &FxHashSet<V>,
) -> Result<(), GraphError<V>>
where
C: CheckingContext<Value = V>,
{
let the_key = expected
.iter()
.next()
.ok_or_else(|| GraphError::MalformedGraph {
reason: "An OnlyIn aggregator node must have at least one expected value"
.to_string(),
})?
.get_key();
let ctx_vals = if let Some(vals) = vald.ctx.get_values_by_key(&the_key) {
vals
} else {
return if let Strength::Weak = vald.strength {
vald.memo
.insert((vald.node_id, vald.relation, vald.strength), Ok(()));
Ok(())
} else {
let err = Arc::new(AnalysisTrace::InAggregation {
expected: expected.iter().cloned().collect(),
found: None,
relation: vald.relation,
info: self.node_info.get(vald.node_id).copied().flatten(),
metadata: self.node_metadata.get(vald.node_id).cloned().flatten(),
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
Err(GraphError::AnalysisError(Arc::downgrade(&err)))
};
};
let relation_bool: bool = vald.relation.into();
for ctx_value in ctx_vals {
if expected.contains(&ctx_value) != relation_bool {
let err = Arc::new(AnalysisTrace::InAggregation {
expected: expected.iter().cloned().collect(),
found: Some(ctx_value.clone()),
relation: vald.relation,
info: self.node_info.get(vald.node_id).copied().flatten(),
metadata: self.node_metadata.get(vald.node_id).cloned().flatten(),
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
Err(GraphError::AnalysisError(Arc::downgrade(&err)))?;
}
}
vald.memo
.insert((vald.node_id, vald.relation, vald.strength), Ok(()));
Ok(())
}
fn validate_value_node<C>(
&self,
vald: CheckNodeContext<'_, V, C>,
val: &NodeValue<V>,
) -> Result<(), GraphError<V>>
where
C: CheckingContext<Value = V>,
{
let mut errors = Vec::<Weak<AnalysisTrace<V>>>::new();
let mut matched_one = false;
self.context_analysis(
vald.node_id,
vald.relation,
vald.strength,
vald.ctx,
val,
vald.memo,
)?;
for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? {
vald.cycle_map
.insert(vald.node_id, (vald.strength, vald.relation.into()));
let result = self.check_node_inner(
vald.ctx,
edge.pred,
edge.relation,
edge.strength,
vald.memo,
vald.cycle_map,
vald.domains,
);
if let Some((resolved_strength, resolved_relation)) =
vald.cycle_map.remove(&vald.node_id)
{
if resolved_relation == RelationResolution::Contradiction {
let err = Arc::new(AnalysisTrace::Contradiction {
relation: resolved_relation,
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
return Err(GraphError::AnalysisError(Arc::downgrade(&err)));
} else if resolved_strength != vald.strength {
self.context_analysis(
vald.node_id,
vald.relation,
resolved_strength,
vald.ctx,
val,
vald.memo,
)?
}
}
match (edge.strength, result) {
(Strength::Strong, Err(trace)) => {
let err = Arc::new(AnalysisTrace::Value {
value: val.clone(),
relation: vald.relation,
info: self.node_info.get(vald.node_id).copied().flatten(),
metadata: self.node_metadata.get(vald.node_id).cloned().flatten(),
predecessors: Some(error::ValueTracePredecessor::Mandatory(Box::new(
trace.get_analysis_trace()?,
))),
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
Err(GraphError::AnalysisError(Arc::downgrade(&err)))?;
}
(Strength::Strong, Ok(_)) => {
matched_one = true;
}
(Strength::Normal | Strength::Weak, Err(trace)) => {
errors.push(trace.get_analysis_trace()?);
}
(Strength::Normal | Strength::Weak, Ok(_)) => {
matched_one = true;
}
}
}
if matched_one || vald.node.preds.is_empty() {
vald.memo
.insert((vald.node_id, vald.relation, vald.strength), Ok(()));
Ok(())
} else {
let err = Arc::new(AnalysisTrace::Value {
value: val.clone(),
relation: vald.relation,
info: self.node_info.get(vald.node_id).copied().flatten(),
metadata: self.node_metadata.get(vald.node_id).cloned().flatten(),
predecessors: Some(error::ValueTracePredecessor::OneOf(errors.clone())),
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
Err(GraphError::AnalysisError(Arc::downgrade(&err)))
}
}
fn context_analysis<C>(
&self,
node_id: NodeId,
relation: Relation,
strength: Strength,
ctx: &C,
val: &NodeValue<V>,
memo: &mut Memoization<V>,
) -> Result<(), GraphError<V>>
where
C: CheckingContext<Value = V>,
{
let in_context = ctx.check_presence(val, strength);
let relation_bool: bool = relation.into();
if in_context != relation_bool {
let err = Arc::new(AnalysisTrace::Value {
value: val.clone(),
relation,
predecessors: None,
info: self.node_info.get(node_id).copied().flatten(),
metadata: self.node_metadata.get(node_id).cloned().flatten(),
});
memo.insert((node_id, relation, strength), Err(Arc::clone(&err)));
Err(GraphError::AnalysisError(Arc::downgrade(&err)))?;
}
if !relation_bool {
memo.insert((node_id, relation, strength), Ok(()));
return Ok(());
}
Ok(())
}
pub fn combine(g1: &Self, g2: &Self) -> Result<Self, GraphError<V>> {
let mut node_builder = builder::ConstraintGraphBuilder::new();
let mut g1_old2new_id = DenseMap::<NodeId, NodeId>::new();
let mut g2_old2new_id = DenseMap::<NodeId, NodeId>::new();
let mut g1_old2new_domain_id = DenseMap::<DomainId, DomainId>::new();
let mut g2_old2new_domain_id = DenseMap::<DomainId, DomainId>::new();
let add_domain = |node_builder: &mut builder::ConstraintGraphBuilder<V>,
domain: DomainInfo|
-> Result<DomainId, GraphError<V>> {
node_builder.make_domain(
domain.domain_identifier.into_inner(),
&domain.domain_description,
)
};
let add_node = |node_builder: &mut builder::ConstraintGraphBuilder<V>,
node: &Node<V>|
-> Result<NodeId, GraphError<V>> {
match &node.node_type {
NodeType::Value(node_value) => {
Ok(node_builder.make_value_node(node_value.clone(), None, None::<()>))
}
NodeType::AllAggregator => {
Ok(node_builder.make_all_aggregator(&[], None, None::<()>, None)?)
}
NodeType::AnyAggregator => {
Ok(node_builder.make_any_aggregator(&[], None, None::<()>, None)?)
}
NodeType::InAggregator(expected) => Ok(node_builder.make_in_aggregator(
expected.iter().cloned().collect(),
None,
None::<()>,
)?),
}
};
for (_old_domain_id, domain) in g1.domain.iter() {
let new_domain_id = add_domain(&mut node_builder, domain.clone())?;
g1_old2new_domain_id.push(new_domain_id);
}
for (_old_domain_id, domain) in g2.domain.iter() {
let new_domain_id = add_domain(&mut node_builder, domain.clone())?;
g2_old2new_domain_id.push(new_domain_id);
}
for (_old_node_id, node) in g1.nodes.iter() {
let new_node_id = add_node(&mut node_builder, node)?;
g1_old2new_id.push(new_node_id);
}
for (_old_node_id, node) in g2.nodes.iter() {
let new_node_id = add_node(&mut node_builder, node)?;
g2_old2new_id.push(new_node_id);
}
for edge in g1.edges.values() {
let new_pred_id = g1_old2new_id
.get(edge.pred)
.ok_or(GraphError::NodeNotFound)?;
let new_succ_id = g1_old2new_id
.get(edge.succ)
.ok_or(GraphError::NodeNotFound)?;
let domain_ident = edge
.domain
.map(|domain_id| g1.domain.get(domain_id).ok_or(GraphError::DomainNotFound))
.transpose()?
.map(|domain| domain.domain_identifier.clone());
node_builder.make_edge(
*new_pred_id,
*new_succ_id,
edge.strength,
edge.relation,
domain_ident,
)?;
}
for edge in g2.edges.values() {
let new_pred_id = g2_old2new_id
.get(edge.pred)
.ok_or(GraphError::NodeNotFound)?;
let new_succ_id = g2_old2new_id
.get(edge.succ)
.ok_or(GraphError::NodeNotFound)?;
let domain_ident = edge
.domain
.map(|domain_id| g2.domain.get(domain_id).ok_or(GraphError::DomainNotFound))
.transpose()?
.map(|domain| domain.domain_identifier.clone());
node_builder.make_edge(
*new_pred_id,
*new_succ_id,
edge.strength,
edge.relation,
domain_ident,
)?;
}
Ok(node_builder.build())
}
}
#[cfg(feature = "viz")]
mod viz {
use graphviz_rust::{
dot_generator::*,
dot_structures::*,
printer::{DotPrinter, PrinterContext},
};
use crate::{dense_map::EntityId, types, ConstraintGraph, NodeViz, ValueNode};
fn get_node_id(node_id: types::NodeId) -> String {
format!("N{}", node_id.get_id())
}
impl<V> ConstraintGraph<V>
where
V: ValueNode + NodeViz,
<V as ValueNode>::Key: NodeViz,
{
fn get_node_label(node: &types::Node<V>) -> String {
let label = match &node.node_type {
types::NodeType::Value(types::NodeValue::Key(key)) => format!("any {}", key.viz()),
types::NodeType::Value(types::NodeValue::Value(val)) => {
format!("{} = {}", val.get_key().viz(), val.viz())
}
types::NodeType::AllAggregator => "&&".to_string(),
types::NodeType::AnyAggregator => "| |".to_string(),
types::NodeType::InAggregator(agg) => {
let key = if let Some(val) = agg.iter().next() {
val.get_key().viz()
} else {
return "empty in".to_string();
};
let nodes = agg.iter().map(NodeViz::viz).collect::<Vec<_>>();
format!("{key} in [{}]", nodes.join(", "))
}
};
format!("\"{label}\"")
}
fn build_node(cg_node_id: types::NodeId, cg_node: &types::Node<V>) -> Node {
let viz_node_id = get_node_id(cg_node_id);
let viz_node_label = Self::get_node_label(cg_node);
node!(viz_node_id; attr!("label", viz_node_label))
}
fn build_edge(cg_edge: &types::Edge) -> Edge {
let pred_vertex = get_node_id(cg_edge.pred);
let succ_vertex = get_node_id(cg_edge.succ);
let arrowhead = match cg_edge.strength {
types::Strength::Weak => "onormal",
types::Strength::Normal => "normal",
types::Strength::Strong => "normalnormal",
};
let color = match cg_edge.relation {
types::Relation::Positive => "blue",
types::Relation::Negative => "red",
};
edge!(
node_id!(pred_vertex) => node_id!(succ_vertex);
attr!("arrowhead", arrowhead),
attr!("color", color)
)
}
pub fn get_viz_digraph(&self) -> Graph {
graph!(
strict di id!("constraint_graph"),
self.nodes
.iter()
.map(|(node_id, node)| Self::build_node(node_id, node))
.map(Stmt::Node)
.chain(self.edges.values().map(Self::build_edge).map(Stmt::Edge))
.collect::<Vec<_>>()
)
}
pub fn get_viz_digraph_string(&self) -> String {
let mut ctx = PrinterContext::default();
let digraph = self.get_viz_digraph();
digraph.print(&mut ctx)
}
}
}
</file>
|
{
"crate": "hyperswitch_constraint_graph",
"file": "crates/hyperswitch_constraint_graph/src/graph.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5106
}
|
large_file_-7777324445412489849
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: connector_configs
File: crates/connector_configs/src/response_modifier.rs
</path>
<file>
use crate::common_config::{
CardProvider, ConnectorApiIntegrationPayload, DashboardPaymentMethodPayload,
DashboardRequestPayload, Provider,
};
impl ConnectorApiIntegrationPayload {
pub fn get_transformed_response_payload(response: Self) -> DashboardRequestPayload {
let mut wallet_details: Vec<Provider> = Vec::new();
let mut bank_redirect_details: Vec<Provider> = Vec::new();
let mut pay_later_details: Vec<Provider> = Vec::new();
let mut debit_details: Vec<CardProvider> = Vec::new();
let mut credit_details: Vec<CardProvider> = Vec::new();
let mut bank_transfer_details: Vec<Provider> = Vec::new();
let mut crypto_details: Vec<Provider> = Vec::new();
let mut bank_debit_details: Vec<Provider> = Vec::new();
let mut reward_details: Vec<Provider> = Vec::new();
let mut real_time_payment_details: Vec<Provider> = Vec::new();
let mut upi_details: Vec<Provider> = Vec::new();
let mut voucher_details: Vec<Provider> = Vec::new();
let mut gift_card_details: Vec<Provider> = Vec::new();
let mut card_redirect_details: Vec<Provider> = Vec::new();
let mut open_banking_details: Vec<Provider> = Vec::new();
let mut mobile_payment_details: Vec<Provider> = Vec::new();
if let Some(payment_methods_enabled) = response.payment_methods_enabled.clone() {
for methods in payment_methods_enabled {
match methods.payment_method {
api_models::enums::PaymentMethod::Card => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
match method_type.payment_method_type {
api_models::enums::PaymentMethodType::Credit => {
if let Some(card_networks) = method_type.card_networks {
for card in card_networks {
credit_details.push(CardProvider {
payment_method_type: card,
accepted_currencies: method_type
.accepted_currencies
.clone(),
accepted_countries: method_type
.accepted_countries
.clone(),
})
}
}
}
api_models::enums::PaymentMethodType::Debit => {
if let Some(card_networks) = method_type.card_networks {
for card in card_networks {
// debit_details.push(card)
debit_details.push(CardProvider {
payment_method_type: card,
accepted_currencies: method_type
.accepted_currencies
.clone(),
accepted_countries: method_type
.accepted_countries
.clone(),
})
}
}
}
_ => (),
}
}
}
}
api_models::enums::PaymentMethod::Wallet => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
// wallet_details.push(method_type.payment_method_type)
wallet_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::BankRedirect => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
bank_redirect_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::PayLater => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
pay_later_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::BankTransfer => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
bank_transfer_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::Crypto => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
crypto_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::BankDebit => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
bank_debit_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::Reward => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
reward_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::RealTimePayment => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
real_time_payment_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::OpenBanking => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
open_banking_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::Upi => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
upi_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::Voucher => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
voucher_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::GiftCard => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
gift_card_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::CardRedirect => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
card_redirect_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::MobilePayment => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
mobile_payment_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
}
}
}
let open_banking = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::OpenBanking,
payment_method_type: api_models::enums::PaymentMethod::OpenBanking.to_string(),
provider: Some(open_banking_details),
card_provider: None,
};
let upi = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::Upi,
payment_method_type: api_models::enums::PaymentMethod::Upi.to_string(),
provider: Some(upi_details),
card_provider: None,
};
let voucher: DashboardPaymentMethodPayload = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::Voucher,
payment_method_type: api_models::enums::PaymentMethod::Voucher.to_string(),
provider: Some(voucher_details),
card_provider: None,
};
let gift_card: DashboardPaymentMethodPayload = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::GiftCard,
payment_method_type: api_models::enums::PaymentMethod::GiftCard.to_string(),
provider: Some(gift_card_details),
card_provider: None,
};
let reward = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::Reward,
payment_method_type: api_models::enums::PaymentMethod::Reward.to_string(),
provider: Some(reward_details),
card_provider: None,
};
let real_time_payment = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::RealTimePayment,
payment_method_type: api_models::enums::PaymentMethod::RealTimePayment.to_string(),
provider: Some(real_time_payment_details),
card_provider: None,
};
let wallet = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::Wallet,
payment_method_type: api_models::enums::PaymentMethod::Wallet.to_string(),
provider: Some(wallet_details),
card_provider: None,
};
let bank_redirect = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::BankRedirect,
payment_method_type: api_models::enums::PaymentMethod::BankRedirect.to_string(),
provider: Some(bank_redirect_details),
card_provider: None,
};
let bank_debit = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::BankDebit,
payment_method_type: api_models::enums::PaymentMethod::BankDebit.to_string(),
provider: Some(bank_debit_details),
card_provider: None,
};
let bank_transfer = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::BankTransfer,
payment_method_type: api_models::enums::PaymentMethod::BankTransfer.to_string(),
provider: Some(bank_transfer_details),
card_provider: None,
};
let crypto = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::Crypto,
payment_method_type: api_models::enums::PaymentMethod::Crypto.to_string(),
provider: Some(crypto_details),
card_provider: None,
};
let card_redirect = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::CardRedirect,
payment_method_type: api_models::enums::PaymentMethod::CardRedirect.to_string(),
provider: Some(card_redirect_details),
card_provider: None,
};
let pay_later = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::PayLater,
payment_method_type: api_models::enums::PaymentMethod::PayLater.to_string(),
provider: Some(pay_later_details),
card_provider: None,
};
let debit_details = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::Card,
payment_method_type: api_models::enums::PaymentMethodType::Debit.to_string(),
provider: None,
card_provider: Some(debit_details),
};
let credit_details = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::Card,
payment_method_type: api_models::enums::PaymentMethodType::Credit.to_string(),
provider: None,
card_provider: Some(credit_details),
};
DashboardRequestPayload {
connector: response.connector_name,
payment_methods_enabled: Some(vec![
open_banking,
upi,
voucher,
reward,
real_time_payment,
wallet,
bank_redirect,
bank_debit,
bank_transfer,
crypto,
card_redirect,
pay_later,
debit_details,
credit_details,
gift_card,
]),
metadata: response.metadata,
}
}
}
</file>
|
{
"crate": "connector_configs",
"file": "crates/connector_configs/src/response_modifier.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2938
}
|
large_file_-7429175404890731431
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: connector_configs
File: crates/connector_configs/src/connector.rs
</path>
<file>
use std::collections::HashMap;
#[cfg(feature = "payouts")]
use api_models::enums::PayoutConnectors;
use api_models::{
enums::{AuthenticationConnectors, Connector, PmAuthConnectors, TaxConnectors},
payments,
};
use serde::{Deserialize, Serialize};
use toml;
use crate::common_config::{CardProvider, InputData, Provider, ZenApplePay};
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PayloadCurrencyAuthKeyType {
pub api_key: String,
pub processing_account_id: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct Classic {
pub password_classic: String,
pub username_classic: String,
pub merchant_id_classic: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct Evoucher {
pub password_evoucher: String,
pub username_evoucher: String,
pub merchant_id_evoucher: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct CashtoCodeCurrencyAuthKeyType {
pub classic: Classic,
pub evoucher: Evoucher,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CurrencyAuthValue {
CashtoCode(CashtoCodeCurrencyAuthKeyType),
Payload(PayloadCurrencyAuthKeyType),
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub enum ConnectorAuthType {
HeaderKey {
api_key: String,
},
BodyKey {
api_key: String,
key1: String,
},
SignatureKey {
api_key: String,
key1: String,
api_secret: String,
},
MultiAuthKey {
api_key: String,
key1: String,
api_secret: String,
key2: String,
},
CurrencyAuthKey {
auth_key_map: HashMap<String, CurrencyAuthValue>,
},
CertificateAuth {
certificate: String,
private_key: String,
},
#[default]
NoKey,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum ApplePayTomlConfig {
Standard(Box<payments::ApplePayMetadata>),
Zen(ZenApplePay),
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum KlarnaEndpoint {
Europe,
NorthAmerica,
Oceania,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ConfigMerchantAdditionalDetails {
pub open_banking_recipient_data: Option<InputData>,
pub account_data: Option<InputData>,
pub iban: Option<Vec<InputData>>,
pub bacs: Option<Vec<InputData>>,
pub connector_recipient_id: Option<InputData>,
pub wallet_id: Option<InputData>,
pub faster_payments: Option<Vec<InputData>>,
pub sepa: Option<Vec<InputData>>,
pub sepa_instant: Option<Vec<InputData>>,
pub elixir: Option<Vec<InputData>>,
pub bankgiro: Option<Vec<InputData>>,
pub plusgiro: Option<Vec<InputData>>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct AccountIdConfigForCard {
pub three_ds: Option<Vec<InputData>>,
pub no_three_ds: Option<Vec<InputData>>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct AccountIdConfigForRedirect {
pub three_ds: Option<Vec<InputData>>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct AccountIdConfigForApplePay {
pub encrypt: Option<Vec<InputData>>,
pub decrypt: Option<Vec<InputData>>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct AccountIDSupportedMethods {
apple_pay: HashMap<String, AccountIdConfigForApplePay>,
card: HashMap<String, AccountIdConfigForCard>,
interac: HashMap<String, AccountIdConfigForRedirect>,
pay_safe_card: HashMap<String, AccountIdConfigForRedirect>,
skrill: HashMap<String, AccountIdConfigForRedirect>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ConfigMetadata {
pub merchant_config_currency: Option<InputData>,
pub merchant_account_id: Option<InputData>,
pub account_name: Option<InputData>,
pub account_type: Option<InputData>,
pub terminal_id: Option<InputData>,
pub google_pay: Option<Vec<InputData>>,
pub apple_pay: Option<Vec<InputData>>,
pub merchant_id: Option<InputData>,
pub endpoint_prefix: Option<InputData>,
pub mcc: Option<InputData>,
pub merchant_country_code: Option<InputData>,
pub merchant_name: Option<InputData>,
pub acquirer_bin: Option<InputData>,
pub acquirer_merchant_id: Option<InputData>,
pub acquirer_country_code: Option<InputData>,
pub three_ds_requestor_name: Option<InputData>,
pub three_ds_requestor_id: Option<InputData>,
pub pull_mechanism_for_external_3ds_enabled: Option<InputData>,
pub klarna_region: Option<InputData>,
pub pricing_type: Option<InputData>,
pub source_balance_account: Option<InputData>,
pub brand_id: Option<InputData>,
pub destination_account_number: Option<InputData>,
pub dpa_id: Option<InputData>,
pub dpa_name: Option<InputData>,
pub locale: Option<InputData>,
pub card_brands: Option<InputData>,
pub merchant_category_code: Option<InputData>,
pub merchant_configuration_id: Option<InputData>,
pub currency_id: Option<InputData>,
pub platform_id: Option<InputData>,
pub ledger_account_id: Option<InputData>,
pub tenant_id: Option<InputData>,
pub platform_url: Option<InputData>,
pub report_group: Option<InputData>,
pub proxy_url: Option<InputData>,
pub shop_name: Option<InputData>,
pub merchant_funding_source: Option<InputData>,
pub account_id: Option<AccountIDSupportedMethods>,
pub name: Option<InputData>,
pub client_merchant_reference_id: Option<InputData>,
pub route: Option<InputData>,
pub mid: Option<InputData>,
pub tid: Option<InputData>,
pub site: Option<InputData>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ConnectorWalletDetailsConfig {
pub samsung_pay: Option<Vec<InputData>>,
pub paze: Option<Vec<InputData>>,
pub google_pay: Option<Vec<InputData>>,
pub amazon_pay: Option<Vec<InputData>>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ConnectorTomlConfig {
pub connector_auth: Option<ConnectorAuthType>,
pub connector_webhook_details: Option<api_models::admin::MerchantConnectorWebhookDetails>,
pub metadata: Option<Box<ConfigMetadata>>,
pub connector_wallets_details: Option<Box<ConnectorWalletDetailsConfig>>,
pub additional_merchant_data: Option<Box<ConfigMerchantAdditionalDetails>>,
pub credit: Option<Vec<CardProvider>>,
pub debit: Option<Vec<CardProvider>>,
pub bank_transfer: Option<Vec<Provider>>,
pub bank_redirect: Option<Vec<Provider>>,
pub bank_debit: Option<Vec<Provider>>,
pub open_banking: Option<Vec<Provider>>,
pub pay_later: Option<Vec<Provider>>,
pub wallet: Option<Vec<Provider>>,
pub crypto: Option<Vec<Provider>>,
pub reward: Option<Vec<Provider>>,
pub upi: Option<Vec<Provider>>,
pub voucher: Option<Vec<Provider>>,
pub gift_card: Option<Vec<Provider>>,
pub card_redirect: Option<Vec<Provider>>,
pub is_verifiable: Option<bool>,
pub real_time_payment: Option<Vec<Provider>>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ConnectorConfig {
pub authipay: Option<ConnectorTomlConfig>,
pub juspaythreedsserver: Option<ConnectorTomlConfig>,
pub katapult: Option<ConnectorTomlConfig>,
pub aci: Option<ConnectorTomlConfig>,
pub adyen: Option<ConnectorTomlConfig>,
pub affirm: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub adyen_payout: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub adyenplatform_payout: Option<ConnectorTomlConfig>,
pub airwallex: Option<ConnectorTomlConfig>,
pub amazonpay: Option<ConnectorTomlConfig>,
pub archipel: Option<ConnectorTomlConfig>,
pub authorizedotnet: Option<ConnectorTomlConfig>,
pub bamboraapac: Option<ConnectorTomlConfig>,
pub bankofamerica: Option<ConnectorTomlConfig>,
pub barclaycard: Option<ConnectorTomlConfig>,
pub billwerk: Option<ConnectorTomlConfig>,
pub bitpay: Option<ConnectorTomlConfig>,
pub blackhawknetwork: Option<ConnectorTomlConfig>,
pub calida: Option<ConnectorTomlConfig>,
pub bluesnap: Option<ConnectorTomlConfig>,
pub boku: Option<ConnectorTomlConfig>,
pub braintree: Option<ConnectorTomlConfig>,
pub breadpay: Option<ConnectorTomlConfig>,
pub cardinal: Option<ConnectorTomlConfig>,
pub cashtocode: Option<ConnectorTomlConfig>,
pub celero: Option<ConnectorTomlConfig>,
pub chargebee: Option<ConnectorTomlConfig>,
pub custombilling: Option<ConnectorTomlConfig>,
pub checkbook: Option<ConnectorTomlConfig>,
pub checkout: Option<ConnectorTomlConfig>,
pub coinbase: Option<ConnectorTomlConfig>,
pub coingate: Option<ConnectorTomlConfig>,
pub cryptopay: Option<ConnectorTomlConfig>,
pub ctp_visa: Option<ConnectorTomlConfig>,
pub cybersource: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub cybersource_payout: Option<ConnectorTomlConfig>,
pub iatapay: Option<ConnectorTomlConfig>,
pub itaubank: Option<ConnectorTomlConfig>,
pub opennode: Option<ConnectorTomlConfig>,
pub bambora: Option<ConnectorTomlConfig>,
pub datatrans: Option<ConnectorTomlConfig>,
pub deutschebank: Option<ConnectorTomlConfig>,
pub digitalvirgo: Option<ConnectorTomlConfig>,
pub dlocal: Option<ConnectorTomlConfig>,
pub dwolla: Option<ConnectorTomlConfig>,
pub ebanx_payout: Option<ConnectorTomlConfig>,
pub elavon: Option<ConnectorTomlConfig>,
pub facilitapay: Option<ConnectorTomlConfig>,
pub finix: Option<ConnectorTomlConfig>,
pub fiserv: Option<ConnectorTomlConfig>,
pub fiservemea: Option<ConnectorTomlConfig>,
pub fiuu: Option<ConnectorTomlConfig>,
pub flexiti: Option<ConnectorTomlConfig>,
pub forte: Option<ConnectorTomlConfig>,
pub getnet: Option<ConnectorTomlConfig>,
pub gigadat: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub gigadat_payout: Option<ConnectorTomlConfig>,
pub globalpay: Option<ConnectorTomlConfig>,
pub globepay: Option<ConnectorTomlConfig>,
pub gocardless: Option<ConnectorTomlConfig>,
pub gpayments: Option<ConnectorTomlConfig>,
pub hipay: Option<ConnectorTomlConfig>,
pub helcim: Option<ConnectorTomlConfig>,
pub hyperswitch_vault: Option<ConnectorTomlConfig>,
pub hyperwallet: Option<ConnectorTomlConfig>,
pub inespay: Option<ConnectorTomlConfig>,
pub jpmorgan: Option<ConnectorTomlConfig>,
pub klarna: Option<ConnectorTomlConfig>,
pub loonio: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub loonio_payout: Option<ConnectorTomlConfig>,
pub mifinity: Option<ConnectorTomlConfig>,
pub mollie: Option<ConnectorTomlConfig>,
pub moneris: Option<ConnectorTomlConfig>,
pub mpgs: Option<ConnectorTomlConfig>,
pub multisafepay: Option<ConnectorTomlConfig>,
pub nexinets: Option<ConnectorTomlConfig>,
pub nexixpay: Option<ConnectorTomlConfig>,
pub nmi: Option<ConnectorTomlConfig>,
pub nomupay_payout: Option<ConnectorTomlConfig>,
pub noon: Option<ConnectorTomlConfig>,
pub nordea: Option<ConnectorTomlConfig>,
pub novalnet: Option<ConnectorTomlConfig>,
pub nuvei_payout: Option<ConnectorTomlConfig>,
pub nuvei: Option<ConnectorTomlConfig>,
pub paybox: Option<ConnectorTomlConfig>,
pub payload: Option<ConnectorTomlConfig>,
pub payme: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub payone_payout: Option<ConnectorTomlConfig>,
pub paypal: Option<ConnectorTomlConfig>,
pub paysafe: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub paypal_payout: Option<ConnectorTomlConfig>,
pub paystack: Option<ConnectorTomlConfig>,
pub paytm: Option<ConnectorTomlConfig>,
pub payu: Option<ConnectorTomlConfig>,
pub peachpayments: Option<ConnectorTomlConfig>,
pub phonepe: Option<ConnectorTomlConfig>,
pub placetopay: Option<ConnectorTomlConfig>,
pub plaid: Option<ConnectorTomlConfig>,
pub powertranz: Option<ConnectorTomlConfig>,
pub prophetpay: Option<ConnectorTomlConfig>,
pub razorpay: Option<ConnectorTomlConfig>,
pub recurly: Option<ConnectorTomlConfig>,
pub riskified: Option<ConnectorTomlConfig>,
pub rapyd: Option<ConnectorTomlConfig>,
pub redsys: Option<ConnectorTomlConfig>,
pub santander: Option<ConnectorTomlConfig>,
pub shift4: Option<ConnectorTomlConfig>,
pub sift: Option<ConnectorTomlConfig>,
pub silverflow: Option<ConnectorTomlConfig>,
pub stripe: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub stripe_payout: Option<ConnectorTomlConfig>,
pub stripebilling: Option<ConnectorTomlConfig>,
pub signifyd: Option<ConnectorTomlConfig>,
pub tersouro: Option<ConnectorTomlConfig>,
pub tokenex: Option<ConnectorTomlConfig>,
pub tokenio: Option<ConnectorTomlConfig>,
pub trustpay: Option<ConnectorTomlConfig>,
pub trustpayments: Option<ConnectorTomlConfig>,
pub threedsecureio: Option<ConnectorTomlConfig>,
pub netcetera: Option<ConnectorTomlConfig>,
pub tsys: Option<ConnectorTomlConfig>,
pub vgs: Option<ConnectorTomlConfig>,
pub volt: Option<ConnectorTomlConfig>,
pub wellsfargo: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub wise_payout: Option<ConnectorTomlConfig>,
pub worldline: Option<ConnectorTomlConfig>,
pub worldpay: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub worldpay_payout: Option<ConnectorTomlConfig>,
pub worldpayvantiv: Option<ConnectorTomlConfig>,
pub worldpayxml: Option<ConnectorTomlConfig>,
pub xendit: Option<ConnectorTomlConfig>,
pub square: Option<ConnectorTomlConfig>,
pub stax: Option<ConnectorTomlConfig>,
pub dummy_connector: Option<ConnectorTomlConfig>,
pub stripe_test: Option<ConnectorTomlConfig>,
pub paypal_test: Option<ConnectorTomlConfig>,
pub zen: Option<ConnectorTomlConfig>,
pub zsl: Option<ConnectorTomlConfig>,
pub taxjar: Option<ConnectorTomlConfig>,
pub tesouro: Option<ConnectorTomlConfig>,
pub ctp_mastercard: Option<ConnectorTomlConfig>,
pub unified_authentication_service: Option<ConnectorTomlConfig>,
}
impl ConnectorConfig {
fn new() -> Result<Self, String> {
let config_str = if cfg!(feature = "production") {
include_str!("../toml/production.toml")
} else if cfg!(feature = "sandbox") {
include_str!("../toml/sandbox.toml")
} else {
include_str!("../toml/development.toml")
};
let config = toml::from_str::<Self>(config_str);
match config {
Ok(data) => Ok(data),
Err(err) => Err(err.to_string()),
}
}
#[cfg(feature = "payouts")]
pub fn get_payout_connector_config(
connector: PayoutConnectors,
) -> Result<Option<ConnectorTomlConfig>, String> {
let connector_data = Self::new()?;
match connector {
PayoutConnectors::Adyen => Ok(connector_data.adyen_payout),
PayoutConnectors::Adyenplatform => Ok(connector_data.adyenplatform_payout),
PayoutConnectors::Cybersource => Ok(connector_data.cybersource_payout),
PayoutConnectors::Ebanx => Ok(connector_data.ebanx_payout),
PayoutConnectors::Gigadat => Ok(connector_data.gigadat_payout),
PayoutConnectors::Loonio => Ok(connector_data.loonio_payout),
PayoutConnectors::Nomupay => Ok(connector_data.nomupay_payout),
PayoutConnectors::Nuvei => Ok(connector_data.nuvei_payout),
PayoutConnectors::Payone => Ok(connector_data.payone_payout),
PayoutConnectors::Paypal => Ok(connector_data.paypal_payout),
PayoutConnectors::Stripe => Ok(connector_data.stripe_payout),
PayoutConnectors::Wise => Ok(connector_data.wise_payout),
PayoutConnectors::Worldpay => Ok(connector_data.worldpay_payout),
}
}
pub fn get_authentication_connector_config(
connector: AuthenticationConnectors,
) -> Result<Option<ConnectorTomlConfig>, String> {
let connector_data = Self::new()?;
match connector {
AuthenticationConnectors::Threedsecureio => Ok(connector_data.threedsecureio),
AuthenticationConnectors::Netcetera => Ok(connector_data.netcetera),
AuthenticationConnectors::Gpayments => Ok(connector_data.gpayments),
AuthenticationConnectors::CtpMastercard => Ok(connector_data.ctp_mastercard),
AuthenticationConnectors::CtpVisa => Ok(connector_data.ctp_visa),
AuthenticationConnectors::UnifiedAuthenticationService => {
Ok(connector_data.unified_authentication_service)
}
AuthenticationConnectors::Juspaythreedsserver => Ok(connector_data.juspaythreedsserver),
AuthenticationConnectors::Cardinal => Ok(connector_data.cardinal),
}
}
pub fn get_tax_processor_config(
connector: TaxConnectors,
) -> Result<Option<ConnectorTomlConfig>, String> {
let connector_data = Self::new()?;
match connector {
TaxConnectors::Taxjar => Ok(connector_data.taxjar),
}
}
pub fn get_pm_authentication_processor_config(
connector: PmAuthConnectors,
) -> Result<Option<ConnectorTomlConfig>, String> {
let connector_data = Self::new()?;
match connector {
PmAuthConnectors::Plaid => Ok(connector_data.plaid),
}
}
pub fn get_connector_config(
connector: Connector,
) -> Result<Option<ConnectorTomlConfig>, String> {
let connector_data = Self::new()?;
match connector {
Connector::Aci => Ok(connector_data.aci),
Connector::Authipay => Ok(connector_data.authipay),
Connector::Adyen => Ok(connector_data.adyen),
Connector::Affirm => Ok(connector_data.affirm),
Connector::Adyenplatform => Err("Use get_payout_connector_config".to_string()),
Connector::Airwallex => Ok(connector_data.airwallex),
Connector::Amazonpay => Ok(connector_data.amazonpay),
Connector::Archipel => Ok(connector_data.archipel),
Connector::Authorizedotnet => Ok(connector_data.authorizedotnet),
Connector::Bamboraapac => Ok(connector_data.bamboraapac),
Connector::Bankofamerica => Ok(connector_data.bankofamerica),
Connector::Barclaycard => Ok(connector_data.barclaycard),
Connector::Billwerk => Ok(connector_data.billwerk),
Connector::Bitpay => Ok(connector_data.bitpay),
Connector::Bluesnap => Ok(connector_data.bluesnap),
Connector::Calida => Ok(connector_data.calida),
Connector::Blackhawknetwork => Ok(connector_data.blackhawknetwork),
Connector::Boku => Ok(connector_data.boku),
Connector::Braintree => Ok(connector_data.braintree),
Connector::Breadpay => Ok(connector_data.breadpay),
Connector::Cashtocode => Ok(connector_data.cashtocode),
Connector::Cardinal => Ok(connector_data.cardinal),
Connector::Celero => Ok(connector_data.celero),
Connector::Chargebee => Ok(connector_data.chargebee),
Connector::Checkbook => Ok(connector_data.checkbook),
Connector::Checkout => Ok(connector_data.checkout),
Connector::Coinbase => Ok(connector_data.coinbase),
Connector::Coingate => Ok(connector_data.coingate),
Connector::Cryptopay => Ok(connector_data.cryptopay),
Connector::CtpVisa => Ok(connector_data.ctp_visa),
Connector::Custombilling => Ok(connector_data.custombilling),
Connector::Cybersource => Ok(connector_data.cybersource),
#[cfg(feature = "dummy_connector")]
Connector::DummyBillingConnector => Ok(connector_data.dummy_connector),
Connector::Iatapay => Ok(connector_data.iatapay),
Connector::Itaubank => Ok(connector_data.itaubank),
Connector::Opennode => Ok(connector_data.opennode),
Connector::Bambora => Ok(connector_data.bambora),
Connector::Datatrans => Ok(connector_data.datatrans),
Connector::Deutschebank => Ok(connector_data.deutschebank),
Connector::Digitalvirgo => Ok(connector_data.digitalvirgo),
Connector::Dlocal => Ok(connector_data.dlocal),
Connector::Dwolla => Ok(connector_data.dwolla),
Connector::Ebanx => Ok(connector_data.ebanx_payout),
Connector::Elavon => Ok(connector_data.elavon),
Connector::Facilitapay => Ok(connector_data.facilitapay),
Connector::Finix => Ok(connector_data.finix),
Connector::Fiserv => Ok(connector_data.fiserv),
Connector::Fiservemea => Ok(connector_data.fiservemea),
Connector::Fiuu => Ok(connector_data.fiuu),
Connector::Flexiti => Ok(connector_data.flexiti),
Connector::Forte => Ok(connector_data.forte),
Connector::Getnet => Ok(connector_data.getnet),
Connector::Gigadat => Ok(connector_data.gigadat),
Connector::Globalpay => Ok(connector_data.globalpay),
Connector::Globepay => Ok(connector_data.globepay),
Connector::Gocardless => Ok(connector_data.gocardless),
Connector::Gpayments => Ok(connector_data.gpayments),
Connector::Hipay => Ok(connector_data.hipay),
Connector::HyperswitchVault => Ok(connector_data.hyperswitch_vault),
Connector::Helcim => Ok(connector_data.helcim),
Connector::Inespay => Ok(connector_data.inespay),
Connector::Jpmorgan => Ok(connector_data.jpmorgan),
Connector::Juspaythreedsserver => Ok(connector_data.juspaythreedsserver),
Connector::Klarna => Ok(connector_data.klarna),
Connector::Loonio => Ok(connector_data.loonio),
Connector::Mifinity => Ok(connector_data.mifinity),
Connector::Mollie => Ok(connector_data.mollie),
Connector::Moneris => Ok(connector_data.moneris),
Connector::Multisafepay => Ok(connector_data.multisafepay),
Connector::Nexinets => Ok(connector_data.nexinets),
Connector::Nexixpay => Ok(connector_data.nexixpay),
Connector::Prophetpay => Ok(connector_data.prophetpay),
Connector::Nmi => Ok(connector_data.nmi),
Connector::Nordea => Ok(connector_data.nordea),
Connector::Nomupay => Err("Use get_payout_connector_config".to_string()),
Connector::Novalnet => Ok(connector_data.novalnet),
Connector::Noon => Ok(connector_data.noon),
Connector::Nuvei => Ok(connector_data.nuvei),
Connector::Paybox => Ok(connector_data.paybox),
Connector::Payload => Ok(connector_data.payload),
Connector::Payme => Ok(connector_data.payme),
Connector::Payone => Err("Use get_payout_connector_config".to_string()),
Connector::Paypal => Ok(connector_data.paypal),
Connector::Paysafe => Ok(connector_data.paysafe),
Connector::Paystack => Ok(connector_data.paystack),
Connector::Payu => Ok(connector_data.payu),
Connector::Peachpayments => Ok(connector_data.peachpayments),
Connector::Placetopay => Ok(connector_data.placetopay),
Connector::Plaid => Ok(connector_data.plaid),
Connector::Powertranz => Ok(connector_data.powertranz),
Connector::Razorpay => Ok(connector_data.razorpay),
Connector::Rapyd => Ok(connector_data.rapyd),
Connector::Recurly => Ok(connector_data.recurly),
Connector::Redsys => Ok(connector_data.redsys),
Connector::Riskified => Ok(connector_data.riskified),
Connector::Santander => Ok(connector_data.santander),
Connector::Shift4 => Ok(connector_data.shift4),
Connector::Signifyd => Ok(connector_data.signifyd),
Connector::Silverflow => Ok(connector_data.silverflow),
Connector::Square => Ok(connector_data.square),
Connector::Stax => Ok(connector_data.stax),
Connector::Stripe => Ok(connector_data.stripe),
Connector::Stripebilling => Ok(connector_data.stripebilling),
Connector::Tesouro => Ok(connector_data.tesouro),
Connector::Tokenex => Ok(connector_data.tokenex),
Connector::Tokenio => Ok(connector_data.tokenio),
Connector::Trustpay => Ok(connector_data.trustpay),
Connector::Trustpayments => Ok(connector_data.trustpayments),
Connector::Threedsecureio => Ok(connector_data.threedsecureio),
Connector::Taxjar => Ok(connector_data.taxjar),
Connector::Tsys => Ok(connector_data.tsys),
Connector::Vgs => Ok(connector_data.vgs),
Connector::Volt => Ok(connector_data.volt),
Connector::Wellsfargo => Ok(connector_data.wellsfargo),
Connector::Wise => Err("Use get_payout_connector_config".to_string()),
Connector::Worldline => Ok(connector_data.worldline),
Connector::Worldpay => Ok(connector_data.worldpay),
Connector::Worldpayvantiv => Ok(connector_data.worldpayvantiv),
Connector::Worldpayxml => Ok(connector_data.worldpayxml),
Connector::Zen => Ok(connector_data.zen),
Connector::Zsl => Ok(connector_data.zsl),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector1 => Ok(connector_data.dummy_connector),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector2 => Ok(connector_data.dummy_connector),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector3 => Ok(connector_data.dummy_connector),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector4 => Ok(connector_data.stripe_test),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector5 => Ok(connector_data.dummy_connector),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector6 => Ok(connector_data.dummy_connector),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector7 => Ok(connector_data.paypal_test),
Connector::Netcetera => Ok(connector_data.netcetera),
Connector::CtpMastercard => Ok(connector_data.ctp_mastercard),
Connector::Xendit => Ok(connector_data.xendit),
Connector::Paytm => Ok(connector_data.paytm),
Connector::Phonepe => Ok(connector_data.phonepe),
}
}
}
</file>
|
{
"crate": "connector_configs",
"file": "crates/connector_configs/src/connector.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6426
}
|
large_file_-9171746674879910149
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: test_utils
File: crates/test_utils/tests/connectors/selenium.rs
</path>
<file>
#![allow(
clippy::expect_used,
clippy::panic,
clippy::unwrap_in_result,
clippy::missing_panics_doc,
clippy::unwrap_used
)]
use std::{
collections::{HashMap, HashSet},
env,
io::Read,
path::{MAIN_SEPARATOR, MAIN_SEPARATOR_STR},
time::Duration,
};
use async_trait::async_trait;
use base64::Engine;
use serde::{Deserialize, Serialize};
use serde_json::json;
use test_utils::connector_auth;
use thirtyfour::{components::SelectElement, prelude::*, WebDriver};
#[derive(Clone)]
pub enum Event<'a> {
RunIf(Assert<'a>, Vec<Event<'a>>),
EitherOr(Assert<'a>, Vec<Event<'a>>, Vec<Event<'a>>),
Assert(Assert<'a>),
Trigger(Trigger<'a>),
}
#[derive(Clone)]
#[allow(dead_code)]
pub enum Trigger<'a> {
Goto(&'a str),
Click(By),
ClickNth(By, usize),
SelectOption(By, &'a str),
ChangeQueryParam(&'a str, &'a str),
SwitchTab(Position),
SwitchFrame(By),
Find(By),
Query(By),
SendKeys(By, &'a str),
Sleep(u64),
}
#[derive(Clone)]
pub enum Position {
Prev,
Next,
}
#[derive(Clone)]
pub enum Selector {
Title,
QueryParamStr,
}
#[derive(Clone)]
pub enum Assert<'a> {
Eq(Selector, &'a str),
Contains(Selector, &'a str),
ContainsAny(Selector, Vec<&'a str>),
EitherOfThemExist(&'a str, &'a str),
IsPresent(&'a str),
IsElePresent(By),
IsPresentNow(&'a str),
}
pub static CHECKOUT_BASE_URL: &str = "https://hs-payments-test.netlify.app";
#[async_trait]
pub trait SeleniumTest {
fn get_saved_testcases(&self) -> serde_json::Value {
get_saved_testcases()
}
fn get_configs(&self) -> connector_auth::ConnectorAuthentication {
get_configs()
}
async fn retry_click(
&self,
times: i32,
interval: u64,
driver: &WebDriver,
by: By,
) -> Result<(), WebDriverError> {
let mut res = Ok(());
for _i in 0..times {
res = self.click_element(driver, by.clone()).await;
if res.is_err() {
tokio::time::sleep(Duration::from_secs(interval)).await;
} else {
break;
}
}
return res;
}
fn get_connector_name(&self) -> String;
async fn complete_actions(
&self,
driver: &WebDriver,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
for action in actions {
match action {
Event::Assert(assert) => match assert {
Assert::Contains(selector, text) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
assert!(url.query().unwrap().contains(text))
}
_ => assert!(driver.title().await?.contains(text)),
},
Assert::ContainsAny(selector, search_keys) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
assert!(search_keys
.iter()
.any(|key| url.query().unwrap().contains(key)))
}
_ => assert!(driver.title().await?.contains(search_keys.first().unwrap())),
},
Assert::EitherOfThemExist(text_1, text_2) => assert!(
is_text_present_now(driver, text_1).await?
|| is_text_present_now(driver, text_2).await?
),
Assert::Eq(_selector, text) => assert_eq!(driver.title().await?, text),
Assert::IsPresent(text) => {
assert!(is_text_present(driver, text).await?)
}
Assert::IsElePresent(selector) => {
assert!(is_element_present(driver, selector).await?)
}
Assert::IsPresentNow(text) => {
assert!(is_text_present_now(driver, text).await?)
}
},
Event::RunIf(con_event, events) => match con_event {
Assert::Contains(selector, text) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
if url.query().unwrap().contains(text) {
self.complete_actions(driver, events).await?;
}
}
_ => assert!(driver.title().await?.contains(text)),
},
Assert::ContainsAny(selector, keys) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
if keys.iter().any(|key| url.query().unwrap().contains(key)) {
self.complete_actions(driver, events).await?;
}
}
_ => assert!(driver.title().await?.contains(keys.first().unwrap())),
},
Assert::Eq(_selector, text) => {
if text == driver.title().await? {
self.complete_actions(driver, events).await?;
}
}
Assert::EitherOfThemExist(text_1, text_2) => {
if is_text_present_now(driver, text_1).await.is_ok()
|| is_text_present_now(driver, text_2).await.is_ok()
{
self.complete_actions(driver, events).await?;
}
}
Assert::IsPresent(text) => {
if is_text_present(driver, text).await.is_ok() {
self.complete_actions(driver, events).await?;
}
}
Assert::IsElePresent(text) => {
if is_element_present(driver, text).await.is_ok() {
self.complete_actions(driver, events).await?;
}
}
Assert::IsPresentNow(text) => {
if is_text_present_now(driver, text).await.is_ok() {
self.complete_actions(driver, events).await?;
}
}
},
Event::EitherOr(con_event, success, failure) => match con_event {
Assert::Contains(selector, text) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
self.complete_actions(
driver,
if url.query().unwrap().contains(text) {
success
} else {
failure
},
)
.await?;
}
_ => assert!(driver.title().await?.contains(text)),
},
Assert::ContainsAny(selector, keys) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
self.complete_actions(
driver,
if keys.iter().any(|key| url.query().unwrap().contains(key)) {
success
} else {
failure
},
)
.await?;
}
_ => assert!(driver.title().await?.contains(keys.first().unwrap())),
},
Assert::Eq(_selector, text) => {
self.complete_actions(
driver,
if text == driver.title().await? {
success
} else {
failure
},
)
.await?;
}
Assert::EitherOfThemExist(text_1, text_2) => {
self.complete_actions(
driver,
if is_text_present_now(driver, text_1).await.is_ok()
|| is_text_present_now(driver, text_2).await.is_ok()
{
success
} else {
failure
},
)
.await?;
}
Assert::IsPresent(text) => {
self.complete_actions(
driver,
if is_text_present(driver, text).await.is_ok() {
success
} else {
failure
},
)
.await?;
}
Assert::IsElePresent(by) => {
self.complete_actions(
driver,
if is_element_present(driver, by).await.is_ok() {
success
} else {
failure
},
)
.await?;
}
Assert::IsPresentNow(text) => {
self.complete_actions(
driver,
if is_text_present_now(driver, text).await.is_ok() {
success
} else {
failure
},
)
.await?;
}
},
Event::Trigger(trigger) => match trigger {
Trigger::Goto(url) => {
let saved_tests =
serde_json::to_string(&self.get_saved_testcases()).unwrap();
let conf = serde_json::to_string(&self.get_configs()).unwrap();
let configs = self.get_configs().automation_configs.unwrap();
let hs_base_url = configs
.hs_base_url
.unwrap_or_else(|| "http://localhost:8080".to_string());
let configs_url = configs.configs_url.unwrap();
let hs_api_keys = configs.hs_api_keys.unwrap();
let test_env = configs.hs_test_env.unwrap();
let script = &[
format!("localStorage.configs='{configs_url}'").as_str(),
format!("localStorage.current_env='{test_env}'").as_str(),
"localStorage.hs_api_key=''",
format!("localStorage.hs_api_keys='{hs_api_keys}'").as_str(),
format!("localStorage.base_url='{hs_base_url}'").as_str(),
format!("localStorage.hs_api_configs='{conf}'").as_str(),
format!("localStorage.saved_payments=JSON.stringify({saved_tests})")
.as_str(),
"localStorage.force_sync='true'",
format!(
"localStorage.current_connector=\"{}\";",
self.get_connector_name().clone()
)
.as_str(),
]
.join(";");
driver.goto(url).await?;
driver.execute(script, Vec::new()).await?;
}
Trigger::Click(by) => {
self.retry_click(3, 5, driver, by.clone()).await?;
}
Trigger::ClickNth(by, n) => {
let ele = driver.query(by).all().await?.into_iter().nth(n).unwrap();
ele.wait_until().enabled().await?;
ele.wait_until().displayed().await?;
ele.wait_until().clickable().await?;
ele.scroll_into_view().await?;
ele.click().await?;
}
Trigger::Find(by) => {
driver.find(by).await?;
}
Trigger::Query(by) => {
driver.query(by).first().await?;
}
Trigger::SendKeys(by, input) => {
let ele = driver.query(by).first().await?;
ele.wait_until().displayed().await?;
ele.send_keys(&input).await?;
}
Trigger::SelectOption(by, input) => {
let ele = driver.query(by).first().await?;
let select_element = SelectElement::new(&ele).await?;
select_element.select_by_partial_text(input).await?;
}
Trigger::ChangeQueryParam(param, value) => {
let mut url = driver.current_url().await?;
let mut hash_query: HashMap<String, String> =
url.query_pairs().into_owned().collect();
hash_query.insert(param.to_string(), value.to_string());
let url_str = serde_urlencoded::to_string(hash_query)
.expect("Query Param update failed");
url.set_query(Some(&url_str));
driver.goto(url.as_str()).await?;
}
Trigger::Sleep(seconds) => {
tokio::time::sleep(Duration::from_secs(seconds)).await;
}
Trigger::SwitchTab(position) => match position {
Position::Next => {
let windows = driver.windows().await?;
if let Some(window) = windows.iter().next_back() {
driver.switch_to_window(window.to_owned()).await?;
}
}
Position::Prev => {
let windows = driver.windows().await?;
if let Some(window) = windows.into_iter().next() {
driver.switch_to_window(window.to_owned()).await?;
}
}
},
Trigger::SwitchFrame(by) => {
let iframe = driver.query(by).first().await?;
iframe.wait_until().displayed().await?;
iframe.clone().enter_frame().await?;
}
},
}
}
Ok(())
}
async fn click_element(&self, driver: &WebDriver, by: By) -> Result<(), WebDriverError> {
let ele = driver.query(by).first().await?;
ele.wait_until().enabled().await?;
ele.wait_until().displayed().await?;
ele.wait_until().clickable().await?;
ele.scroll_into_view().await?;
ele.click().await
}
async fn make_redirection_payment(
&self,
web_driver: WebDriver,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
// To support failure retries
let result = self
.execute_steps(web_driver.clone(), actions.clone())
.await;
if result.is_err() {
self.execute_steps(web_driver, actions).await
} else {
result
}
}
async fn execute_steps(
&self,
web_driver: WebDriver,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
let config = self.get_configs().automation_configs.unwrap();
if config.run_minimum_steps.unwrap() {
self.complete_actions(&web_driver, actions.get(..3).unwrap().to_vec())
.await
} else {
self.complete_actions(&web_driver, actions).await
}
}
async fn make_gpay_payment(
&self,
web_driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
self.execute_gpay_steps(web_driver, url, actions).await
}
async fn execute_gpay_steps(
&self,
web_driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
let config = self.get_configs().automation_configs.unwrap();
let (email, pass) = (&config.gmail_email.unwrap(), &config.gmail_pass.unwrap());
let default_actions = vec![
Event::Trigger(Trigger::Goto(url)),
Event::Trigger(Trigger::Click(By::Css(".gpay-button"))),
Event::Trigger(Trigger::SwitchTab(Position::Next)),
Event::Trigger(Trigger::Sleep(5)),
Event::RunIf(
Assert::EitherOfThemExist("Use your Google Account", "Sign in"),
vec![
Event::Trigger(Trigger::SendKeys(By::Id("identifierId"), email)),
Event::Trigger(Trigger::ClickNth(By::Tag("button"), 2)),
Event::EitherOr(
Assert::IsPresent("Welcome"),
vec![
Event::Trigger(Trigger::SendKeys(By::Name("Passwd"), pass)),
Event::Trigger(Trigger::Sleep(2)),
Event::Trigger(Trigger::Click(By::Id("passwordNext"))),
Event::Trigger(Trigger::Sleep(10)),
],
vec![
Event::Trigger(Trigger::SendKeys(By::Id("identifierId"), email)),
Event::Trigger(Trigger::ClickNth(By::Tag("button"), 2)),
Event::Trigger(Trigger::SendKeys(By::Name("Passwd"), pass)),
Event::Trigger(Trigger::Sleep(2)),
Event::Trigger(Trigger::Click(By::Id("passwordNext"))),
Event::Trigger(Trigger::Sleep(10)),
],
),
],
),
Event::Trigger(Trigger::SwitchFrame(By::Css(
".bootstrapperIframeContainerElement iframe",
))),
Event::Assert(Assert::IsPresent("Gpay Tester")),
Event::Trigger(Trigger::Click(By::ClassName("jfk-button-action"))),
Event::Trigger(Trigger::SwitchTab(Position::Prev)),
];
self.complete_actions(&web_driver, default_actions).await?;
self.complete_actions(&web_driver, actions).await
}
async fn make_affirm_payment(
&self,
driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
self.complete_actions(
&driver,
vec![
Event::Trigger(Trigger::Goto(url)),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
],
)
.await?;
let mut affirm_actions = vec![
Event::RunIf(
Assert::IsPresent("Big purchase? No problem."),
vec![
Event::Trigger(Trigger::SendKeys(
By::Css("input[data-testid='phone-number-field']"),
"(833) 549-5574", // any test phone number accepted by affirm
)),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='submit-button']",
))),
Event::Trigger(Trigger::SendKeys(
By::Css("input[data-testid='phone-pin-field']"),
"1234",
)),
],
),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='skip-payment-button']",
))),
Event::Trigger(Trigger::Click(By::Css("div[data-testid='indicator']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='submit-button']",
))),
Event::Trigger(Trigger::Click(By::Css("div[data-testid='indicator']"))),
Event::Trigger(Trigger::Click(By::Css(
"div[data-testid='disclosure-checkbox-indicator']",
))),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='submit-button']",
))),
];
affirm_actions.extend(actions);
self.complete_actions(&driver, affirm_actions).await
}
async fn make_webhook_test(
&self,
web_driver: WebDriver,
payment_url: &str,
actions: Vec<Event<'_>>,
webhook_retry_time: u64,
webhook_status: &str,
) -> Result<(), WebDriverError> {
self.complete_actions(
&web_driver,
vec![Event::Trigger(Trigger::Goto(payment_url))],
)
.await?;
self.complete_actions(&web_driver, actions).await?; //additional actions needs to make a payment
self.complete_actions(
&web_driver,
vec![Event::Trigger(Trigger::Goto(&format!(
"{CHECKOUT_BASE_URL}/events"
)))],
)
.await?;
let element = web_driver.query(By::Css("h2.last-payment")).first().await?;
let payment_id = element.text().await?;
let retries = 3; // no of retry times
for _i in 0..retries {
let configs = self.get_configs().automation_configs.unwrap();
let outgoing_webhook_url = configs.hs_webhook_url.unwrap().to_string();
let client = reqwest::Client::new();
let response = client.get(outgoing_webhook_url).send().await.unwrap(); // get events from outgoing webhook endpoint
let body_text = response.text().await.unwrap();
let data: WebhookResponse = serde_json::from_str(&body_text).unwrap();
let last_three_events = data.data.get(data.data.len().saturating_sub(3)..).unwrap(); // Get the last three elements if available
for last_event in last_three_events {
let last_event_body = &last_event.step.request.body;
let decoded_bytes = base64::engine::general_purpose::STANDARD //decode the encoded outgoing webhook event
.decode(last_event_body)
.unwrap();
let decoded_str = String::from_utf8(decoded_bytes).unwrap();
let webhook_response: HsWebhookResponse =
serde_json::from_str(&decoded_str).unwrap();
if payment_id == webhook_response.content.object.payment_id
&& webhook_status == webhook_response.content.object.status
{
return Ok(());
}
}
self.complete_actions(
&web_driver,
vec![Event::Trigger(Trigger::Sleep(webhook_retry_time))],
)
.await?;
}
Err(WebDriverError::CustomError("Webhook Not Found".to_string()))
}
async fn make_paypal_payment(
&self,
web_driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
let pypl_url = url.to_string();
// To support failure retries
let result = self
.execute_paypal_steps(web_driver.clone(), &pypl_url, actions.clone())
.await;
if result.is_err() {
self.execute_paypal_steps(web_driver.clone(), &pypl_url, actions.clone())
.await
} else {
result
}
}
async fn execute_paypal_steps(
&self,
web_driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
self.complete_actions(
&web_driver,
vec![
Event::Trigger(Trigger::Goto(url)),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
],
)
.await?;
let (email, pass) = (
&self
.get_configs()
.automation_configs
.unwrap()
.pypl_email
.unwrap(),
&self
.get_configs()
.automation_configs
.unwrap()
.pypl_pass
.unwrap(),
);
let mut pypl_actions = vec![
Event::Trigger(Trigger::Sleep(8)),
Event::RunIf(
Assert::IsPresentNow("Enter your email address to get started"),
vec![
Event::Trigger(Trigger::SendKeys(By::Id("email"), email)),
Event::Trigger(Trigger::Click(By::Id("btnNext"))),
],
),
Event::RunIf(
Assert::IsPresentNow("Password"),
vec![
Event::Trigger(Trigger::SendKeys(By::Id("password"), pass)),
Event::Trigger(Trigger::Click(By::Id("btnLogin"))),
],
),
];
pypl_actions.extend(actions);
self.complete_actions(&web_driver, pypl_actions).await
}
async fn make_clearpay_payment(
&self,
driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
self.complete_actions(
&driver,
vec![
Event::Trigger(Trigger::Goto(url)),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(5)),
Event::RunIf(
Assert::IsPresentNow("Manage Cookies"),
vec![
Event::Trigger(Trigger::Click(By::Css("button.cookie-setting-link"))),
Event::Trigger(Trigger::Click(By::Id("accept-recommended-btn-handler"))),
],
),
],
)
.await?;
let (email, pass) = (
&self
.get_configs()
.automation_configs
.unwrap()
.clearpay_email
.unwrap(),
&self
.get_configs()
.automation_configs
.unwrap()
.clearpay_pass
.unwrap(),
);
let mut clearpay_actions = vec![
Event::Trigger(Trigger::Sleep(3)),
Event::EitherOr(
Assert::IsPresent("Please enter your password"),
vec![
Event::Trigger(Trigger::SendKeys(By::Css("input[name='password']"), pass)),
Event::Trigger(Trigger::Click(By::Css("button[type='submit']"))),
],
vec![
Event::Trigger(Trigger::SendKeys(
By::Css("input[name='identifier']"),
email,
)),
Event::Trigger(Trigger::Click(By::Css("button[type='submit']"))),
Event::Trigger(Trigger::Sleep(3)),
Event::Trigger(Trigger::SendKeys(By::Css("input[name='password']"), pass)),
Event::Trigger(Trigger::Click(By::Css("button[type='submit']"))),
],
),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='summary-button']",
))),
];
clearpay_actions.extend(actions);
self.complete_actions(&driver, clearpay_actions).await
}
}
async fn is_text_present_now(driver: &WebDriver, key: &str) -> WebDriverResult<bool> {
let mut xpath = "//*[contains(text(),'".to_owned();
xpath.push_str(key);
xpath.push_str("')]");
let result = driver.find(By::XPath(&xpath)).await?;
let display: &str = &result.css_value("display").await?;
if display.is_empty() || display == "none" {
return Err(WebDriverError::CustomError("Element is hidden".to_string()));
}
result.is_present().await
}
async fn is_text_present(driver: &WebDriver, key: &str) -> WebDriverResult<bool> {
let mut xpath = "//*[contains(text(),'".to_owned();
xpath.push_str(key);
xpath.push_str("')]");
let result = driver.query(By::XPath(&xpath)).first().await?;
result.is_present().await
}
async fn is_element_present(driver: &WebDriver, by: By) -> WebDriverResult<bool> {
let element = driver.query(by).first().await?;
element.is_present().await
}
#[macro_export]
macro_rules! tester_inner {
($execute:ident, $webdriver:expr) => {{
use std::{
sync::{Arc, Mutex},
thread,
};
let driver = $webdriver;
// we'll need the session_id from the thread
// NOTE: even if it panics, so can't just return it
let session_id = Arc::new(Mutex::new(None));
// run test in its own thread to catch panics
let sid = session_id.clone();
let res = thread::spawn(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let driver = runtime
.block_on(driver)
.expect("failed to construct test WebDriver");
*sid.lock().unwrap() = runtime.block_on(driver.session_id()).ok();
// make sure we close, even if an assertion fails
let client = driver.clone();
let x = runtime.block_on(async move {
let run = tokio::spawn($execute(driver)).await;
let _ = client.quit().await;
run
});
drop(runtime);
x.expect("test panicked")
})
.join();
let success = handle_test_error(res);
assert!(success);
}};
}
#[macro_export]
macro_rules! function {
() => {{
fn f() {}
fn type_name_of<T>(_: T) -> &'static str {
std::any::type_name::<T>()
}
let name = type_name_of(f);
&name.get(..name.len() - 3).unwrap()
}};
}
#[macro_export]
macro_rules! tester {
($f:ident) => {{
use $crate::{function, tester_inner};
let test_name = format!("{:?}", function!());
if (should_ignore_test(&test_name)) {
return;
}
let browser = get_browser();
let url = make_url(&browser);
let caps = make_capabilities(&browser);
tester_inner!($f, WebDriver::new(url, caps));
}};
}
fn get_saved_testcases() -> serde_json::Value {
let env_value = env::var("CONNECTOR_TESTS_FILE_PATH").ok();
if env_value.is_none() {
return serde_json::json!("");
}
let path = env_value.unwrap();
let mut file = &std::fs::File::open(path).expect("Failed to open file");
let mut contents = String::new();
file.read_to_string(&mut contents)
.expect("Failed to read file");
// Parse the JSON data
serde_json::from_str(&contents).expect("Failed to parse JSON")
}
fn get_configs() -> connector_auth::ConnectorAuthentication {
let path =
env::var("CONNECTOR_AUTH_FILE_PATH").expect("connector authentication file path not set");
toml::from_str(
&std::fs::read_to_string(path).expect("connector authentication config file not found"),
)
.expect("Failed to read connector authentication config file")
}
pub fn should_ignore_test(name: &str) -> bool {
let conf = get_saved_testcases()
.get("tests_to_ignore")
.unwrap_or(&json!([]))
.clone();
let tests_to_ignore: HashSet<String> =
serde_json::from_value(conf).unwrap_or_else(|_| HashSet::new());
let modules: Vec<_> = name.split("::").collect();
let file_match = format!(
"{}::*",
<&str>::clone(modules.get(1).expect("Error obtaining module path segment"))
);
let module_name = modules
.get(1..3)
.expect("Error obtaining module path segment")
.join("::");
// Ignore if it matches patterns like nuvei_ui::*, nuvei_ui::should_make_nuvei_eps_payment_test
tests_to_ignore.contains(&file_match) || tests_to_ignore.contains(&module_name)
}
pub fn get_browser() -> String {
"firefox".to_string()
}
// based on the browser settings build profile info
pub fn make_capabilities(browser: &str) -> Capabilities {
match browser {
"firefox" => {
let mut caps = DesiredCapabilities::firefox();
let ignore_profile = env::var("IGNORE_BROWSER_PROFILE").ok();
if ignore_profile.is_none() || ignore_profile.unwrap() == "false" {
let profile_path = &format!("-profile={}", get_firefox_profile_path().unwrap());
caps.add_firefox_arg(profile_path).unwrap();
} else {
let profile_path = &format!("-profile={}", get_firefox_profile_path().unwrap());
caps.add_firefox_arg(profile_path).unwrap();
caps.add_firefox_arg("--headless").ok();
}
caps.into()
}
"chrome" => {
let mut caps = DesiredCapabilities::chrome();
let profile_path = &format!("user-data-dir={}", get_chrome_profile_path().unwrap());
caps.add_chrome_arg(profile_path).unwrap();
caps.into()
}
&_ => DesiredCapabilities::safari().into(),
}
}
fn get_chrome_profile_path() -> Result<String, WebDriverError> {
let exe = env::current_exe()?;
let dir = exe.parent().expect("Executable must be in some directory");
let mut base_path = dir
.to_str()
.map(|str| {
let mut fp = str.split(MAIN_SEPARATOR).collect::<Vec<_>>();
fp.truncate(3);
fp.join(MAIN_SEPARATOR_STR)
})
.unwrap();
if env::consts::OS == "macos" {
base_path.push_str(r"/Library/Application\ Support/Google/Chrome/Default");
//Issue: 1573
} // We're only using Firefox on Ubuntu runner
Ok(base_path)
}
fn get_firefox_profile_path() -> Result<String, WebDriverError> {
let exe = env::current_exe()?;
let dir = exe.parent().expect("Executable must be in some directory");
let mut base_path = dir
.to_str()
.map(|str| {
let mut fp = str.split(MAIN_SEPARATOR).collect::<Vec<_>>();
fp.truncate(3);
fp.join(MAIN_SEPARATOR_STR)
})
.unwrap();
if env::consts::OS == "macos" {
base_path.push_str(r#"/Library/Application Support/Firefox/Profiles/hs-test"#);
//Issue: 1573
} else if env::consts::OS == "linux" {
if let Some(home_dir) = env::var_os("HOME") {
if let Some(home_path) = home_dir.to_str() {
let profile_path = format!("{home_path}/.mozilla/firefox/hs-test");
return Ok(profile_path);
}
}
}
Ok(base_path)
}
pub fn make_url(browser: &str) -> &'static str {
match browser {
"firefox" => "http://localhost:4444",
"chrome" => "http://localhost:9515",
&_ => "",
}
}
pub fn handle_test_error(
res: Result<Result<(), WebDriverError>, Box<dyn std::any::Any + Send>>,
) -> bool {
match res {
Ok(Ok(_)) => true,
Ok(Err(web_driver_error)) => {
eprintln!("test future failed to resolve: {web_driver_error:?}");
false
}
Err(e) => {
if let Some(web_driver_error) = e.downcast_ref::<WebDriverError>() {
eprintln!("test future panicked: {web_driver_error:?}");
} else {
eprintln!("test future panicked; an assertion probably failed");
}
false
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct WebhookResponse {
data: Vec<WebhookResponseData>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct WebhookResponseData {
step: WebhookRequestData,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct WebhookRequestData {
request: WebhookRequest,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct WebhookRequest {
body: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct HsWebhookResponse {
content: HsWebhookContent,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct HsWebhookContent {
object: HsWebhookObject,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct HsWebhookObject {
payment_id: String,
status: String,
connector: String,
}
</file>
|
{
"crate": "test_utils",
"file": "crates/test_utils/tests/connectors/selenium.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 7281
}
|
large_file_431518949464588162
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: test_utils
File: crates/test_utils/tests/connectors/aci_ui.rs
</path>
<file>
use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct AciSeleniumTest;
impl SeleniumTest for AciSeleniumTest {
fn get_connector_name(&self) -> String {
"aci".to_string()
}
}
async fn should_make_aci_card_mandate_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/180"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("a.btn"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_alipay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/213"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("submit-success"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_interac_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/14"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("input[value='Continue payment']"))),
Event::Trigger(Trigger::Click(By::Css("input[value='Confirm']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_eps_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/208"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("input.button-body.button-short"))),
Event::Trigger(Trigger::Click(By::Css("input.button-body.button-short"))),
Event::Trigger(Trigger::Click(By::Css("input.button-body.button-short"))),
Event::Trigger(Trigger::Click(By::Css("input.button-body.button-middle"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_ideal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/211"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("input.pps-button"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_sofort_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/212"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"button.large.button.primary.expand.form-submitter",
))),
Event::Trigger(Trigger::Click(By::Css(
"button.large.button.primary.expand.form-submitter",
))),
Event::Trigger(Trigger::Click(By::Css(
"button.large.button.primary.expand.form-submitter",
))),
Event::Trigger(Trigger::Click(By::Css(
"button.large.button.primary.expand.form-submitter",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_giropay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/209"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(By::Name("sc"), "10")),
Event::Trigger(Trigger::SendKeys(By::Name("extensionSc"), "4000")),
Event::Trigger(Trigger::SendKeys(By::Name("customerName1"), "Hopper")),
Event::Trigger(Trigger::Click(By::Css("input[value='Absenden']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_trustly_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/13"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(2)),
Event::Trigger(Trigger::Click(By::XPath(
r#"//*[@id="app"]/div[1]/div/div[2]/div/ul/div[4]/div/div[1]/div[2]/div[1]/span"#,
))),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Trigger(Trigger::SendKeys(
By::Css("input.sc-fXgAZx.hkChHq"),
"123456789",
)),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Trigger(Trigger::SendKeys(
By::Css("input.sc-fXgAZx.hkChHq"),
"783213",
)),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Trigger(Trigger::Click(By::Css("div.sc-jJMGnK.laKGqb"))),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Trigger(Trigger::SendKeys(
By::Css("input.sc-fXgAZx.hkChHq"),
"355508",
)),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_przelewy24_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/12"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("pf31"))),
Event::Trigger(Trigger::Click(By::Css(
"button.btn.btn-lg.btn-info.btn-block",
))),
Event::Trigger(Trigger::Click(By::Css(
"button.btn.btn-success.btn-lg.accept-button",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_aci_card_mandate_payment_test() {
tester!(should_make_aci_card_mandate_payment);
}
#[test]
#[serial]
fn should_make_aci_alipay_payment_test() {
tester!(should_make_aci_alipay_payment);
}
#[test]
#[serial]
fn should_make_aci_interac_payment_test() {
tester!(should_make_aci_interac_payment);
}
#[test]
#[serial]
fn should_make_aci_eps_payment_test() {
tester!(should_make_aci_eps_payment);
}
#[test]
#[serial]
fn should_make_aci_ideal_payment_test() {
tester!(should_make_aci_ideal_payment);
}
#[test]
#[serial]
fn should_make_aci_sofort_payment_test() {
tester!(should_make_aci_sofort_payment);
}
#[test]
#[serial]
fn should_make_aci_giropay_payment_test() {
tester!(should_make_aci_giropay_payment);
}
#[test]
#[serial]
fn should_make_aci_trustly_payment_test() {
tester!(should_make_aci_trustly_payment);
}
#[test]
#[serial]
fn should_make_aci_przelewy24_payment_test() {
tester!(should_make_aci_przelewy24_payment);
}
</file>
|
{
"crate": "test_utils",
"file": "crates/test_utils/tests/connectors/aci_ui.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2235
}
|
large_file_-2504411055966381663
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: test_utils
File: crates/test_utils/tests/connectors/adyen_uk_ui.rs
</path>
<file>
use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct AdyenSeleniumTest;
impl SeleniumTest for AdyenSeleniumTest {
fn get_connector_name(&self) -> String {
"adyen_uk".to_string()
}
}
async fn should_make_adyen_3ds_payment_failed(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/177"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Name("threeDSIframe"))),
Event::Assert(Assert::IsPresent("AUTHENTICATION DETAILS")),
Event::Trigger(Trigger::SendKeys(By::ClassName("input-field"), "password")),
Event::Trigger(Trigger::Click(By::Id("buttonSubmit"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Assert(Assert::IsPresent("failed")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_3ds_payment_success(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/62"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Name("threeDSIframe"))),
Event::Assert(Assert::IsPresent("AUTHENTICATION DETAILS")),
Event::Trigger(Trigger::SendKeys(By::ClassName("input-field"), "password")),
Event::Trigger(Trigger::Click(By::Id("buttonSubmit"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_3ds_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/203"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("a.btn"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_3ds_mandate_with_zero_dollar_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/204"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("a.btn"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_gpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=70.00&country=US¤cy=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_adyen_gpay_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=70.00&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_adyen_gpay_zero_dollar_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=0.00&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_adyen_klarna_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/195"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Id("klarna-apf-iframe"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Trigger(Trigger::Click(By::Id("signInWithBankId"))),
Event::Assert(Assert::IsPresent("Klart att betala")),
Event::EitherOr(
Assert::IsPresent("Klart att betala"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='confirm-and-pay']",
)))],
vec![
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='SmoothCheckoutPopUp:skip']",
))),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='confirm-and-pay']",
))),
],
),
Event::RunIf(
Assert::IsPresent("Färre klick, snabbare betalning"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='SmoothCheckoutPopUp:enable']",
)))],
),
Event::Trigger(Trigger::SwitchTab(Position::Prev)),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_alipay_hk_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/162"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::EitherOr(
Assert::IsPresent("Payment Method Not Available"),
vec![Event::Assert(Assert::IsPresent(
"Please try again or select a different payment method",
))],
vec![
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_bizum_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/186"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(By::Id("iPhBizInit"), "700000000")),
Event::Trigger(Trigger::Click(By::Id("bBizInit"))),
Event::Trigger(Trigger::Click(By::Css("input.btn.btn-lg.btn-continue"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_clearpay_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_clearpay_payment(
driver,
&format!("{CHECKOUT_BASE_URL}/saved/163"),
vec![Event::Assert(Assert::IsPresent("succeeded"))],
)
.await?;
Ok(())
}
async fn should_make_adyen_paypal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_paypal_payment(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/202"),
vec![
Event::Trigger(Trigger::Click(By::Id("payment-submit-btn"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=processing"], //final status of this payment method will remain in processing state
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_ach_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/58"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_sepa_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/51"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_bacs_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/54"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Status")),
Event::Assert(Assert::IsPresent("processing")), //final status of this payment method will remain in processing state
],
)
.await?;
Ok(())
}
async fn should_make_adyen_ideal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/52"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("btnLink"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_eps_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/61"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_bancontact_card_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
let user = &conn
.get_configs()
.automation_configs
.unwrap()
.adyen_bancontact_username
.unwrap();
let pass = &conn
.get_configs()
.automation_configs
.unwrap()
.adyen_bancontact_pass
.unwrap();
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/68"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(By::Id("username"), user)),
Event::Trigger(Trigger::SendKeys(By::Id("password"), pass)),
Event::Trigger(Trigger::Click(By::ClassName("button"))),
Event::Trigger(Trigger::Sleep(2)),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_wechatpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/75"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_mbway_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/196"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Status")),
Event::Assert(Assert::IsPresent("processing")), //final status of this payment method will remain in processing state
],
)
.await?;
Ok(())
}
async fn should_make_adyen_ebanking_fi_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/78"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("css-ns0tbt"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_onlinebanking_pl_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/197"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("user_account_pbl_correct"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
#[ignore]
async fn should_make_adyen_giropay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/70"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(
By::Css("input[id='tags']"),
"Testbank Fiducia 44448888 GENODETT488",
)),
Event::Trigger(Trigger::Click(By::Css("input[id='tags']"))),
Event::Trigger(Trigger::Sleep(3)),
Event::Trigger(Trigger::Click(By::Id("ui-id-3"))),
Event::Trigger(Trigger::Click(By::ClassName("blueButton"))),
Event::Trigger(Trigger::SendKeys(By::Name("sc"), "10")),
Event::Trigger(Trigger::SendKeys(By::Name("extensionSc"), "4000")),
Event::Trigger(Trigger::SendKeys(By::Name("customerName1"), "Hopper")),
Event::Trigger(Trigger::SendKeys(
By::Name("customerIBAN"),
"DE36444488881234567890",
)),
Event::Trigger(Trigger::Click(By::Css("input[value='Absenden']"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=processing"], //final status of this payment method will remain in processing state
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_twint_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/170"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_walley_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/198"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Teknikmössor AB")),
Event::Trigger(Trigger::SwitchFrame(By::ClassName(
"collector-checkout-iframe",
))),
Event::Trigger(Trigger::Click(By::Id("purchase"))),
Event::Trigger(Trigger::Sleep(10)),
Event::Trigger(Trigger::SwitchFrame(By::Css(
"iframe[title='Walley Modal - idp-choices']",
))),
Event::Assert(Assert::IsPresent("Identifisering")),
Event::Trigger(Trigger::Click(By::Id("optionLoggInnMedBankId"))),
Event::Trigger(Trigger::SwitchFrame(By::Css("iframe[title='BankID']"))),
Event::Assert(Assert::IsPresent("Engangskode")),
Event::Trigger(Trigger::SendKeys(By::Css("input[type='password']"), "otp")),
Event::Trigger(Trigger::Sleep(4)),
Event::Trigger(Trigger::Click(By::Css("button[title='Neste']"))),
Event::Assert(Assert::IsPresent("Ditt BankID-passord")),
Event::Trigger(Trigger::Sleep(4)),
Event::Trigger(Trigger::SendKeys(
By::Css("input[type='password']"),
"qwer1234",
)),
Event::Trigger(Trigger::Click(By::Css("button[title='Neste']"))),
Event::Trigger(Trigger::SwitchTab(Position::Prev)),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_dana_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/175"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(
By::Css("input[type='number']"),
"12345678901",
)), // Mobile Number can be any random 11 digit number
Event::Trigger(Trigger::Click(By::Css("button"))),
Event::Trigger(Trigger::SendKeys(By::Css("input[type='number']"), "111111")), // PIN can be any random 11 digit number
Event::Trigger(Trigger::Click(By::ClassName("btn-next"))),
Event::Trigger(Trigger::Sleep(3)),
Event::Trigger(Trigger::Click(By::ClassName("btn-next"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_online_banking_fpx_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/172"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_online_banking_thailand_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/184"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_touch_n_go_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/185"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_swish_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/210"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("status")),
Event::Assert(Assert::IsPresent("processing")),
Event::Assert(Assert::IsPresent("Next Action Type")),
Event::Assert(Assert::IsPresent("qr_code_information")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_blik_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/64"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Next Action Type")),
Event::Assert(Assert::IsPresent("wait_screen_information")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_momo_atm_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/238"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(5)), // Delay for provider to not reject payment for botting
Event::Trigger(Trigger::SendKeys(
By::Id("card-number"),
"9704 0000 0000 0018",
)),
Event::Trigger(Trigger::SendKeys(By::Id("card-expire"), "03/07")),
Event::Trigger(Trigger::SendKeys(By::Id("card-name"), "NGUYEN VAN A")),
Event::Trigger(Trigger::SendKeys(By::Id("number-phone"), "987656666")),
Event::Trigger(Trigger::Click(By::Id("btn-pay-card"))),
Event::Trigger(Trigger::SendKeys(By::Id("napasOtpCode"), "otp")),
Event::Trigger(Trigger::Click(By::Id("napasProcessBtn1"))),
Event::Trigger(Trigger::Sleep(5)), // Delay to get to status page
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_adyen_gpay_payment_test() {
tester!(should_make_adyen_gpay_payment);
}
#[test]
#[serial]
fn should_make_adyen_gpay_mandate_payment_test() {
tester!(should_make_adyen_gpay_mandate_payment);
}
#[test]
#[serial]
fn should_make_adyen_gpay_zero_dollar_mandate_payment_test() {
tester!(should_make_adyen_gpay_zero_dollar_mandate_payment);
}
#[test]
#[serial]
fn should_make_adyen_klarna_mandate_payment_test() {
tester!(should_make_adyen_klarna_mandate_payment);
}
#[test]
#[serial]
fn should_make_adyen_3ds_payment_failed_test() {
tester!(should_make_adyen_3ds_payment_failed);
}
#[test]
#[serial]
fn should_make_adyen_3ds_mandate_payment_test() {
tester!(should_make_adyen_3ds_mandate_payment);
}
#[test]
#[serial]
fn should_make_adyen_3ds_mandate_with_zero_dollar_payment_test() {
tester!(should_make_adyen_3ds_mandate_with_zero_dollar_payment);
}
#[test]
#[serial]
fn should_make_adyen_3ds_payment_success_test() {
tester!(should_make_adyen_3ds_payment_success);
}
#[test]
#[serial]
fn should_make_adyen_alipay_hk_payment_test() {
tester!(should_make_adyen_alipay_hk_payment);
}
#[test]
#[serial]
fn should_make_adyen_swish_payment_test() {
tester!(should_make_adyen_swish_payment);
}
#[test]
#[serial]
#[ignore = "Failing from connector side"]
fn should_make_adyen_bizum_payment_test() {
tester!(should_make_adyen_bizum_payment);
}
#[test]
#[serial]
fn should_make_adyen_clearpay_payment_test() {
tester!(should_make_adyen_clearpay_payment);
}
#[test]
#[serial]
fn should_make_adyen_twint_payment_test() {
tester!(should_make_adyen_twint_payment);
}
#[test]
#[serial]
fn should_make_adyen_paypal_payment_test() {
tester!(should_make_adyen_paypal_payment);
}
#[test]
#[serial]
fn should_make_adyen_ach_payment_test() {
tester!(should_make_adyen_ach_payment);
}
#[test]
#[serial]
fn should_make_adyen_sepa_payment_test() {
tester!(should_make_adyen_sepa_payment);
}
#[test]
#[serial]
fn should_make_adyen_bacs_payment_test() {
tester!(should_make_adyen_bacs_payment);
}
#[test]
#[serial]
fn should_make_adyen_ideal_payment_test() {
tester!(should_make_adyen_ideal_payment);
}
#[test]
#[serial]
fn should_make_adyen_eps_payment_test() {
tester!(should_make_adyen_eps_payment);
}
#[test]
#[serial]
fn should_make_adyen_bancontact_card_payment_test() {
tester!(should_make_adyen_bancontact_card_payment);
}
#[test]
#[serial]
fn should_make_adyen_wechatpay_payment_test() {
tester!(should_make_adyen_wechatpay_payment);
}
#[test]
#[serial]
fn should_make_adyen_mbway_payment_test() {
tester!(should_make_adyen_mbway_payment);
}
#[test]
#[serial]
fn should_make_adyen_ebanking_fi_payment_test() {
tester!(should_make_adyen_ebanking_fi_payment);
}
#[test]
#[serial]
fn should_make_adyen_onlinebanking_pl_payment_test() {
tester!(should_make_adyen_onlinebanking_pl_payment);
}
#[ignore]
#[test]
#[serial]
fn should_make_adyen_giropay_payment_test() {
tester!(should_make_adyen_giropay_payment);
}
#[ignore]
#[test]
#[serial]
fn should_make_adyen_walley_payment_test() {
tester!(should_make_adyen_walley_payment);
}
#[test]
#[serial]
fn should_make_adyen_dana_payment_test() {
tester!(should_make_adyen_dana_payment);
}
#[test]
#[serial]
fn should_make_adyen_blik_payment_test() {
tester!(should_make_adyen_blik_payment);
}
#[test]
#[serial]
fn should_make_adyen_online_banking_fpx_payment_test() {
tester!(should_make_adyen_online_banking_fpx_payment);
}
#[test]
#[serial]
fn should_make_adyen_online_banking_thailand_payment_test() {
tester!(should_make_adyen_online_banking_thailand_payment);
}
#[test]
#[serial]
fn should_make_adyen_touch_n_go_payment_test() {
tester!(should_make_adyen_touch_n_go_payment);
}
#[ignore]
#[test]
#[serial]
fn should_make_adyen_momo_atm_payment_test() {
tester!(should_make_adyen_momo_atm_payment);
}
</file>
|
{
"crate": "test_utils",
"file": "crates/test_utils/tests/connectors/adyen_uk_ui.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 7588
}
|
large_file_5500126766853282711
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: test_utils
File: crates/test_utils/tests/connectors/nuvei_ui.rs
</path>
<file>
use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct NuveiSeleniumTest;
impl SeleniumTest for NuveiSeleniumTest {
fn get_connector_name(&self) -> String {
"nuvei".to_string()
}
}
async fn should_make_nuvei_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US¤cy=USD"))),
Event::Assert(Assert::IsPresent("Expiry Year")),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Query(By::ClassName("title"))),
Event::Assert(Assert::Eq(Selector::Title, "ThreeDS ACS Emulator - Challenge Page")),
Event::Trigger(Trigger::Click(By::Id("btn1"))),
Event::Trigger(Trigger::Click(By::Id("btn5"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(Selector::QueryParamStr, "status=succeeded")),
]).await?;
Ok(())
}
async fn should_make_nuvei_3ds_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US¤cy=USD&setup_future_usage=off_session&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=in%20sit&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD&mandate_data[mandate_type][multi_use][start_date]=2022-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][end_date]=2023-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][metadata][frequency]=13&return_url={CHECKOUT_BASE_URL}/payments"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Query(By::ClassName("title"))),
Event::Assert(Assert::Eq(Selector::Title, "ThreeDS ACS Emulator - Challenge Page")),
Event::Trigger(Trigger::Click(By::Id("btn1"))),
Event::Trigger(Trigger::Click(By::Id("btn5"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("man_")),//mandate id prefix is present
]).await?;
Ok(())
}
async fn should_make_nuvei_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_gpay_payment(c,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=nuveidigital&gatewaymerchantid=googletest&amount=10.00&country=IN¤cy=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_nuvei_pypl_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_paypal_payment(
c,
&format!("{CHECKOUT_BASE_URL}/saved/5"),
vec![
Event::Trigger(Trigger::Click(By::Id("payment-submit-btn"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_nuvei_giropay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/bank-redirect?amount=1.00&country=DE¤cy=EUR&paymentmethod=giropay"))),
Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))),
Event::Assert(Assert::IsPresent("You are about to make a payment using the Giropay service.")),
Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))),
Event::RunIf(Assert::IsPresent("Bank suchen"), vec![
Event::Trigger(Trigger::SendKeys(By::Id("bankSearch"), "GIROPAY Testbank 1")),
Event::Trigger(Trigger::Click(By::Id("GIROPAY Testbank 1"))),
]),
Event::Assert(Assert::IsPresent("GIROPAY Testbank 1")),
Event::Trigger(Trigger::Click(By::Css("button[name='claimCheckoutButton']"))),
Event::Assert(Assert::IsPresent("sandbox.paydirekt")),
Event::Trigger(Trigger::Click(By::Id("submitButton"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Trigger(Trigger::SwitchTab(Position::Next)),
Event::Assert(Assert::IsPresent("Sicher bezahlt!")),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"]))
]).await?;
Ok(())
}
async fn should_make_nuvei_ideal_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/bank-redirect?amount=10.00&country=NL¤cy=EUR&paymentmethod=ideal&processingbank=ing"))),
Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))),
Event::Assert(Assert::IsPresent("Your account will be debited:")),
Event::Trigger(Trigger::SelectOption(By::Id("ctl00_ctl00_mainContent_ServiceContent_ddlBanks"), "ING Simulator")),
Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))),
Event::Assert(Assert::IsPresent("IDEALFORTIS")),
Event::Trigger(Trigger::Sleep(5)),
Event::Trigger(Trigger::Click(By::Id("ctl00_mainContent_btnGo"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"]))
]).await?;
Ok(())
}
async fn should_make_nuvei_sofort_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/bank-redirect?amount=10.00&country=DE¤cy=EUR&paymentmethod=sofort"))),
Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))),
Event::Assert(Assert::IsPresent("SOFORT")),
Event::Trigger(Trigger::ChangeQueryParam("sender_holder", "John Doe")),
Event::Trigger(Trigger::Click(By::Id("ctl00_mainContent_btnGo"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"]))
]).await?;
Ok(())
}
async fn should_make_nuvei_eps_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/bank-redirect?amount=10.00&country=AT¤cy=EUR&paymentmethod=eps&processingbank=ing"))),
Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))),
Event::Assert(Assert::IsPresent("You are about to make a payment using the EPS service.")),
Event::Trigger(Trigger::SendKeys(By::Id("ctl00_ctl00_mainContent_ServiceContent_txtCustomerName"), "John Doe")),
Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))),
Event::Assert(Assert::IsPresent("Simulator")),
Event::Trigger(Trigger::SelectOption(By::Css("select[name='result']"), "Succeeded")),
Event::Trigger(Trigger::Click(By::Id("submitbutton"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"]))
]).await?;
Ok(())
}
#[test]
#[serial]
fn should_make_nuvei_3ds_payment_test() {
tester!(should_make_nuvei_3ds_payment);
}
#[test]
#[serial]
fn should_make_nuvei_3ds_mandate_payment_test() {
tester!(should_make_nuvei_3ds_mandate_payment);
}
#[test]
#[serial]
fn should_make_nuvei_gpay_payment_test() {
tester!(should_make_nuvei_gpay_payment);
}
#[test]
#[serial]
fn should_make_nuvei_pypl_payment_test() {
tester!(should_make_nuvei_pypl_payment);
}
#[test]
#[serial]
fn should_make_nuvei_giropay_payment_test() {
tester!(should_make_nuvei_giropay_payment);
}
#[test]
#[serial]
fn should_make_nuvei_ideal_payment_test() {
tester!(should_make_nuvei_ideal_payment);
}
#[test]
#[serial]
fn should_make_nuvei_sofort_payment_test() {
tester!(should_make_nuvei_sofort_payment);
}
#[test]
#[serial]
fn should_make_nuvei_eps_payment_test() {
tester!(should_make_nuvei_eps_payment);
}
</file>
|
{
"crate": "test_utils",
"file": "crates/test_utils/tests/connectors/nuvei_ui.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2482
}
|
large_file_-7199252348823983596
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: test_utils
File: crates/test_utils/tests/connectors/stripe_ui.rs
</path>
<file>
use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct StripeSeleniumTest;
impl SeleniumTest for StripeSeleniumTest {
fn get_connector_name(&self) -> String {
"stripe".to_string()
}
}
async fn should_make_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000000000003063&expmonth=10&expyear=25&cvv=123&amount=100&country=US¤cy=USD"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(Selector::QueryParamStr, "status=succeeded")),
]).await?;
Ok(())
}
async fn should_make_3ds_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002500003155&expmonth=10&expyear=25&cvv=123&amount=10&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&return_url={CHECKOUT_BASE_URL}/payments"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_fail_recurring_payment_due_to_authentication(
c: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002760003184&expmonth=10&expyear=25&cvv=123&amount=10&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&return_url={CHECKOUT_BASE_URL}/payments"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Your card was declined. This transaction requires authentication.")),
]).await?;
Ok(())
}
async fn should_make_3ds_mandate_with_zero_dollar_payment(
c: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002500003155&expmonth=10&expyear=25&cvv=123&amount=0&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&return_url={CHECKOUT_BASE_URL}/payments"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
// Need to be handled as mentioned in https://stripe.com/docs/payments/save-and-reuse?platform=web#charge-saved-payment-method
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
let pub_key = conn
.get_configs()
.automation_configs
.unwrap()
.stripe_pub_key
.unwrap();
conn.make_gpay_payment(c,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=stripe&gpaycustomfields[stripe:version]=2018-10-31&gpaycustomfields[stripe:publishableKey]={pub_key}&amount=70.00&country=US¤cy=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_gpay_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
let pub_key = conn
.get_configs()
.automation_configs
.unwrap()
.stripe_pub_key
.unwrap();
conn.make_gpay_payment(c,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=stripe&gpaycustomfields[stripe:version]=2018-10-31&gpaycustomfields[stripe:publishableKey]={pub_key}&amount=70.00&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
#[ignore = "Different flows"]
//https://stripe.com/docs/testing#regulatory-cards
async fn should_make_stripe_klarna_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/19"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Id("klarna-apf-iframe"))),
Event::RunIf(
Assert::IsPresent("Let’s verify your phone"),
vec![
Event::Trigger(Trigger::SendKeys(By::Id("phone"), "9123456789")),
Event::Trigger(Trigger::Click(By::Id("onContinue"))),
Event::Trigger(Trigger::SendKeys(By::Id("otp_field"), "123456")),
],
),
Event::RunIf(
Assert::IsPresent("We've updated our Shopping terms"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='kaf-button']",
)))],
),
Event::RunIf(
Assert::IsPresent("Pick a plan"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='pick-plan']",
)))],
),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='confirm-and-pay']",
))),
Event::RunIf(
Assert::IsPresent("Fewer clicks"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='SmoothCheckoutPopUp:skip']",
)))],
),
Event::Trigger(Trigger::SwitchTab(Position::Prev)),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_afterpay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/22"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_alipay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/35"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='common-Button common-Button--default']",
))),
Event::Trigger(Trigger::Sleep(5)),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_ideal_bank_redirect_payment(
c: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/2"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_giropay_bank_redirect_payment(
c: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/1"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_eps_bank_redirect_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/26"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_bancontact_card_redirect_payment(
c: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/28"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_p24_redirect_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/31"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_sofort_redirect_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/34"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=processing", "status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_ach_bank_debit_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/56"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(
By::Css("input[class='p-CodePuncher-controllingInput']"),
"11AA",
)),
Event::Trigger(Trigger::Click(By::Css(
"div[class='SubmitButton-IconContainer']",
))),
Event::Assert(Assert::IsPresent("Thanks for your payment")),
Event::Assert(Assert::IsPresent("You completed a payment")),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_sepa_bank_debit_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/67"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Status")),
Event::Assert(Assert::IsPresent("processing")),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_affirm_paylater_payment(
driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_affirm_payment(
driver,
&format!("{CHECKOUT_BASE_URL}/saved/110"),
vec![Event::Assert(Assert::IsPresent("succeeded"))],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_3ds_payment_test() {
tester!(should_make_3ds_payment);
}
#[test]
#[serial]
fn should_make_3ds_mandate_payment_test() {
tester!(should_make_3ds_mandate_payment);
}
#[test]
#[serial]
fn should_fail_recurring_payment_due_to_authentication_test() {
tester!(should_fail_recurring_payment_due_to_authentication);
}
#[test]
#[serial]
fn should_make_3ds_mandate_with_zero_dollar_payment_test() {
tester!(should_make_3ds_mandate_with_zero_dollar_payment);
}
#[test]
#[serial]
fn should_make_gpay_payment_test() {
tester!(should_make_gpay_payment);
}
#[test]
#[serial]
#[ignore]
fn should_make_gpay_mandate_payment_test() {
tester!(should_make_gpay_mandate_payment);
}
#[test]
#[serial]
fn should_make_stripe_klarna_payment_test() {
tester!(should_make_stripe_klarna_payment);
}
#[test]
#[serial]
fn should_make_afterpay_payment_test() {
tester!(should_make_afterpay_payment);
}
#[test]
#[serial]
fn should_make_stripe_alipay_payment_test() {
tester!(should_make_stripe_alipay_payment);
}
#[test]
#[serial]
fn should_make_stripe_ideal_bank_redirect_payment_test() {
tester!(should_make_stripe_ideal_bank_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_giropay_bank_redirect_payment_test() {
tester!(should_make_stripe_giropay_bank_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_eps_bank_redirect_payment_test() {
tester!(should_make_stripe_eps_bank_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_bancontact_card_redirect_payment_test() {
tester!(should_make_stripe_bancontact_card_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_p24_redirect_payment_test() {
tester!(should_make_stripe_p24_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_sofort_redirect_payment_test() {
tester!(should_make_stripe_sofort_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_ach_bank_debit_payment_test() {
tester!(should_make_stripe_ach_bank_debit_payment);
}
#[test]
#[serial]
fn should_make_stripe_sepa_bank_debit_payment_test() {
tester!(should_make_stripe_sepa_bank_debit_payment);
}
#[test]
#[serial]
fn should_make_stripe_affirm_paylater_payment_test() {
tester!(should_make_stripe_affirm_paylater_payment);
}
</file>
|
{
"crate": "test_utils",
"file": "crates/test_utils/tests/connectors/stripe_ui.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4825
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.