repo stringclasses 4 values | file_path stringlengths 6 193 | extension stringclasses 23 values | content stringlengths 0 1.73M | token_count int64 0 724k | __index_level_0__ int64 0 10.8k |
|---|---|---|---|---|---|
hyperswitch | crates/hyperswitch_connectors/src/connectors/opennode/transformers.rs | .rs | use std::collections::HashMap;
use common_enums::{enums, AttemptStatus};
use common_utils::request::Method;
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::{api::CurrencyUnit, 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: i64,
pub router_data: T,
}
impl<T> TryFrom<(&CurrencyUnit, enums::Currency, i64, T)> for OpennodeRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(_currency_unit, _currency, amount, router_data): (&CurrencyUnit, enums::Currency, i64, 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: i64,
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,
}
| 2,064 | 2,206 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/volt/transformers.rs | .rs | 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,
})
} 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,
})
} 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,
}
| 4,615 | 2,207 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs | .rs | 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::AmazonPayRedirect(_)
| 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(_) => 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>,
}
| 3,135 | 2,208 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/coingate/transformers.rs | .rs | use std::collections::HashMap;
use common_enums::{enums, Currency};
use common_utils::{ext_traits::OptionExt, pii, request::Method, types::StringMajorUnit};
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::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{self, PaymentsAuthorizeRequestData},
};
pub struct CoingateRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for CoingateRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CoingateConnectorMetadataObject {
pub currency_id: i32,
pub platform_id: i32,
pub ledger_account_id: Secret<String>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for CoingateConnectorMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct CoingatePaymentsRequest {
price_amount: StringMajorUnit,
price_currency: Currency,
receive_currency: String,
callback_url: String,
success_url: Option<String>,
cancel_url: Option<String>,
title: String,
token: Secret<String>,
}
impl TryFrom<&CoingateRouterData<&PaymentsAuthorizeRouterData>> for CoingatePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CoingateRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let auth = CoingateAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(match item.router_data.request.payment_method_data {
PaymentMethodData::Crypto(_) => Ok(Self {
price_amount: item.amount.clone(),
price_currency: item.router_data.request.currency,
receive_currency: "DO_NOT_CONVERT".to_string(),
callback_url: item.router_data.request.get_webhook_url()?,
success_url: item.router_data.request.router_return_url.clone(),
cancel_url: item.router_data.request.router_return_url.clone(),
title: item.router_data.connector_request_reference_id.clone(),
token: auth.merchant_token,
}),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Coingate"),
)),
}?)
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CoingateSyncResponse {
status: CoingatePaymentStatus,
id: i64,
}
impl TryFrom<PaymentsSyncResponseRouterData<CoingateSyncResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<CoingateSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status.clone()),
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: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
pub struct CoingateAuthType {
pub(super) api_key: Secret<String>,
pub(super) merchant_token: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for CoingateAuthType {
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_token: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CoingatePaymentStatus {
New,
Pending,
Confirming,
Paid,
Invalid,
Expired,
Canceled,
}
impl From<CoingatePaymentStatus> for common_enums::AttemptStatus {
fn from(item: CoingatePaymentStatus) -> Self {
match item {
CoingatePaymentStatus::Paid => Self::Charged,
CoingatePaymentStatus::Canceled
| CoingatePaymentStatus::Expired
| CoingatePaymentStatus::Invalid => Self::Failure,
CoingatePaymentStatus::Confirming | CoingatePaymentStatus::New => {
Self::AuthenticationPending
}
CoingatePaymentStatus::Pending => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CoingatePaymentsResponse {
status: CoingatePaymentStatus,
id: i64,
payment_url: Option<String>,
order_id: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, CoingatePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CoingatePaymentsResponse, 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.id.to_string()),
redirection_data: Box::new(Some(RedirectForm::Form {
endpoint: item.response.payment_url.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "payment_url",
},
)?,
method: Method::Get,
form_fields: HashMap::new(),
})),
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, Serialize)]
pub struct CoingateRefundRequest {
pub amount: StringMajorUnit,
pub address: Secret<String>,
pub currency_id: i32,
pub platform_id: i32,
pub reason: String,
pub email: pii::Email,
pub ledger_account_id: Secret<String>,
}
impl<F> TryFrom<&CoingateRouterData<&RefundsRouterData<F>>> for CoingateRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &CoingateRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let metadata: CoingateConnectorMetadataObject =
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
let refund_metadata = item
.router_data
.request
.refund_connector_metadata
.as_ref()
.get_required_value("refund_connector_metadata")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "refund_connector_metadata",
})?
.clone()
.expose();
let address: Secret<String> = serde_json::from_value::<Secret<String>>(
refund_metadata.get("address").cloned().ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "address",
}
})?,
)
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "address",
})?;
let email: pii::Email = serde_json::from_value::<pii::Email>(
refund_metadata.get("email").cloned().ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "email",
}
})?,
)
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "email",
})?;
Ok(Self {
amount: item.amount.clone(),
address,
currency_id: metadata.currency_id,
platform_id: metadata.platform_id,
reason: item.router_data.request.reason.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "refund.reason",
},
)?,
email,
ledger_account_id: metadata.ledger_account_id,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CoingateRefundResponse {
pub status: CoingateRefundStatus,
pub id: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CoingateRefundStatus {
Pending,
Completed,
Rejected,
Processing,
}
impl TryFrom<RefundsResponseRouterData<Execute, CoingateRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, CoingateRefundResponse>,
) -> 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, CoingateRefundResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, CoingateRefundResponse>,
) -> 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 From<CoingateRefundStatus> for common_enums::RefundStatus {
fn from(item: CoingateRefundStatus) -> Self {
match item {
CoingateRefundStatus::Pending => Self::Pending,
CoingateRefundStatus::Completed => Self::Success,
CoingateRefundStatus::Rejected => Self::Failure,
CoingateRefundStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct CoingateErrorResponse {
pub message: String,
pub reason: String,
pub errors: Option<Vec<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CoingateWebhookBody {
pub token: Secret<String>,
pub status: CoingatePaymentStatus,
pub id: i64,
}
| 2,611 | 2,209 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs | .rs | 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(_) => (
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,
})
} 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,
})
} 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,
})
} 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,
}
| 5,388 | 2,210 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs | .rs | #[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(request.payout_id),
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,
}),
..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!("{:?} is not supported", other_bank),
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,
}),
..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.request.clone().payout_id,
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,
}),
..item.data
})
}
}
| 3,896 | 2,211 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs | .rs | 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::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,
}
| 3,644 | 2,212 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/boku/transformers.rs | .rs | use std::fmt;
use common_enums::enums;
use common_utils::{request::Method, types::MinorUnit};
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{self, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use url::Url;
use uuid::Uuid;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, AddressDetailsData, RouterData as _},
};
#[derive(Debug, Serialize)]
pub struct BokuRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for BokuRouterData<T> {
fn from((amount, router_data): (MinorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum BokuPaymentsRequest {
BeginSingleCharge(SingleChargeData),
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SingleChargeData {
total_amount: MinorUnit,
currency: String,
country: String,
merchant_id: Secret<String>,
merchant_transaction_id: Secret<String>,
merchant_request_id: String,
merchant_item_description: String,
notification_url: Option<String>,
payment_method: String,
charge_type: String,
hosted: Option<BokuHostedData>,
}
#[derive(Debug, Clone, Serialize)]
pub enum BokuPaymentType {
Dana,
Momo,
Gcash,
GoPay,
Kakaopay,
}
impl fmt::Display for BokuPaymentType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Dana => write!(f, "Dana"),
Self::Momo => write!(f, "Momo"),
Self::Gcash => write!(f, "Gcash"),
Self::GoPay => write!(f, "GoPay"),
Self::Kakaopay => write!(f, "Kakaopay"),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub enum BokuChargeType {
Hosted,
}
impl fmt::Display for BokuChargeType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Hosted => write!(f, "hosted"),
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "kebab-case")]
struct BokuHostedData {
forward_url: String,
}
impl TryFrom<&BokuRouterData<&types::PaymentsAuthorizeRouterData>> for BokuPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BokuRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Wallet(wallet_data) => Self::try_from((item, &wallet_data)),
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
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::AmazonPayRedirect(_)
| 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(_) => 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 })
}
| 3,933 | 2,213 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs | .rs | use std::collections::BTreeMap;
use api_models::webhooks::IncomingWebhookEvent;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::{Encode, OptionExt, ValueExt},
request::Method,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{Card, PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::RSync,
router_request_types::ResponseId,
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundsRouterData,
SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{api, errors};
use masking::{ExposeInterface, PeekInterface, Secret, StrongSecret};
use rand::distributions::{Alphanumeric, DistString};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, CardData, ForeignTryFrom, PaymentsAuthorizeRequestData, PaymentsSyncRequestData,
RefundsRequestData, RouterData as OtherRouterData, WalletData as OtherWalletData,
},
};
#[derive(Debug, Serialize)]
pub enum TransactionType {
#[serde(rename = "authCaptureTransaction")]
Payment,
#[serde(rename = "authOnlyTransaction")]
Authorization,
#[serde(rename = "priorAuthCaptureTransaction")]
Capture,
#[serde(rename = "refundTransaction")]
Refund,
#[serde(rename = "voidTransaction")]
Void,
#[serde(rename = "authOnlyContinueTransaction")]
ContinueAuthorization,
#[serde(rename = "authCaptureContinueTransaction")]
ContinueCapture,
}
#[derive(Debug, Serialize)]
pub struct AuthorizedotnetRouterData<T> {
pub amount: f64,
pub router_data: T,
}
impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for AuthorizedotnetRouterData<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,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetAuthType {
name: Secret<String>,
transaction_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AuthorizedotnetAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
name: api_key.to_owned(),
transaction_key: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct CreditCardDetails {
card_number: StrongSecret<String, cards::CardNumberStrategy>,
expiration_date: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
card_code: Option<Secret<String>>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct BankAccountDetails {
account_number: Secret<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
enum PaymentDetails {
CreditCard(CreditCardDetails),
OpaqueData(WalletDetails),
PayPal(PayPalDetails),
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PayPalDetails {
pub success_url: Option<String>,
pub cancel_url: Option<String>,
}
#[derive(Serialize, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletDetails {
pub data_descriptor: WalletMethod,
pub data_value: Secret<String>,
}
#[derive(Serialize, Debug, Deserialize)]
pub enum WalletMethod {
#[serde(rename = "COMMON.GOOGLE.INAPP.PAYMENT")]
Googlepay,
#[serde(rename = "COMMON.APPLE.INAPP.PAYMENT")]
Applepay,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct TransactionRequest {
transaction_type: TransactionType,
amount: f64,
currency_code: common_enums::Currency,
#[serde(skip_serializing_if = "Option::is_none")]
payment: Option<PaymentDetails>,
#[serde(skip_serializing_if = "Option::is_none")]
profile: Option<ProfileDetails>,
order: Order,
#[serde(skip_serializing_if = "Option::is_none")]
customer: Option<CustomerDetails>,
#[serde(skip_serializing_if = "Option::is_none")]
bill_to: Option<BillTo>,
#[serde(skip_serializing_if = "Option::is_none")]
user_fields: Option<UserFields>,
#[serde(skip_serializing_if = "Option::is_none")]
processing_options: Option<ProcessingOptions>,
#[serde(skip_serializing_if = "Option::is_none")]
subsequent_auth_information: Option<SubsequentAuthInformation>,
authorization_indicator_type: Option<AuthorizationIndicator>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UserFields {
user_field: Vec<UserField>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UserField {
name: String,
value: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
enum ProfileDetails {
CreateProfileDetails(CreateProfileDetails),
CustomerProfileDetails(CustomerProfileDetails),
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct CreateProfileDetails {
create_profile: bool,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct CustomerProfileDetails {
customer_profile_id: Secret<String>,
payment_profile: PaymentProfileDetails,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct PaymentProfileDetails {
payment_profile_id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomerDetails {
id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingOptions {
is_subsequent_auth: bool,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BillTo {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address: Option<Secret<String>>,
city: Option<String>,
state: Option<Secret<String>>,
zip: Option<Secret<String>>,
country: Option<enums::CountryAlpha2>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Order {
description: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SubsequentAuthInformation {
original_network_trans_id: Secret<String>,
// original_auth_amount: String, Required for Discover, Diners Club, JCB, and China Union Pay transactions.
reason: Reason,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Reason {
Resubmission,
#[serde(rename = "delayedCharge")]
DelayedCharge,
Reauthorization,
#[serde(rename = "noShow")]
NoShow,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct AuthorizationIndicator {
authorization_indicator: AuthorizationType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct TransactionVoidOrCaptureRequest {
transaction_type: TransactionType,
#[serde(skip_serializing_if = "Option::is_none")]
amount: Option<f64>,
ref_trans_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetPaymentsRequest {
merchant_authentication: AuthorizedotnetAuthType,
ref_id: Option<String>,
transaction_request: TransactionRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetPaymentCancelOrCaptureRequest {
merchant_authentication: AuthorizedotnetAuthType,
transaction_request: TransactionVoidOrCaptureRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
// The connector enforces field ordering, it expects fields to be in the same order as in their API documentation
pub struct CreateCustomerProfileRequest {
create_customer_profile_request: AuthorizedotnetZeroMandateRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetZeroMandateRequest {
merchant_authentication: AuthorizedotnetAuthType,
profile: Profile,
validation_mode: ValidationMode,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct Profile {
description: String,
payment_profiles: PaymentProfiles,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct PaymentProfiles {
customer_type: CustomerType,
payment: PaymentDetails,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CustomerType {
Individual,
Business,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ValidationMode {
// testMode performs a Luhn mod-10 check on the card number, without further validation at connector.
TestMode,
// liveMode submits a zero-dollar or one-cent transaction (depending on card type and processor support) to confirm that the card number belongs to an active credit or debit account.
LiveMode,
}
impl ForeignTryFrom<Value> for Vec<UserField> {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(metadata: Value) -> Result<Self, Self::Error> {
let hashmap: BTreeMap<String, Value> = serde_json::from_str(&metadata.to_string())
.change_context(errors::ConnectorError::RequestEncodingFailedWithReason(
"Failed to serialize request metadata".to_owned(),
))
.attach_printable("")?;
let mut vector: Self = Self::new();
for (key, value) in hashmap {
vector.push(UserField {
name: key,
value: value.to_string(),
});
}
Ok(vector)
}
}
impl TryFrom<&SetupMandateRouterData> for CreateCustomerProfileRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => {
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
let validation_mode = match item.test_mode {
Some(true) | None => ValidationMode::TestMode,
Some(false) => ValidationMode::LiveMode,
};
Ok(Self {
create_customer_profile_request: AuthorizedotnetZeroMandateRequest {
merchant_authentication,
profile: Profile {
// The payment ID is included in the description because the connector requires unique description when creating a mandate.
description: item.payment_id.clone(),
payment_profiles: PaymentProfiles {
customer_type: CustomerType::Individual,
payment: PaymentDetails::CreditCard(CreditCardDetails {
card_number: (*ccard.card_number).clone(),
expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
card_code: Some(ccard.card_cvc.clone()),
}),
},
},
validation_mode,
},
})
}
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::GooglePay(_) => {
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
let validation_mode = match item.test_mode {
Some(true) | None => ValidationMode::TestMode,
Some(false) => ValidationMode::LiveMode,
};
Ok(Self {
create_customer_profile_request: AuthorizedotnetZeroMandateRequest {
merchant_authentication,
profile: Profile {
// The payment ID is included in the description because the connector requires unique description when creating a mandate.
description: item.payment_id.clone(),
payment_profiles: PaymentProfiles {
customer_type: CustomerType::Individual,
payment: PaymentDetails::OpaqueData(WalletDetails {
data_descriptor: WalletMethod::Googlepay,
data_value: Secret::new(
wallet_data.get_encoded_wallet_token()?,
),
}),
},
},
validation_mode,
},
})
}
WalletData::ApplePay(applepay_token) => {
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
let validation_mode = match item.test_mode {
Some(true) | None => ValidationMode::TestMode,
Some(false) => ValidationMode::LiveMode,
};
Ok(Self {
create_customer_profile_request: AuthorizedotnetZeroMandateRequest {
merchant_authentication,
profile: Profile {
// The payment ID is included in the description because the connector requires unique description when creating a mandate.
description: item.payment_id.clone(),
payment_profiles: PaymentProfiles {
customer_type: CustomerType::Individual,
payment: PaymentDetails::OpaqueData(WalletDetails {
data_descriptor: WalletMethod::Applepay,
data_value: Secret::new(
applepay_token.payment_data.clone(),
),
}),
},
},
validation_mode,
},
})
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))?,
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))?
}
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetSetupMandateResponse {
customer_profile_id: Option<String>,
customer_payment_profile_id_list: Vec<String>,
validation_direct_response_list: Option<Vec<Secret<String>>>,
pub messages: ResponseMessages,
}
// zero dollar response
impl<F, T>
TryFrom<ResponseRouterData<F, AuthorizedotnetSetupMandateResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AuthorizedotnetSetupMandateResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.messages.result_code {
ResultCode::Ok => Ok(Self {
status: enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(item.response.customer_profile_id.map(
|customer_profile_id| MandateReference {
connector_mandate_id:
item.response.customer_payment_profile_id_list.first().map(
|payment_profile_id| {
format!("{customer_profile_id}-{payment_profile_id}")
},
),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
},
)),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
ResultCode::Error => {
let error_code = match item.response.messages.message.first() {
Some(first_error_message) => first_error_message.code.clone(),
None => hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
};
let error_reason = item
.response
.messages
.message
.iter()
.map(|error: &ResponseMessage| error.text.clone())
.collect::<Vec<String>>()
.join(" ");
let response = Err(ErrorResponse {
code: error_code,
message: item.response.messages.result_code.to_string(),
reason: Some(error_reason),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
});
Ok(Self {
response,
status: enums::AttemptStatus::Failure,
..item.data
})
}
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
// The connector enforces field ordering, it expects fields to be in the same order as in their API documentation
pub struct CreateTransactionRequest {
create_transaction_request: AuthorizedotnetPaymentsRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelOrCaptureTransactionRequest {
create_transaction_request: AuthorizedotnetPaymentCancelOrCaptureRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AuthorizationType {
Final,
Pre,
}
impl TryFrom<enums::CaptureMethod> for AuthorizationType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(capture_method: enums::CaptureMethod) -> Result<Self, Self::Error> {
match capture_method {
enums::CaptureMethod::Manual => Ok(Self::Pre),
enums::CaptureMethod::SequentialAutomatic | enums::CaptureMethod::Automatic => {
Ok(Self::Final)
}
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
utils::construct_not_supported_error_report(capture_method, "authorizedotnet"),
)?,
}
}
}
impl TryFrom<&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>>
for CreateTransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
let ref_id = if item.router_data.connector_request_reference_id.len() <= 20 {
Some(item.router_data.connector_request_reference_id.clone())
} else {
None
};
let transaction_request = match item
.router_data
.request
.mandate_id
.clone()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id)
{
Some(api_models::payments::MandateReferenceId::NetworkMandateId(network_trans_id)) => {
TransactionRequest::try_from((item, network_trans_id))?
}
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_id,
)) => TransactionRequest::try_from((item, connector_mandate_id))?,
Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_)) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))?
}
None => {
match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(ccard) => TransactionRequest::try_from((item, ccard)),
PaymentMethodData::Wallet(wallet_data) => {
TransactionRequest::try_from((item, wallet_data))
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"authorizedotnet",
),
))?
}
}
}?,
};
Ok(Self {
create_transaction_request: AuthorizedotnetPaymentsRequest {
merchant_authentication,
ref_id,
transaction_request,
},
})
}
}
impl
TryFrom<(
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
String,
)> for TransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, network_trans_id): (
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
String,
),
) -> Result<Self, Self::Error> {
Ok(Self {
transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
amount: item.amount,
currency_code: item.router_data.request.currency,
payment: Some(match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => {
PaymentDetails::CreditCard(CreditCardDetails {
card_number: (*ccard.card_number).clone(),
expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
card_code: None,
})
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))?
}
}),
profile: None,
order: Order {
description: item.router_data.connector_request_reference_id.clone(),
},
customer: None,
bill_to: item
.router_data
.get_optional_billing()
.and_then(|billing_address| billing_address.address.as_ref())
.map(|address| BillTo {
first_name: address.first_name.clone(),
last_name: address.last_name.clone(),
address: address.line1.clone(),
city: address.city.clone(),
state: address.state.clone(),
zip: address.zip.clone(),
country: address.country,
}),
user_fields: match item.router_data.request.metadata.clone() {
Some(metadata) => Some(UserFields {
user_field: Vec::<UserField>::foreign_try_from(metadata)?,
}),
None => None,
},
processing_options: Some(ProcessingOptions {
is_subsequent_auth: true,
}),
subsequent_auth_information: Some(SubsequentAuthInformation {
original_network_trans_id: Secret::new(network_trans_id),
reason: Reason::Resubmission,
}),
authorization_indicator_type: match item.router_data.request.capture_method {
Some(capture_method) => Some(AuthorizationIndicator {
authorization_indicator: capture_method.try_into()?,
}),
None => None,
},
})
}
}
impl
TryFrom<(
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
api_models::payments::ConnectorMandateReferenceId,
)> for TransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, connector_mandate_id): (
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
api_models::payments::ConnectorMandateReferenceId,
),
) -> Result<Self, Self::Error> {
let mandate_id = connector_mandate_id
.get_connector_mandate_id()
.ok_or(errors::ConnectorError::MissingConnectorMandateID)?;
Ok(Self {
transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
amount: item.amount,
currency_code: item.router_data.request.currency,
payment: None,
profile: mandate_id
.split_once('-')
.map(|(customer_profile_id, payment_profile_id)| {
ProfileDetails::CustomerProfileDetails(CustomerProfileDetails {
customer_profile_id: Secret::from(customer_profile_id.to_string()),
payment_profile: PaymentProfileDetails {
payment_profile_id: Secret::from(payment_profile_id.to_string()),
},
})
}),
order: Order {
description: item.router_data.connector_request_reference_id.clone(),
},
customer: None,
bill_to: None,
user_fields: match item.router_data.request.metadata.clone() {
Some(metadata) => Some(UserFields {
user_field: Vec::<UserField>::foreign_try_from(metadata)?,
}),
None => None,
},
processing_options: Some(ProcessingOptions {
is_subsequent_auth: true,
}),
subsequent_auth_information: None,
authorization_indicator_type: match item.router_data.request.capture_method {
Some(capture_method) => Some(AuthorizationIndicator {
authorization_indicator: capture_method.try_into()?,
}),
None => None,
},
})
}
}
impl
TryFrom<(
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
&Card,
)> for TransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, ccard): (
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
&Card,
),
) -> Result<Self, Self::Error> {
let (profile, customer) = if item.router_data.request.is_mandate_payment() {
(
Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails {
create_profile: true,
})),
Some(CustomerDetails {
//The payment ID is included in the customer details because the connector requires unique customer information with a length of fewer than 20 characters when creating a mandate.
//If the length exceeds 20 characters, a random alphanumeric string is used instead.
id: if item.router_data.payment_id.len() <= 20 {
item.router_data.payment_id.clone()
} else {
Alphanumeric.sample_string(&mut rand::thread_rng(), 20)
},
}),
)
} else {
(None, None)
};
Ok(Self {
transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
amount: item.amount,
currency_code: item.router_data.request.currency,
payment: Some(PaymentDetails::CreditCard(CreditCardDetails {
card_number: (*ccard.card_number).clone(),
expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
card_code: Some(ccard.card_cvc.clone()),
})),
profile,
order: Order {
description: item.router_data.connector_request_reference_id.clone(),
},
customer,
bill_to: item
.router_data
.get_optional_billing()
.and_then(|billing_address| billing_address.address.as_ref())
.map(|address| BillTo {
first_name: address.first_name.clone(),
last_name: address.last_name.clone(),
address: address.line1.clone(),
city: address.city.clone(),
state: address.state.clone(),
zip: address.zip.clone(),
country: address.country,
}),
user_fields: match item.router_data.request.metadata.clone() {
Some(metadata) => Some(UserFields {
user_field: Vec::<UserField>::foreign_try_from(metadata)?,
}),
None => None,
},
processing_options: None,
subsequent_auth_information: None,
authorization_indicator_type: match item.router_data.request.capture_method {
Some(capture_method) => Some(AuthorizationIndicator {
authorization_indicator: capture_method.try_into()?,
}),
None => None,
},
})
}
}
impl
TryFrom<(
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
&WalletData,
)> for TransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, wallet_data): (
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
&WalletData,
),
) -> Result<Self, Self::Error> {
let (profile, customer) = if item.router_data.request.is_mandate_payment() {
(
Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails {
create_profile: true,
})),
Some(CustomerDetails {
id: if item.router_data.payment_id.len() <= 20 {
item.router_data.payment_id.clone()
} else {
Alphanumeric.sample_string(&mut rand::thread_rng(), 20)
},
}),
)
} else {
(None, None)
};
Ok(Self {
transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
amount: item.amount,
currency_code: item.router_data.request.currency,
payment: Some(get_wallet_data(
wallet_data,
&item.router_data.request.complete_authorize_url,
)?),
profile,
order: Order {
description: item.router_data.connector_request_reference_id.clone(),
},
customer,
bill_to: item
.router_data
.get_optional_billing()
.and_then(|billing_address| billing_address.address.as_ref())
.map(|address| BillTo {
first_name: address.first_name.clone(),
last_name: address.last_name.clone(),
address: address.line1.clone(),
city: address.city.clone(),
state: address.state.clone(),
zip: address.zip.clone(),
country: address.country,
}),
user_fields: match item.router_data.request.metadata.clone() {
Some(metadata) => Some(UserFields {
user_field: Vec::<UserField>::foreign_try_from(metadata)?,
}),
None => None,
},
processing_options: None,
subsequent_auth_information: None,
authorization_indicator_type: match item.router_data.request.capture_method {
Some(capture_method) => Some(AuthorizationIndicator {
authorization_indicator: capture_method.try_into()?,
}),
None => None,
},
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for CancelOrCaptureTransactionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let transaction_request = TransactionVoidOrCaptureRequest {
amount: None, //amount is not required for void
transaction_type: TransactionType::Void,
ref_trans_id: item.request.connector_transaction_id.to_string(),
};
let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
create_transaction_request: AuthorizedotnetPaymentCancelOrCaptureRequest {
merchant_authentication,
transaction_request,
},
})
}
}
impl TryFrom<&AuthorizedotnetRouterData<&PaymentsCaptureRouterData>>
for CancelOrCaptureTransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthorizedotnetRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let transaction_request = TransactionVoidOrCaptureRequest {
amount: Some(item.amount),
transaction_type: TransactionType::Capture,
ref_trans_id: item
.router_data
.request
.connector_transaction_id
.to_string(),
};
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
create_transaction_request: AuthorizedotnetPaymentCancelOrCaptureRequest {
merchant_authentication,
transaction_request,
},
})
}
}
#[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)]
pub enum AuthorizedotnetPaymentStatus {
#[serde(rename = "1")]
Approved,
#[serde(rename = "2")]
Declined,
#[serde(rename = "3")]
Error,
#[serde(rename = "4")]
#[default]
HeldForReview,
#[serde(rename = "5")]
RequiresAction,
}
#[derive(Debug, Clone, serde::Deserialize, Serialize)]
pub enum AuthorizedotnetRefundStatus {
#[serde(rename = "1")]
Approved,
#[serde(rename = "2")]
Declined,
#[serde(rename = "3")]
Error,
#[serde(rename = "4")]
HeldForReview,
}
fn get_payment_status(
(item, auto_capture): (AuthorizedotnetPaymentStatus, bool),
) -> enums::AttemptStatus {
match item {
AuthorizedotnetPaymentStatus::Approved => {
if auto_capture {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
AuthorizedotnetPaymentStatus::Declined | AuthorizedotnetPaymentStatus::Error => {
enums::AttemptStatus::Failure
}
AuthorizedotnetPaymentStatus::RequiresAction => enums::AttemptStatus::AuthenticationPending,
AuthorizedotnetPaymentStatus::HeldForReview => enums::AttemptStatus::Pending,
}
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Serialize)]
pub struct ResponseMessage {
code: String,
pub text: String,
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Serialize, strum::Display)]
enum ResultCode {
#[default]
Ok,
Error,
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResponseMessages {
result_code: ResultCode,
pub message: Vec<ResponseMessage>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorMessage {
pub error_code: String,
pub error_text: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum TransactionResponse {
AuthorizedotnetTransactionResponse(Box<AuthorizedotnetTransactionResponse>),
AuthorizedotnetTransactionResponseError(Box<AuthorizedotnetTransactionResponseError>),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct AuthorizedotnetTransactionResponseError {
_supplemental_data_qualification_indicator: i64,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetTransactionResponse {
response_code: AuthorizedotnetPaymentStatus,
#[serde(rename = "transId")]
transaction_id: String,
network_trans_id: Option<Secret<String>>,
pub(super) account_number: Option<Secret<String>>,
pub(super) errors: Option<Vec<ErrorMessage>>,
secure_acceptance: Option<SecureAcceptance>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
response_code: AuthorizedotnetRefundStatus,
#[serde(rename = "transId")]
transaction_id: String,
#[allow(dead_code)]
network_trans_id: Option<Secret<String>>,
pub account_number: Option<Secret<String>>,
pub errors: Option<Vec<ErrorMessage>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct SecureAcceptance {
secure_acceptance_url: Option<url::Url>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetPaymentsResponse {
pub transaction_response: Option<TransactionResponse>,
pub profile_response: Option<AuthorizedotnetNonZeroMandateResponse>,
pub messages: ResponseMessages,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetNonZeroMandateResponse {
customer_profile_id: Option<String>,
customer_payment_profile_id_list: Option<Vec<String>>,
pub messages: ResponseMessages,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetVoidResponse {
pub transaction_response: Option<VoidResponse>,
pub messages: ResponseMessages,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoidResponse {
response_code: AuthorizedotnetVoidStatus,
#[serde(rename = "transId")]
transaction_id: String,
network_trans_id: Option<Secret<String>>,
pub account_number: Option<Secret<String>>,
pub errors: Option<Vec<ErrorMessage>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum AuthorizedotnetVoidStatus {
#[serde(rename = "1")]
Approved,
#[serde(rename = "2")]
Declined,
#[serde(rename = "3")]
Error,
#[serde(rename = "4")]
HeldForReview,
}
impl From<AuthorizedotnetVoidStatus> for enums::AttemptStatus {
fn from(item: AuthorizedotnetVoidStatus) -> Self {
match item {
AuthorizedotnetVoidStatus::Approved => Self::Voided,
AuthorizedotnetVoidStatus::Declined | AuthorizedotnetVoidStatus::Error => {
Self::VoidFailed
}
AuthorizedotnetVoidStatus::HeldForReview => Self::VoidInitiated,
}
}
}
impl<F, T>
ForeignTryFrom<(
ResponseRouterData<F, AuthorizedotnetPaymentsResponse, T, PaymentsResponseData>,
bool,
)> for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, is_auto_capture): (
ResponseRouterData<F, AuthorizedotnetPaymentsResponse, T, PaymentsResponseData>,
bool,
),
) -> Result<Self, Self::Error> {
match &item.response.transaction_response {
Some(TransactionResponse::AuthorizedotnetTransactionResponse(transaction_response)) => {
let status = get_payment_status((
transaction_response.response_code.clone(),
is_auto_capture,
));
let error = transaction_response.errors.as_ref().and_then(|errors| {
errors.iter().next().map(|error| ErrorResponse {
code: error.error_code.clone(),
message: error.error_text.clone(),
reason: Some(error.error_text.clone()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(transaction_response.transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
});
let metadata = transaction_response
.account_number
.as_ref()
.map(|acc_no| {
construct_refund_payment_details(acc_no.clone().expose()).encode_to_value()
})
.transpose()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "connector_metadata",
})?;
let url = transaction_response
.secure_acceptance
.as_ref()
.and_then(|x| x.secure_acceptance_url.to_owned());
let redirection_data = url.map(|url| RedirectForm::from((url, Method::Get)));
let mandate_reference = item.response.profile_response.map(|profile_response| {
let payment_profile_id = profile_response
.customer_payment_profile_id_list
.and_then(|customer_payment_profile_id_list| {
customer_payment_profile_id_list.first().cloned()
});
MandateReference {
connector_mandate_id: profile_response.customer_profile_id.and_then(
|customer_profile_id| {
payment_profile_id.map(|payment_profile_id| {
format!("{customer_profile_id}-{payment_profile_id}")
})
},
),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}
});
Ok(Self {
status,
response: match error {
Some(err) => Err(err),
None => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
transaction_response.transaction_id.clone(),
),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: metadata,
network_txn_id: transaction_response
.network_trans_id
.clone()
.map(|network_trans_id| network_trans_id.expose()),
connector_response_reference_id: Some(
transaction_response.transaction_id.clone(),
),
incremental_authorization_allowed: None,
charges: None,
}),
},
..item.data
})
}
Some(TransactionResponse::AuthorizedotnetTransactionResponseError(_)) | None => {
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(get_err_response(item.http_code, item.response.messages)?),
..item.data
})
}
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AuthorizedotnetVoidResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AuthorizedotnetVoidResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match &item.response.transaction_response {
Some(transaction_response) => {
let status = enums::AttemptStatus::from(transaction_response.response_code.clone());
let error = transaction_response.errors.as_ref().and_then(|errors| {
errors.iter().next().map(|error| ErrorResponse {
code: error.error_code.clone(),
message: error.error_text.clone(),
reason: Some(error.error_text.clone()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(transaction_response.transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
});
let metadata = transaction_response
.account_number
.as_ref()
.map(|acc_no| {
construct_refund_payment_details(acc_no.clone().expose()).encode_to_value()
})
.transpose()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "connector_metadata",
})?;
Ok(Self {
status,
response: match error {
Some(err) => Err(err),
None => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
transaction_response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: metadata,
network_txn_id: transaction_response
.network_trans_id
.clone()
.map(|network_trans_id| network_trans_id.expose()),
connector_response_reference_id: Some(
transaction_response.transaction_id.clone(),
),
incremental_authorization_allowed: None,
charges: None,
}),
},
..item.data
})
}
None => Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(get_err_response(item.http_code, item.response.messages)?),
..item.data
}),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct RefundTransactionRequest {
transaction_type: TransactionType,
amount: f64,
currency_code: String,
payment: PaymentDetails,
#[serde(rename = "refTransId")]
reference_transaction_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetRefundRequest {
merchant_authentication: AuthorizedotnetAuthType,
transaction_request: RefundTransactionRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
// The connector enforces field ordering, it expects fields to be in the same order as in their API documentation
pub struct CreateRefundRequest {
create_transaction_request: AuthorizedotnetRefundRequest,
}
impl<F> TryFrom<&AuthorizedotnetRouterData<&RefundsRouterData<F>>> for CreateRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthorizedotnetRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let payment_details = item
.router_data
.request
.connector_metadata
.as_ref()
.get_required_value("connector_metadata")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "connector_metadata",
})?
.clone();
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
let transaction_request = RefundTransactionRequest {
transaction_type: TransactionType::Refund,
amount: item.amount,
payment: payment_details
.parse_value("PaymentDetails")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "payment_details",
})?,
currency_code: item.router_data.request.currency.to_string(),
reference_transaction_id: item.router_data.request.connector_transaction_id.clone(),
};
Ok(Self {
create_transaction_request: AuthorizedotnetRefundRequest {
merchant_authentication,
transaction_request,
},
})
}
}
impl From<AuthorizedotnetRefundStatus> for enums::RefundStatus {
fn from(item: AuthorizedotnetRefundStatus) -> Self {
match item {
AuthorizedotnetRefundStatus::Declined | AuthorizedotnetRefundStatus::Error => {
Self::Failure
}
AuthorizedotnetRefundStatus::Approved | AuthorizedotnetRefundStatus::HeldForReview => {
Self::Pending
}
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetRefundResponse {
pub transaction_response: RefundResponse,
pub messages: ResponseMessages,
}
impl<F> TryFrom<RefundsResponseRouterData<F, AuthorizedotnetRefundResponse>>
for RefundsRouterData<F>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<F, AuthorizedotnetRefundResponse>,
) -> Result<Self, Self::Error> {
let transaction_response = &item.response.transaction_response;
let refund_status = enums::RefundStatus::from(transaction_response.response_code.clone());
let error = transaction_response.errors.clone().and_then(|errors| {
errors.first().map(|error| ErrorResponse {
code: error.error_code.clone(),
message: error.error_text.clone(),
reason: Some(error.error_text.clone()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(transaction_response.transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
});
Ok(Self {
response: match error {
Some(err) => Err(err),
None => Ok(RefundsResponseData {
connector_refund_id: transaction_response.transaction_id.clone(),
refund_status,
}),
},
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionDetails {
merchant_authentication: AuthorizedotnetAuthType,
#[serde(rename = "transId")]
transaction_id: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetCreateSyncRequest {
get_transaction_details_request: TransactionDetails,
}
impl<F> TryFrom<&AuthorizedotnetRouterData<&RefundsRouterData<F>>>
for AuthorizedotnetCreateSyncRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthorizedotnetRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let transaction_id = item.router_data.request.get_connector_refund_id()?;
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
let payload = Self {
get_transaction_details_request: TransactionDetails {
merchant_authentication,
transaction_id: Some(transaction_id),
},
};
Ok(payload)
}
}
impl TryFrom<&PaymentsSyncRouterData> for AuthorizedotnetCreateSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let transaction_id = Some(
item.request
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
);
let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
let payload = Self {
get_transaction_details_request: TransactionDetails {
merchant_authentication,
transaction_id,
},
};
Ok(payload)
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum SyncStatus {
RefundSettledSuccessfully,
RefundPendingSettlement,
AuthorizedPendingCapture,
CapturedPendingSettlement,
SettledSuccessfully,
Declined,
Voided,
CouldNotVoid,
GeneralError,
#[serde(rename = "FDSPendingReview")]
FDSPendingReview,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum RSyncStatus {
RefundSettledSuccessfully,
RefundPendingSettlement,
Declined,
GeneralError,
Voided,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SyncTransactionResponse {
#[serde(rename = "transId")]
transaction_id: String,
transaction_status: SyncStatus,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct AuthorizedotnetSyncResponse {
transaction: Option<SyncTransactionResponse>,
messages: ResponseMessages,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RSyncTransactionResponse {
#[serde(rename = "transId")]
transaction_id: String,
transaction_status: RSyncStatus,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct AuthorizedotnetRSyncResponse {
transaction: Option<RSyncTransactionResponse>,
messages: ResponseMessages,
}
impl From<SyncStatus> for enums::AttemptStatus {
fn from(transaction_status: SyncStatus) -> Self {
match transaction_status {
SyncStatus::SettledSuccessfully | SyncStatus::CapturedPendingSettlement => {
Self::Charged
}
SyncStatus::AuthorizedPendingCapture => Self::Authorized,
SyncStatus::Declined => Self::AuthenticationFailed,
SyncStatus::Voided => Self::Voided,
SyncStatus::CouldNotVoid => Self::VoidFailed,
SyncStatus::GeneralError => Self::Failure,
SyncStatus::RefundSettledSuccessfully
| SyncStatus::RefundPendingSettlement
| SyncStatus::FDSPendingReview => Self::Pending,
}
}
}
impl From<RSyncStatus> for enums::RefundStatus {
fn from(transaction_status: RSyncStatus) -> Self {
match transaction_status {
RSyncStatus::RefundSettledSuccessfully => Self::Success,
RSyncStatus::RefundPendingSettlement => Self::Pending,
RSyncStatus::Declined | RSyncStatus::GeneralError | RSyncStatus::Voided => {
Self::Failure
}
}
}
}
impl TryFrom<RefundsResponseRouterData<RSync, AuthorizedotnetRSyncResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, AuthorizedotnetRSyncResponse>,
) -> Result<Self, Self::Error> {
match item.response.transaction {
Some(transaction) => {
let refund_status = enums::RefundStatus::from(transaction.transaction_status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: transaction.transaction_id,
refund_status,
}),
..item.data
})
}
None => Ok(Self {
response: Err(get_err_response(item.http_code, item.response.messages)?),
..item.data
}),
}
}
}
impl<F, Req> TryFrom<ResponseRouterData<F, AuthorizedotnetSyncResponse, Req, PaymentsResponseData>>
for RouterData<F, Req, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AuthorizedotnetSyncResponse, Req, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.transaction {
Some(transaction) => {
let payment_status = enums::AttemptStatus::from(transaction.transaction_status);
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
transaction.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(transaction.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
status: payment_status,
..item.data
})
}
None => Ok(Self {
response: Err(get_err_response(item.http_code, item.response.messages)?),
..item.data
}),
}
}
}
#[derive(Debug, Default, Deserialize)]
pub struct ErrorDetails {
pub code: Option<String>,
#[serde(rename = "type")]
pub error_type: Option<String>,
pub message: Option<String>,
pub param: Option<String>,
}
#[derive(Default, Debug, Deserialize)]
pub struct AuthorizedotnetErrorResponse {
pub error: ErrorDetails,
}
fn construct_refund_payment_details(masked_number: String) -> PaymentDetails {
PaymentDetails::CreditCard(CreditCardDetails {
card_number: masked_number.into(),
expiration_date: "XXXX".to_string().into(),
card_code: None,
})
}
impl TryFrom<Option<enums::CaptureMethod>> for TransactionType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(capture_method: Option<enums::CaptureMethod>) -> Result<Self, Self::Error> {
match capture_method {
Some(enums::CaptureMethod::Manual) => Ok(Self::Authorization),
Some(enums::CaptureMethod::SequentialAutomatic)
| Some(enums::CaptureMethod::Automatic)
| None => Ok(Self::Payment),
Some(enums::CaptureMethod::ManualMultiple) => {
Err(utils::construct_not_supported_error_report(
enums::CaptureMethod::ManualMultiple,
"authorizedotnet",
))?
}
Some(enums::CaptureMethod::Scheduled) => {
Err(utils::construct_not_supported_error_report(
enums::CaptureMethod::Scheduled,
"authorizedotnet",
))?
}
}
}
}
fn get_err_response(
status_code: u16,
message: ResponseMessages,
) -> Result<ErrorResponse, errors::ConnectorError> {
let response_message = message
.message
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
Ok(ErrorResponse {
code: response_message.code.clone(),
message: response_message.text.clone(),
reason: Some(response_message.text.clone()),
status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetWebhookObjectId {
pub webhook_id: String,
pub event_type: AuthorizedotnetWebhookEvent,
pub payload: AuthorizedotnetWebhookPayload,
}
#[derive(Debug, Deserialize)]
pub struct AuthorizedotnetWebhookPayload {
pub id: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetWebhookEventType {
pub event_type: AuthorizedotnetIncomingWebhookEventType,
}
#[derive(Debug, Deserialize)]
pub enum AuthorizedotnetWebhookEvent {
#[serde(rename = "net.authorize.payment.authorization.created")]
AuthorizationCreated,
#[serde(rename = "net.authorize.payment.priorAuthCapture.created")]
PriorAuthCapture,
#[serde(rename = "net.authorize.payment.authcapture.created")]
AuthCapCreated,
#[serde(rename = "net.authorize.payment.capture.created")]
CaptureCreated,
#[serde(rename = "net.authorize.payment.void.created")]
VoidCreated,
#[serde(rename = "net.authorize.payment.refund.created")]
RefundCreated,
}
///Including Unknown to map unknown webhook events
#[derive(Debug, Deserialize)]
pub enum AuthorizedotnetIncomingWebhookEventType {
#[serde(rename = "net.authorize.payment.authorization.created")]
AuthorizationCreated,
#[serde(rename = "net.authorize.payment.priorAuthCapture.created")]
PriorAuthCapture,
#[serde(rename = "net.authorize.payment.authcapture.created")]
AuthCapCreated,
#[serde(rename = "net.authorize.payment.capture.created")]
CaptureCreated,
#[serde(rename = "net.authorize.payment.void.created")]
VoidCreated,
#[serde(rename = "net.authorize.payment.refund.created")]
RefundCreated,
#[serde(other)]
Unknown,
}
impl From<AuthorizedotnetIncomingWebhookEventType> for IncomingWebhookEvent {
fn from(event_type: AuthorizedotnetIncomingWebhookEventType) -> Self {
match event_type {
AuthorizedotnetIncomingWebhookEventType::AuthorizationCreated
| AuthorizedotnetIncomingWebhookEventType::PriorAuthCapture
| AuthorizedotnetIncomingWebhookEventType::AuthCapCreated
| AuthorizedotnetIncomingWebhookEventType::CaptureCreated
| AuthorizedotnetIncomingWebhookEventType::VoidCreated => Self::PaymentIntentSuccess,
AuthorizedotnetIncomingWebhookEventType::RefundCreated => Self::RefundSuccess,
AuthorizedotnetIncomingWebhookEventType::Unknown => Self::EventNotSupported,
}
}
}
impl From<AuthorizedotnetWebhookEvent> for SyncStatus {
// status mapping reference https://developer.authorize.net/api/reference/features/webhooks.html#Event_Types_and_Payloads
fn from(event_type: AuthorizedotnetWebhookEvent) -> Self {
match event_type {
AuthorizedotnetWebhookEvent::AuthorizationCreated => Self::AuthorizedPendingCapture,
AuthorizedotnetWebhookEvent::CaptureCreated
| AuthorizedotnetWebhookEvent::AuthCapCreated => Self::CapturedPendingSettlement,
AuthorizedotnetWebhookEvent::PriorAuthCapture => Self::SettledSuccessfully,
AuthorizedotnetWebhookEvent::VoidCreated => Self::Voided,
AuthorizedotnetWebhookEvent::RefundCreated => Self::RefundSettledSuccessfully,
}
}
}
pub fn get_trans_id(
details: &AuthorizedotnetWebhookObjectId,
) -> Result<String, errors::ConnectorError> {
details
.payload
.id
.clone()
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)
}
impl TryFrom<AuthorizedotnetWebhookObjectId> for AuthorizedotnetSyncResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: AuthorizedotnetWebhookObjectId) -> Result<Self, Self::Error> {
Ok(Self {
transaction: Some(SyncTransactionResponse {
transaction_id: get_trans_id(&item)?,
transaction_status: SyncStatus::from(item.event_type),
}),
messages: ResponseMessages {
..Default::default()
},
})
}
}
fn get_wallet_data(
wallet_data: &WalletData,
return_url: &Option<String>,
) -> CustomResult<PaymentDetails, errors::ConnectorError> {
match wallet_data {
WalletData::GooglePay(_) => Ok(PaymentDetails::OpaqueData(WalletDetails {
data_descriptor: WalletMethod::Googlepay,
data_value: Secret::new(wallet_data.get_encoded_wallet_token()?),
})),
WalletData::ApplePay(applepay_token) => Ok(PaymentDetails::OpaqueData(WalletDetails {
data_descriptor: WalletMethod::Applepay,
data_value: Secret::new(applepay_token.payment_data.clone()),
})),
WalletData::PaypalRedirect(_) => Ok(PaymentDetails::PayPal(PayPalDetails {
success_url: return_url.to_owned(),
cancel_url: return_url.to_owned(),
})),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| 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(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))?,
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetQueryParams {
payer_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaypalConfirmRequest {
create_transaction_request: PaypalConfirmTransactionRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaypalConfirmTransactionRequest {
merchant_authentication: AuthorizedotnetAuthType,
transaction_request: TransactionConfirmRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionConfirmRequest {
transaction_type: TransactionType,
payment: PaypalPaymentConfirm,
ref_trans_id: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaypalPaymentConfirm {
pay_pal: Paypal,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Paypal {
#[serde(rename = "payerID")]
payer_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaypalQueryParams {
#[serde(rename = "PayerID")]
payer_id: Option<Secret<String>>,
}
impl TryFrom<&AuthorizedotnetRouterData<&PaymentsCompleteAuthorizeRouterData>>
for PaypalConfirmRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthorizedotnetRouterData<&PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let params = item
.router_data
.request
.redirect_response
.as_ref()
.and_then(|redirect_response| redirect_response.params.as_ref())
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let query_params: PaypalQueryParams = serde_urlencoded::from_str(params.peek())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable("Failed to parse connector response")?;
let payer_id = query_params.payer_id;
let transaction_type = match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual) => Ok(TransactionType::ContinueAuthorization),
Some(enums::CaptureMethod::SequentialAutomatic)
| Some(enums::CaptureMethod::Automatic)
| None => Ok(TransactionType::ContinueCapture),
Some(enums::CaptureMethod::ManualMultiple) => {
Err(errors::ConnectorError::NotSupported {
message: enums::CaptureMethod::ManualMultiple.to_string(),
connector: "authorizedotnet",
})
}
Some(enums::CaptureMethod::Scheduled) => Err(errors::ConnectorError::NotSupported {
message: enums::CaptureMethod::Scheduled.to_string(),
connector: "authorizedotnet",
}),
}?;
let transaction_request = TransactionConfirmRequest {
transaction_type,
payment: PaypalPaymentConfirm {
pay_pal: Paypal { payer_id },
},
ref_trans_id: item.router_data.request.connector_transaction_id.clone(),
};
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
create_transaction_request: PaypalConfirmTransactionRequest {
merchant_authentication,
transaction_request,
},
})
}
}
| 14,577 | 2,214 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs | .rs | use api_models::payments::AdditionalPaymentData;
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 _, 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 CardMandateInfo {
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
}
#[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 = extract_card_mandate_info(
item.router_data
.request
.additional_payment_method_data
.clone(),
)?;
Ok(Self::Mandate(MandatePaymentRequest::try_from((
item,
mandate_data,
))?))
}
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
fn extract_card_mandate_info(
additional_payment_method_data: Option<AdditionalPaymentData>,
) -> Result<CardMandateInfo, Error> {
match additional_payment_method_data {
Some(AdditionalPaymentData::Card(card_data)) => Ok(CardMandateInfo {
card_exp_month: card_data.card_exp_month.clone().ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "card_exp_month",
}
})?,
card_exp_year: card_data.card_exp_year.clone().ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "card_exp_year",
}
})?,
}),
_ => Err(errors::ConnectorError::MissingRequiredFields {
field_names: vec!["card_exp_month", "card_exp_year"],
}
.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,
}),
..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,
}),
..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,
}),
..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,
}),
..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,
}),
..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,
}),
..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,
}),
..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)?
)))
}
| 9,565 | 2,215 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs | .rs | 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,
}),
)
}
};
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,
}),
..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,
}),
..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,
}),
..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
}
},
}
}
}
| 3,552 | 2,216 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs | .rs | #[cfg(feature = "payouts")]
use api_models::payouts::{PayoutMethodData, Wallet as WalletPayout};
use api_models::{enums, webhooks::IncomingWebhookEvent};
use base64::Engine;
use common_enums::enums as storage_enums;
#[cfg(feature = "payouts")]
use common_utils::pii::Email;
use common_utils::{consts, errors::CustomResult, request::Method, types::StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{
BankDebitData, BankRedirectData, BankTransferData, CardRedirectData, GiftCardData,
PayLaterData, PaymentMethodData, VoucherData, WalletData,
},
router_data::{AccessToken, ConnectorAuthType, RouterData},
router_flow_types::{
payments::{Authorize, PostSessionTokens},
refunds::{Execute, RSync},
VerifyWebhookSource,
},
router_request_types::{
PaymentsAuthorizeData, PaymentsPostSessionTokensData, PaymentsSyncData, ResponseId,
VerifyWebhookSourceRequestData,
},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
VerifyWebhookSourceResponseData, VerifyWebhookStatus,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData,
PaymentsPostSessionTokensRouterData, RefreshTokenRouterData, RefundsRouterData,
SdkSessionUpdateRouterData, SetupMandateRouterData, VerifyWebhookSourceRouterData,
},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::PoFulfill, router_response_types::PayoutsResponseData,
types::PayoutsRouterData,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use url::Url;
use utils::ForeignTryFrom;
#[cfg(feature = "payouts")]
use crate::{constants, types::PayoutsResponseRouterData};
use crate::{
types::{PaymentsCaptureResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, missing_field_err, to_connector_meta, AccessTokenRequestInfo, AddressDetailsData,
CardData, PaymentsAuthorizeRequestData, PaymentsPostSessionTokensRequestData,
RouterData as OtherRouterData,
},
};
#[derive(Debug, Serialize)]
pub struct PaypalRouterData<T> {
pub amount: StringMajorUnit,
pub shipping_cost: Option<StringMajorUnit>,
pub order_tax_amount: Option<StringMajorUnit>,
pub order_amount: Option<StringMajorUnit>,
pub router_data: T,
}
impl<T>
TryFrom<(
StringMajorUnit,
Option<StringMajorUnit>,
Option<StringMajorUnit>,
Option<StringMajorUnit>,
T,
)> for PaypalRouterData<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(amount, shipping_cost, order_tax_amount, order_amount, item): (
StringMajorUnit,
Option<StringMajorUnit>,
Option<StringMajorUnit>,
Option<StringMajorUnit>,
T,
),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
shipping_cost,
order_tax_amount,
order_amount,
router_data: item,
})
}
}
mod webhook_headers {
pub const PAYPAL_TRANSMISSION_ID: &str = "paypal-transmission-id";
pub const PAYPAL_TRANSMISSION_TIME: &str = "paypal-transmission-time";
pub const PAYPAL_TRANSMISSION_SIG: &str = "paypal-transmission-sig";
pub const PAYPAL_CERT_URL: &str = "paypal-cert-url";
pub const PAYPAL_AUTH_ALGO: &str = "paypal-auth-algo";
}
pub mod auth_headers {
pub const PAYPAL_PARTNER_ATTRIBUTION_ID: &str = "PayPal-Partner-Attribution-Id";
pub const PREFER: &str = "Prefer";
pub const PAYPAL_REQUEST_ID: &str = "PayPal-Request-Id";
pub const PAYPAL_AUTH_ASSERTION: &str = "PayPal-Auth-Assertion";
}
const ORDER_QUANTITY: u16 = 1;
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaypalPaymentIntent {
Capture,
Authorize,
Authenticate,
}
#[derive(Default, Debug, Clone, Serialize, Eq, PartialEq, Deserialize)]
pub struct OrderAmount {
pub currency_code: storage_enums::Currency,
pub value: StringMajorUnit,
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct OrderRequestAmount {
pub currency_code: storage_enums::Currency,
pub value: StringMajorUnit,
pub breakdown: AmountBreakdown,
}
impl From<&PaypalRouterData<&PaymentsAuthorizeRouterData>> for OrderRequestAmount {
fn from(item: &PaypalRouterData<&PaymentsAuthorizeRouterData>) -> Self {
Self {
currency_code: item.router_data.request.currency,
value: item.amount.clone(),
breakdown: AmountBreakdown {
item_total: OrderAmount {
currency_code: item.router_data.request.currency,
value: item.amount.clone(),
},
tax_total: None,
shipping: Some(OrderAmount {
currency_code: item.router_data.request.currency,
value: item
.shipping_cost
.clone()
.unwrap_or(StringMajorUnit::zero()),
}),
},
}
}
}
impl TryFrom<&PaypalRouterData<&PaymentsPostSessionTokensRouterData>> for OrderRequestAmount {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaypalRouterData<&PaymentsPostSessionTokensRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
currency_code: item.router_data.request.currency,
value: item.amount.clone(),
breakdown: AmountBreakdown {
item_total: OrderAmount {
currency_code: item.router_data.request.currency,
value: item.order_amount.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "order_amount",
},
)?,
},
tax_total: None,
shipping: Some(OrderAmount {
currency_code: item.router_data.request.currency,
value: item
.shipping_cost
.clone()
.unwrap_or(StringMajorUnit::zero()),
}),
},
})
}
}
impl TryFrom<&PaypalRouterData<&SdkSessionUpdateRouterData>> for OrderRequestAmount {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaypalRouterData<&SdkSessionUpdateRouterData>) -> Result<Self, Self::Error> {
Ok(Self {
currency_code: item.router_data.request.currency,
value: item.amount.clone(),
breakdown: AmountBreakdown {
item_total: OrderAmount {
currency_code: item.router_data.request.currency,
value: item.order_amount.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "order_amount",
},
)?,
},
tax_total: Some(OrderAmount {
currency_code: item.router_data.request.currency,
value: item.order_tax_amount.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "order_tax_amount",
},
)?,
}),
shipping: Some(OrderAmount {
currency_code: item.router_data.request.currency,
value: item
.shipping_cost
.clone()
.unwrap_or(StringMajorUnit::zero()),
}),
},
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct AmountBreakdown {
item_total: OrderAmount,
tax_total: Option<OrderAmount>,
shipping: Option<OrderAmount>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct PurchaseUnitRequest {
reference_id: Option<String>, //reference for an item in purchase_units
invoice_id: Option<String>, //The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives.
custom_id: Option<String>, //Used to reconcile client transactions with PayPal transactions.
amount: OrderRequestAmount,
#[serde(skip_serializing_if = "Option::is_none")]
payee: Option<Payee>,
shipping: Option<ShippingAddress>,
items: Vec<ItemDetails>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct Payee {
merchant_id: Secret<String>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct ItemDetails {
name: String,
quantity: u16,
unit_amount: OrderAmount,
tax: Option<OrderAmount>,
}
impl From<&PaypalRouterData<&PaymentsAuthorizeRouterData>> for ItemDetails {
fn from(item: &PaypalRouterData<&PaymentsAuthorizeRouterData>) -> Self {
Self {
name: format!(
"Payment for invoice {}",
item.router_data.connector_request_reference_id
),
quantity: ORDER_QUANTITY,
unit_amount: OrderAmount {
currency_code: item.router_data.request.currency,
value: item.amount.clone(),
},
tax: None,
}
}
}
impl TryFrom<&PaypalRouterData<&PaymentsPostSessionTokensRouterData>> for ItemDetails {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaypalRouterData<&PaymentsPostSessionTokensRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
name: format!(
"Payment for invoice {}",
item.router_data.connector_request_reference_id
),
quantity: ORDER_QUANTITY,
unit_amount: OrderAmount {
currency_code: item.router_data.request.currency,
value: item.order_amount.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "order_amount",
},
)?,
},
tax: None,
})
}
}
impl TryFrom<&PaypalRouterData<&SdkSessionUpdateRouterData>> for ItemDetails {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaypalRouterData<&SdkSessionUpdateRouterData>) -> Result<Self, Self::Error> {
Ok(Self {
name: format!(
"Payment for invoice {}",
item.router_data.connector_request_reference_id
),
quantity: ORDER_QUANTITY,
unit_amount: OrderAmount {
currency_code: item.router_data.request.currency,
value: item.order_amount.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "order_amount",
},
)?,
},
tax: Some(OrderAmount {
currency_code: item.router_data.request.currency,
value: item.order_tax_amount.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "order_tax_amount",
},
)?,
}),
})
}
}
#[derive(Default, Debug, Serialize, Eq, PartialEq, Deserialize)]
pub struct Address {
address_line_1: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
country_code: enums::CountryAlpha2,
admin_area_2: Option<String>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct ShippingAddress {
address: Option<Address>,
name: Option<ShippingName>,
}
impl From<&PaypalRouterData<&PaymentsAuthorizeRouterData>> for ShippingAddress {
fn from(item: &PaypalRouterData<&PaymentsAuthorizeRouterData>) -> Self {
Self {
address: get_address_info(item.router_data.get_optional_shipping()),
name: Some(ShippingName {
full_name: item
.router_data
.get_optional_shipping()
.and_then(|inner_data| inner_data.address.as_ref())
.and_then(|inner_data| inner_data.first_name.clone()),
}),
}
}
}
impl From<&PaypalRouterData<&PaymentsPostSessionTokensRouterData>> for ShippingAddress {
fn from(item: &PaypalRouterData<&PaymentsPostSessionTokensRouterData>) -> Self {
Self {
address: get_address_info(item.router_data.get_optional_shipping()),
name: Some(ShippingName {
full_name: item
.router_data
.get_optional_shipping()
.and_then(|inner_data| inner_data.address.as_ref())
.and_then(|inner_data| inner_data.first_name.clone()),
}),
}
}
}
#[derive(Debug, Serialize, PartialEq, Eq)]
pub struct PaypalUpdateOrderRequest(Vec<Operation>);
impl PaypalUpdateOrderRequest {
pub fn get_inner_value(self) -> Vec<Operation> {
self.0
}
}
#[derive(Debug, Serialize, PartialEq, Eq)]
pub struct Operation {
pub op: PaypalOperationType,
pub path: String,
pub value: Value,
}
#[derive(Debug, Serialize, PartialEq, Eq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum PaypalOperationType {
Add,
Remove,
Replace,
Move,
Copy,
Test,
}
#[derive(Debug, Serialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum Value {
Amount(OrderRequestAmount),
Items(Vec<ItemDetails>),
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct ShippingName {
full_name: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct CardRequestStruct {
billing_address: Option<Address>,
expiry: Option<Secret<String>>,
name: Option<Secret<String>>,
number: Option<cards::CardNumber>,
security_code: Option<Secret<String>>,
attributes: Option<CardRequestAttributes>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct VaultStruct {
vault_id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum CardRequest {
CardRequestStruct(CardRequestStruct),
CardVaultStruct(VaultStruct),
}
#[derive(Debug, Serialize)]
pub struct CardRequestAttributes {
vault: Option<PaypalVault>,
verification: Option<ThreeDsMethod>,
}
#[derive(Debug, Serialize)]
pub struct ThreeDsMethod {
method: ThreeDsType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ThreeDsType {
ScaAlways,
}
#[derive(Debug, Serialize)]
pub struct RedirectRequest {
name: Secret<String>,
country_code: enums::CountryAlpha2,
experience_context: ContextStruct,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ContextStruct {
return_url: Option<String>,
cancel_url: Option<String>,
user_action: Option<UserAction>,
shipping_preference: ShippingPreference,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum UserAction {
#[serde(rename = "PAY_NOW")]
PayNow,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum ShippingPreference {
#[serde(rename = "SET_PROVIDED_ADDRESS")]
SetProvidedAddress,
#[serde(rename = "GET_FROM_FILE")]
GetFromFile,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaypalRedirectionRequest {
PaypalRedirectionStruct(PaypalRedirectionStruct),
PaypalVaultStruct(VaultStruct),
}
#[derive(Debug, Serialize)]
pub struct PaypalRedirectionStruct {
experience_context: ContextStruct,
attributes: Option<Attributes>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Attributes {
vault: PaypalVault,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PaypalRedirectionResponse {
attributes: Option<AttributeResponse>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct EpsRedirectionResponse {
name: Option<Secret<String>>,
country_code: Option<enums::CountryAlpha2>,
bic: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct IdealRedirectionResponse {
name: Option<Secret<String>>,
country_code: Option<enums::CountryAlpha2>,
bic: Option<Secret<String>>,
iban_last_chars: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AttributeResponse {
vault: PaypalVaultResponse,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PaypalVault {
store_in_vault: StoreInVault,
usage_type: UsageType,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PaypalVaultResponse {
id: String,
status: String,
customer: CustomerId,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CustomerId {
id: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum StoreInVault {
OnSuccess,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum UsageType {
Merchant,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum PaymentSourceItem {
Card(CardRequest),
Paypal(PaypalRedirectionRequest),
IDeal(RedirectRequest),
Eps(RedirectRequest),
Giropay(RedirectRequest),
Sofort(RedirectRequest),
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CardVaultResponse {
attributes: Option<AttributeResponse>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "lowercase")]
pub enum PaymentSourceItemResponse {
Card(CardVaultResponse),
Paypal(PaypalRedirectionResponse),
Eps(EpsRedirectionResponse),
Ideal(IdealRedirectionResponse),
}
#[derive(Debug, Serialize)]
pub struct PaypalPaymentsRequest {
intent: PaypalPaymentIntent,
purchase_units: Vec<PurchaseUnitRequest>,
payment_source: Option<PaymentSourceItem>,
}
#[derive(Debug, Serialize)]
pub struct PaypalZeroMandateRequest {
payment_source: ZeroMandateSourceItem,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ZeroMandateSourceItem {
Card(CardMandateRequest),
Paypal(PaypalMandateStruct),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaypalMandateStruct {
experience_context: Option<ContextStruct>,
usage_type: UsageType,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CardMandateRequest {
billing_address: Option<Address>,
expiry: Option<Secret<String>>,
name: Option<Secret<String>>,
number: Option<cards::CardNumber>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaypalSetupMandatesResponse {
id: String,
customer: Customer,
payment_source: ZeroMandateSourceItem,
links: Vec<PaypalLinks>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Customer {
id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PaypalSetupMandatesResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaypalSetupMandatesResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let info_response = item.response;
let mandate_reference = Some(MandateReference {
connector_mandate_id: Some(info_response.id.clone()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
// https://developer.paypal.com/docs/api/payment-tokens/v3/#payment-tokens_create
// If 201 status code, then order is captured, other status codes are handled by the error handler
let status = if item.http_code == 201 {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Failure
};
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(info_response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(info_response.id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<&SetupMandateRouterData> for PaypalZeroMandateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
let payment_source = match item.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => ZeroMandateSourceItem::Card(CardMandateRequest {
billing_address: get_address_info(item.get_optional_billing()),
expiry: Some(ccard.get_expiry_date_as_yyyymm("-")),
name: item.get_optional_billing_full_name(),
number: Some(ccard.card_number),
}),
PaymentMethodData::Wallet(_)
| 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::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::MobilePayment(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
))?,
};
Ok(Self { payment_source })
}
}
fn get_address_info(
payment_address: Option<&hyperswitch_domain_models::address::Address>,
) -> Option<Address> {
let address = payment_address.and_then(|payment_address| payment_address.address.as_ref());
match address {
Some(address) => address.get_optional_country().map(|country| Address {
country_code: country.to_owned(),
address_line_1: address.line1.clone(),
postal_code: address.zip.clone(),
admin_area_2: address.city.clone(),
}),
None => None,
}
}
fn get_payment_source(
item: &PaymentsAuthorizeRouterData,
bank_redirection_data: &BankRedirectData,
) -> Result<PaymentSourceItem, error_stack::Report<errors::ConnectorError>> {
match bank_redirection_data {
BankRedirectData::Eps { bank_name: _, .. } => Ok(PaymentSourceItem::Eps(RedirectRequest {
name: item.get_billing_full_name()?,
country_code: item.get_billing_country()?,
experience_context: ContextStruct {
return_url: item.request.complete_authorize_url.clone(),
cancel_url: item.request.complete_authorize_url.clone(),
shipping_preference: if item.get_optional_shipping_country().is_some() {
ShippingPreference::SetProvidedAddress
} else {
ShippingPreference::GetFromFile
},
user_action: Some(UserAction::PayNow),
},
})),
BankRedirectData::Giropay { .. } => Ok(PaymentSourceItem::Giropay(RedirectRequest {
name: item.get_billing_full_name()?,
country_code: item.get_billing_country()?,
experience_context: ContextStruct {
return_url: item.request.complete_authorize_url.clone(),
cancel_url: item.request.complete_authorize_url.clone(),
shipping_preference: if item.get_optional_shipping_country().is_some() {
ShippingPreference::SetProvidedAddress
} else {
ShippingPreference::GetFromFile
},
user_action: Some(UserAction::PayNow),
},
})),
BankRedirectData::Ideal { bank_name: _, .. } => {
Ok(PaymentSourceItem::IDeal(RedirectRequest {
name: item.get_billing_full_name()?,
country_code: item.get_billing_country()?,
experience_context: ContextStruct {
return_url: item.request.complete_authorize_url.clone(),
cancel_url: item.request.complete_authorize_url.clone(),
shipping_preference: if item.get_optional_shipping_country().is_some() {
ShippingPreference::SetProvidedAddress
} else {
ShippingPreference::GetFromFile
},
user_action: Some(UserAction::PayNow),
},
}))
}
BankRedirectData::Sofort {
preferred_language: _,
..
} => Ok(PaymentSourceItem::Sofort(RedirectRequest {
name: item.get_billing_full_name()?,
country_code: item.get_billing_country()?,
experience_context: ContextStruct {
return_url: item.request.complete_authorize_url.clone(),
cancel_url: item.request.complete_authorize_url.clone(),
shipping_preference: if item.get_optional_shipping_country().is_some() {
ShippingPreference::SetProvidedAddress
} else {
ShippingPreference::GetFromFile
},
user_action: Some(UserAction::PayNow),
},
})),
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::Przelewy24 { .. } => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
.into()),
BankRedirectData::Bizum {}
| BankRedirectData::Eft { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {} => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
))?,
}
}
fn get_payee(auth_type: &PaypalAuthType) -> Option<Payee> {
auth_type
.get_credentials()
.ok()
.and_then(|credentials| credentials.get_payer_id())
.map(|payer_id| Payee {
merchant_id: payer_id,
})
}
impl TryFrom<&PaypalRouterData<&PaymentsPostSessionTokensRouterData>> for PaypalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaypalRouterData<&PaymentsPostSessionTokensRouterData>,
) -> Result<Self, Self::Error> {
let intent = if item.router_data.request.is_auto_capture()? {
PaypalPaymentIntent::Capture
} else {
PaypalPaymentIntent::Authorize
};
let paypal_auth: PaypalAuthType =
PaypalAuthType::try_from(&item.router_data.connector_auth_type)?;
let payee = get_payee(&paypal_auth);
let amount = OrderRequestAmount::try_from(item)?;
let connector_request_reference_id =
item.router_data.connector_request_reference_id.clone();
let shipping_address = ShippingAddress::from(item);
let item_details = vec![ItemDetails::try_from(item)?];
let purchase_units = vec![PurchaseUnitRequest {
reference_id: Some(connector_request_reference_id.clone()),
custom_id: item.router_data.request.merchant_order_reference_id.clone(),
invoice_id: Some(connector_request_reference_id),
amount,
payee,
shipping: Some(shipping_address),
items: item_details,
}];
let payment_source = Some(PaymentSourceItem::Paypal(
PaypalRedirectionRequest::PaypalRedirectionStruct(PaypalRedirectionStruct {
experience_context: ContextStruct {
return_url: item.router_data.request.router_return_url.clone(),
cancel_url: item.router_data.request.router_return_url.clone(),
shipping_preference: ShippingPreference::GetFromFile,
user_action: Some(UserAction::PayNow),
},
attributes: match item.router_data.request.setup_future_usage {
Some(setup_future_usage) => match setup_future_usage {
enums::FutureUsage::OffSession => Some(Attributes {
vault: PaypalVault {
store_in_vault: StoreInVault::OnSuccess,
usage_type: UsageType::Merchant,
},
}),
enums::FutureUsage::OnSession => None,
},
None => None,
},
}),
));
Ok(Self {
intent,
purchase_units,
payment_source,
})
}
}
impl TryFrom<&PaypalRouterData<&SdkSessionUpdateRouterData>> for PaypalUpdateOrderRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaypalRouterData<&SdkSessionUpdateRouterData>) -> Result<Self, Self::Error> {
let op = PaypalOperationType::Replace;
// Create separate paths for amount and items
let reference_id = &item.router_data.connector_request_reference_id;
let amount_path = format!("/purchase_units/@reference_id=='{}'/amount", reference_id);
let items_path = format!("/purchase_units/@reference_id=='{}'/items", reference_id);
let amount_value = Value::Amount(OrderRequestAmount::try_from(item)?);
let items_value = Value::Items(vec![ItemDetails::try_from(item)?]);
Ok(Self(vec![
Operation {
op: op.clone(),
path: amount_path,
value: amount_value,
},
Operation {
op,
path: items_path,
value: items_value,
},
]))
}
}
impl TryFrom<&PaypalRouterData<&PaymentsAuthorizeRouterData>> for PaypalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaypalRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let paypal_auth: PaypalAuthType =
PaypalAuthType::try_from(&item.router_data.connector_auth_type)?;
let payee = get_payee(&paypal_auth);
let amount = OrderRequestAmount::from(item);
let intent = if item.router_data.request.is_auto_capture()? {
PaypalPaymentIntent::Capture
} else {
PaypalPaymentIntent::Authorize
};
let connector_request_reference_id =
item.router_data.connector_request_reference_id.clone();
let shipping_address = ShippingAddress::from(item);
let item_details = vec![ItemDetails::from(item)];
let purchase_units = vec![PurchaseUnitRequest {
reference_id: Some(connector_request_reference_id.clone()),
custom_id: item.router_data.request.merchant_order_reference_id.clone(),
invoice_id: Some(connector_request_reference_id),
amount,
payee,
shipping: Some(shipping_address),
items: item_details,
}];
match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => {
let card = item.router_data.request.get_card()?;
let expiry = Some(card.get_expiry_date_as_yyyymm("-"));
let verification = match item.router_data.auth_type {
enums::AuthenticationType::ThreeDs => Some(ThreeDsMethod {
method: ThreeDsType::ScaAlways,
}),
enums::AuthenticationType::NoThreeDs => None,
};
let payment_source = Some(PaymentSourceItem::Card(CardRequest::CardRequestStruct(
CardRequestStruct {
billing_address: get_address_info(item.router_data.get_optional_billing()),
expiry,
name: item.router_data.get_optional_billing_full_name(),
number: Some(ccard.card_number.clone()),
security_code: Some(ccard.card_cvc.clone()),
attributes: Some(CardRequestAttributes {
vault: match item.router_data.request.setup_future_usage {
Some(setup_future_usage) => match setup_future_usage {
enums::FutureUsage::OffSession => Some(PaypalVault {
store_in_vault: StoreInVault::OnSuccess,
usage_type: UsageType::Merchant,
}),
enums::FutureUsage::OnSession => None,
},
None => None,
},
verification,
}),
},
)));
Ok(Self {
intent,
purchase_units,
payment_source,
})
}
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletData::PaypalRedirect(_) => {
let payment_source = Some(PaymentSourceItem::Paypal(
PaypalRedirectionRequest::PaypalRedirectionStruct(
PaypalRedirectionStruct {
experience_context: ContextStruct {
return_url: item
.router_data
.request
.complete_authorize_url
.clone(),
cancel_url: item
.router_data
.request
.complete_authorize_url
.clone(),
shipping_preference: if item
.router_data
.get_optional_shipping()
.is_some()
{
ShippingPreference::SetProvidedAddress
} else {
ShippingPreference::GetFromFile
},
user_action: Some(UserAction::PayNow),
},
attributes: match item.router_data.request.setup_future_usage {
Some(setup_future_usage) => match setup_future_usage {
enums::FutureUsage::OffSession => Some(Attributes {
vault: PaypalVault {
store_in_vault: StoreInVault::OnSuccess,
usage_type: UsageType::Merchant,
},
}),
enums::FutureUsage::OnSession => None,
},
None => None,
},
},
),
));
Ok(Self {
intent,
purchase_units,
payment_source,
})
}
WalletData::PaypalSdk(_) => {
let payment_source = Some(PaymentSourceItem::Paypal(
PaypalRedirectionRequest::PaypalRedirectionStruct(
PaypalRedirectionStruct {
experience_context: ContextStruct {
return_url: None,
cancel_url: None,
shipping_preference: ShippingPreference::GetFromFile,
user_action: Some(UserAction::PayNow),
},
attributes: match item.router_data.request.setup_future_usage {
Some(setup_future_usage) => match setup_future_usage {
enums::FutureUsage::OffSession => Some(Attributes {
vault: PaypalVault {
store_in_vault: StoreInVault::OnSuccess,
usage_type: UsageType::Merchant,
},
}),
enums::FutureUsage::OnSession => None,
},
None => None,
},
},
),
));
Ok(Self {
intent,
purchase_units,
payment_source,
})
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| 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::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::Paze(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
))?,
},
PaymentMethodData::BankRedirect(ref bank_redirection_data) => {
let bank_redirect_intent = if item.router_data.request.is_auto_capture()? {
PaypalPaymentIntent::Capture
} else {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Manual capture method for Bank Redirect".to_string(),
connector: "Paypal".to_string(),
})?
};
let payment_source =
Some(get_payment_source(item.router_data, bank_redirection_data)?);
Ok(Self {
intent: bank_redirect_intent,
purchase_units,
payment_source,
})
}
PaymentMethodData::CardRedirect(ref card_redirect_data) => {
Self::try_from(card_redirect_data)
}
PaymentMethodData::PayLater(ref paylater_data) => Self::try_from(paylater_data),
PaymentMethodData::BankDebit(ref bank_debit_data) => Self::try_from(bank_debit_data),
PaymentMethodData::BankTransfer(ref bank_transfer_data) => {
Self::try_from(bank_transfer_data.as_ref())
}
PaymentMethodData::Voucher(ref voucher_data) => Self::try_from(voucher_data),
PaymentMethodData::GiftCard(ref giftcard_data) => {
Self::try_from(giftcard_data.as_ref())
}
PaymentMethodData::MandatePayment => {
let payment_method_type = item
.router_data
.get_recurring_mandate_payment_data()?
.payment_method_type
.ok_or_else(missing_field_err("payment_method_type"))?;
let connector_mandate_id = item.router_data.request.connector_mandate_id().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
},
)?;
let payment_source = match payment_method_type {
#[cfg(feature = "v1")]
enums::PaymentMethodType::Credit | enums::PaymentMethodType::Debit => Ok(Some(
PaymentSourceItem::Card(CardRequest::CardVaultStruct(VaultStruct {
vault_id: connector_mandate_id.into(),
})),
)),
#[cfg(feature = "v2")]
enums::PaymentMethodType::Credit
| enums::PaymentMethodType::Debit
| enums::PaymentMethodType::Card => Ok(Some(PaymentSourceItem::Card(
CardRequest::CardVaultStruct(VaultStruct {
vault_id: connector_mandate_id.into(),
}),
))),
enums::PaymentMethodType::Paypal => Ok(Some(PaymentSourceItem::Paypal(
PaypalRedirectionRequest::PaypalVaultStruct(VaultStruct {
vault_id: connector_mandate_id.into(),
}),
))),
enums::PaymentMethodType::Ach
| enums::PaymentMethodType::Affirm
| enums::PaymentMethodType::AfterpayClearpay
| enums::PaymentMethodType::Alfamart
| enums::PaymentMethodType::AliPay
| enums::PaymentMethodType::AliPayHk
| enums::PaymentMethodType::Alma
| enums::PaymentMethodType::AmazonPay
| enums::PaymentMethodType::ApplePay
| enums::PaymentMethodType::Atome
| enums::PaymentMethodType::Bacs
| enums::PaymentMethodType::BancontactCard
| enums::PaymentMethodType::Becs
| enums::PaymentMethodType::Benefit
| enums::PaymentMethodType::Bizum
| enums::PaymentMethodType::Blik
| enums::PaymentMethodType::Boleto
| enums::PaymentMethodType::BcaBankTransfer
| enums::PaymentMethodType::BniVa
| enums::PaymentMethodType::BriVa
| enums::PaymentMethodType::CardRedirect
| enums::PaymentMethodType::CimbVa
| enums::PaymentMethodType::ClassicReward
| enums::PaymentMethodType::CryptoCurrency
| enums::PaymentMethodType::Cashapp
| enums::PaymentMethodType::Dana
| enums::PaymentMethodType::DanamonVa
| enums::PaymentMethodType::DirectCarrierBilling
| enums::PaymentMethodType::DuitNow
| enums::PaymentMethodType::Efecty
| enums::PaymentMethodType::Eft
| enums::PaymentMethodType::Eps
| enums::PaymentMethodType::Fps
| enums::PaymentMethodType::Evoucher
| enums::PaymentMethodType::Giropay
| enums::PaymentMethodType::Givex
| enums::PaymentMethodType::GooglePay
| enums::PaymentMethodType::GoPay
| enums::PaymentMethodType::Gcash
| enums::PaymentMethodType::Ideal
| enums::PaymentMethodType::Interac
| enums::PaymentMethodType::Indomaret
| enums::PaymentMethodType::Klarna
| enums::PaymentMethodType::KakaoPay
| enums::PaymentMethodType::LocalBankRedirect
| enums::PaymentMethodType::MandiriVa
| enums::PaymentMethodType::Knet
| enums::PaymentMethodType::MbWay
| enums::PaymentMethodType::MobilePay
| enums::PaymentMethodType::Momo
| enums::PaymentMethodType::MomoAtm
| enums::PaymentMethodType::Multibanco
| enums::PaymentMethodType::OnlineBankingThailand
| enums::PaymentMethodType::OnlineBankingCzechRepublic
| enums::PaymentMethodType::OnlineBankingFinland
| enums::PaymentMethodType::OnlineBankingFpx
| enums::PaymentMethodType::OnlineBankingPoland
| enums::PaymentMethodType::OnlineBankingSlovakia
| enums::PaymentMethodType::OpenBankingPIS
| enums::PaymentMethodType::Oxxo
| enums::PaymentMethodType::PagoEfectivo
| enums::PaymentMethodType::PermataBankTransfer
| enums::PaymentMethodType::OpenBankingUk
| enums::PaymentMethodType::PayBright
| enums::PaymentMethodType::Pix
| enums::PaymentMethodType::PaySafeCard
| enums::PaymentMethodType::Przelewy24
| enums::PaymentMethodType::PromptPay
| enums::PaymentMethodType::Pse
| enums::PaymentMethodType::RedCompra
| enums::PaymentMethodType::RedPagos
| enums::PaymentMethodType::SamsungPay
| enums::PaymentMethodType::Sepa
| enums::PaymentMethodType::SepaBankTransfer
| enums::PaymentMethodType::Sofort
| enums::PaymentMethodType::Swish
| enums::PaymentMethodType::TouchNGo
| enums::PaymentMethodType::Trustly
| enums::PaymentMethodType::Twint
| enums::PaymentMethodType::UpiCollect
| enums::PaymentMethodType::UpiIntent
| enums::PaymentMethodType::Vipps
| enums::PaymentMethodType::VietQr
| enums::PaymentMethodType::Venmo
| enums::PaymentMethodType::Walley
| enums::PaymentMethodType::WeChatPay
| enums::PaymentMethodType::SevenEleven
| enums::PaymentMethodType::Lawson
| enums::PaymentMethodType::MiniStop
| enums::PaymentMethodType::FamilyMart
| enums::PaymentMethodType::Seicomart
| enums::PaymentMethodType::PayEasy
| enums::PaymentMethodType::LocalBankTransfer
| enums::PaymentMethodType::InstantBankTransfer
| enums::PaymentMethodType::Mifinity
| enums::PaymentMethodType::Paze => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("paypal"),
))
}
};
Ok(Self {
intent,
purchase_units,
payment_source: payment_source?,
})
}
PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
.into())
}
}
}
}
impl TryFrom<&CardRedirectData> for PaypalPaymentsRequest {
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("Paypal"),
)
.into()),
}
}
}
impl TryFrom<&PayLaterData> for PaypalPaymentsRequest {
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::AtomeRedirect {} => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
.into()),
}
}
}
impl TryFrom<&BankDebitData> for PaypalPaymentsRequest {
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 { .. } => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
.into()),
}
}
}
impl TryFrom<&BankTransferData> for PaypalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &BankTransferData) -> Result<Self, Self::Error> {
match value {
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::InstantBankTransfer {}
| BankTransferData::LocalBankTransfer { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
.into())
}
}
}
}
impl TryFrom<&VoucherData> for PaypalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &VoucherData) -> Result<Self, Self::Error> {
match value {
VoucherData::Boleto(_)
| VoucherData::Efecty
| VoucherData::PagoEfectivo
| VoucherData::RedCompra
| VoucherData::RedPagos
| VoucherData::Alfamart(_)
| VoucherData::Indomaret(_)
| VoucherData::Oxxo
| VoucherData::SevenEleven(_)
| VoucherData::Lawson(_)
| VoucherData::MiniStop(_)
| VoucherData::FamilyMart(_)
| VoucherData::Seicomart(_)
| VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
.into()),
}
}
}
impl TryFrom<&GiftCardData> for PaypalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &GiftCardData) -> Result<Self, Self::Error> {
match value {
GiftCardData::Givex(_) | GiftCardData::PaySafeCard {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
.into())
}
}
}
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct PaypalAuthUpdateRequest {
grant_type: String,
client_id: Secret<String>,
client_secret: Secret<String>,
}
impl TryFrom<&RefreshTokenRouterData> for PaypalAuthUpdateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
Ok(Self {
grant_type: "client_credentials".to_string(),
client_id: item.get_request_id()?,
client_secret: item.request.app_id.clone(),
})
}
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct PaypalAuthUpdateResponse {
pub access_token: Secret<String>,
pub token_type: String,
pub expires_in: i64,
}
impl<F, T> TryFrom<ResponseRouterData<F, PaypalAuthUpdateResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaypalAuthUpdateResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Debug)]
pub enum PaypalAuthType {
TemporaryAuth,
AuthWithDetails(PaypalConnectorCredentials),
}
#[derive(Debug)]
pub enum PaypalConnectorCredentials {
StandardIntegration(StandardFlowCredentials),
PartnerIntegration(PartnerFlowCredentials),
}
impl PaypalConnectorCredentials {
pub fn get_client_id(&self) -> Secret<String> {
match self {
Self::StandardIntegration(item) => item.client_id.clone(),
Self::PartnerIntegration(item) => item.client_id.clone(),
}
}
pub fn get_client_secret(&self) -> Secret<String> {
match self {
Self::StandardIntegration(item) => item.client_secret.clone(),
Self::PartnerIntegration(item) => item.client_secret.clone(),
}
}
pub fn get_payer_id(&self) -> Option<Secret<String>> {
match self {
Self::StandardIntegration(_) => None,
Self::PartnerIntegration(item) => Some(item.payer_id.clone()),
}
}
pub fn generate_authorization_value(&self) -> String {
let auth_id = format!(
"{}:{}",
self.get_client_id().expose(),
self.get_client_secret().expose(),
);
format!("Basic {}", consts::BASE64_ENGINE.encode(auth_id))
}
}
#[derive(Debug)]
pub struct StandardFlowCredentials {
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
}
#[derive(Debug)]
pub struct PartnerFlowCredentials {
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
pub(super) payer_id: Secret<String>,
}
impl PaypalAuthType {
pub fn get_credentials(
&self,
) -> CustomResult<&PaypalConnectorCredentials, errors::ConnectorError> {
match self {
Self::TemporaryAuth => Err(errors::ConnectorError::InvalidConnectorConfig {
config: "TemporaryAuth found in connector_account_details",
}
.into()),
Self::AuthWithDetails(credentials) => Ok(credentials),
}
}
}
impl TryFrom<&ConnectorAuthType> for PaypalAuthType {
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::AuthWithDetails(
PaypalConnectorCredentials::StandardIntegration(StandardFlowCredentials {
client_id: key1.to_owned(),
client_secret: api_key.to_owned(),
}),
)),
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self::AuthWithDetails(
PaypalConnectorCredentials::PartnerIntegration(PartnerFlowCredentials {
client_id: key1.to_owned(),
client_secret: api_key.to_owned(),
payer_id: api_secret.to_owned(),
}),
)),
ConnectorAuthType::TemporaryAuth => Ok(Self::TemporaryAuth),
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaypalOrderStatus {
Pending,
Completed,
Voided,
Created,
Saved,
PayerActionRequired,
Approved,
}
pub(crate) fn get_order_status(
item: PaypalOrderStatus,
intent: PaypalPaymentIntent,
) -> storage_enums::AttemptStatus {
match item {
PaypalOrderStatus::Completed => {
if intent == PaypalPaymentIntent::Authorize {
storage_enums::AttemptStatus::Authorized
} else {
storage_enums::AttemptStatus::Charged
}
}
PaypalOrderStatus::Voided => storage_enums::AttemptStatus::Voided,
PaypalOrderStatus::Created | PaypalOrderStatus::Saved | PaypalOrderStatus::Pending => {
storage_enums::AttemptStatus::Pending
}
PaypalOrderStatus::Approved => storage_enums::AttemptStatus::AuthenticationSuccessful,
PaypalOrderStatus::PayerActionRequired => {
storage_enums::AttemptStatus::AuthenticationPending
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentsCollectionItem {
amount: OrderAmount,
expiration_time: Option<String>,
id: String,
final_capture: Option<bool>,
status: PaypalPaymentStatus,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PaymentsCollection {
authorizations: Option<Vec<PaymentsCollectionItem>>,
captures: Option<Vec<PaymentsCollectionItem>>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PurchaseUnitItem {
pub reference_id: Option<String>,
pub invoice_id: Option<String>,
pub payments: PaymentsCollection,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaypalThreeDsResponse {
id: String,
status: PaypalOrderStatus,
links: Vec<PaypalLinks>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PaypalPreProcessingResponse {
PaypalLiabilityResponse(PaypalLiabilityResponse),
PaypalNonLiabilityResponse(PaypalNonLiabilityResponse),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaypalLiabilityResponse {
pub payment_source: CardParams,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaypalNonLiabilityResponse {
payment_source: CardsData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CardParams {
pub card: AuthResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthResult {
pub authentication_result: PaypalThreeDsParams,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaypalThreeDsParams {
pub liability_shift: LiabilityShift,
pub three_d_secure: ThreeDsCheck,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreeDsCheck {
pub enrollment_status: Option<EnrollmentStatus>,
pub authentication_status: Option<AuthenticationStatus>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum LiabilityShift {
Possible,
No,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EnrollmentStatus {
Null,
#[serde(rename = "Y")]
Ready,
#[serde(rename = "N")]
NotReady,
#[serde(rename = "U")]
Unavailable,
#[serde(rename = "B")]
Bypassed,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AuthenticationStatus {
Null,
#[serde(rename = "Y")]
Success,
#[serde(rename = "N")]
Failed,
#[serde(rename = "R")]
Rejected,
#[serde(rename = "A")]
Attempted,
#[serde(rename = "U")]
Unable,
#[serde(rename = "C")]
ChallengeRequired,
#[serde(rename = "I")]
InfoOnly,
#[serde(rename = "D")]
Decoupled,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaypalOrdersResponse {
id: String,
intent: PaypalPaymentIntent,
status: PaypalOrderStatus,
purchase_units: Vec<PurchaseUnitItem>,
payment_source: Option<PaymentSourceItemResponse>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaypalLinks {
href: Option<Url>,
rel: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RedirectPurchaseUnitItem {
pub invoice_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaypalRedirectResponse {
id: String,
intent: PaypalPaymentIntent,
status: PaypalOrderStatus,
purchase_units: Vec<RedirectPurchaseUnitItem>,
links: Vec<PaypalLinks>,
payment_source: Option<PaymentSourceItemResponse>,
}
// Note: Don't change order of deserialization of variant, priority is in descending order
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum PaypalAuthResponse {
PaypalOrdersResponse(PaypalOrdersResponse),
PaypalRedirectResponse(PaypalRedirectResponse),
PaypalThreeDsResponse(PaypalThreeDsResponse),
}
// Note: Don't change order of deserialization of variant, priority is in descending order
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum PaypalSyncResponse {
PaypalOrdersSyncResponse(PaypalOrdersResponse),
PaypalThreeDsSyncResponse(PaypalThreeDsSyncResponse),
PaypalRedirectSyncResponse(PaypalRedirectResponse),
PaypalPaymentsSyncResponse(PaypalPaymentsSyncResponse),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaypalPaymentsSyncResponse {
id: String,
status: PaypalPaymentStatus,
amount: OrderAmount,
invoice_id: Option<String>,
supplementary_data: PaypalSupplementaryData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaypalThreeDsSyncResponse {
id: String,
status: PaypalOrderStatus,
// provided to separated response of card's 3DS from other
payment_source: CardsData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CardsData {
card: CardDetails,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CardDetails {
last_digits: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaypalMeta {
pub authorize_id: Option<String>,
pub capture_id: Option<String>,
pub psync_flow: PaypalPaymentIntent,
pub next_action: Option<api_models::payments::NextActionCall>,
pub order_id: Option<String>,
}
fn get_id_based_on_intent(
intent: &PaypalPaymentIntent,
purchase_unit: &PurchaseUnitItem,
) -> CustomResult<String, errors::ConnectorError> {
|| -> _ {
match intent {
PaypalPaymentIntent::Capture => Some(
purchase_unit
.payments
.captures
.clone()?
.into_iter()
.next()?
.id,
),
PaypalPaymentIntent::Authorize => Some(
purchase_unit
.payments
.authorizations
.clone()?
.into_iter()
.next()?
.id,
),
PaypalPaymentIntent::Authenticate => None,
}
}()
.ok_or_else(|| errors::ConnectorError::MissingConnectorTransactionID.into())
}
impl<F, T> TryFrom<ResponseRouterData<F, PaypalOrdersResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaypalOrdersResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let purchase_units = item
.response
.purchase_units
.first()
.ok_or(errors::ConnectorError::MissingConnectorTransactionID)?;
let id = get_id_based_on_intent(&item.response.intent, purchase_units)?;
let (connector_meta, order_id) = match item.response.intent.clone() {
PaypalPaymentIntent::Capture => (
serde_json::json!(PaypalMeta {
authorize_id: None,
capture_id: Some(id),
psync_flow: item.response.intent.clone(),
next_action: None,
order_id: None,
}),
ResponseId::ConnectorTransactionId(item.response.id.clone()),
),
PaypalPaymentIntent::Authorize => (
serde_json::json!(PaypalMeta {
authorize_id: Some(id),
capture_id: None,
psync_flow: item.response.intent.clone(),
next_action: None,
order_id: None,
}),
ResponseId::ConnectorTransactionId(item.response.id.clone()),
),
PaypalPaymentIntent::Authenticate => {
Err(errors::ConnectorError::ResponseDeserializationFailed)?
}
};
//payment collection will always have only one element as we only make one transaction per order.
let payment_collection = &item
.response
.purchase_units
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?
.payments;
//payment collection item will either have "authorizations" field or "capture" field, not both at a time.
let payment_collection_item = match (
&payment_collection.authorizations,
&payment_collection.captures,
) {
(Some(authorizations), None) => authorizations.first(),
(None, Some(captures)) => captures.first(),
(Some(_), Some(captures)) => captures.first(),
_ => None,
}
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let status = payment_collection_item.status.clone();
let status = storage_enums::AttemptStatus::from(status);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: order_id,
redirection_data: Box::new(None),
mandate_reference: Box::new(Some(MandateReference {
connector_mandate_id: match item.response.payment_source.clone() {
Some(paypal_source) => match paypal_source {
PaymentSourceItemResponse::Paypal(paypal_source) => {
paypal_source.attributes.map(|attr| attr.vault.id)
}
PaymentSourceItemResponse::Card(card) => {
card.attributes.map(|attr| attr.vault.id)
}
PaymentSourceItemResponse::Eps(_)
| PaymentSourceItemResponse::Ideal(_) => None,
},
None => None,
},
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})),
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: purchase_units
.invoice_id
.clone()
.or(Some(item.response.id)),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
fn get_redirect_url(
link_vec: Vec<PaypalLinks>,
) -> CustomResult<Option<Url>, errors::ConnectorError> {
let mut link: Option<Url> = None;
for item2 in link_vec.iter() {
if item2.rel == "payer-action" {
link.clone_from(&item2.href)
}
}
Ok(link)
}
impl<F>
ForeignTryFrom<(
ResponseRouterData<F, PaypalSyncResponse, PaymentsSyncData, PaymentsResponseData>,
Option<common_enums::PaymentExperience>,
)> for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, payment_experience): (
ResponseRouterData<F, PaypalSyncResponse, PaymentsSyncData, PaymentsResponseData>,
Option<common_enums::PaymentExperience>,
),
) -> Result<Self, Self::Error> {
match item.response {
PaypalSyncResponse::PaypalOrdersSyncResponse(response) => {
Self::try_from(ResponseRouterData {
response,
data: item.data,
http_code: item.http_code,
})
}
PaypalSyncResponse::PaypalRedirectSyncResponse(response) => Self::foreign_try_from((
ResponseRouterData {
response,
data: item.data,
http_code: item.http_code,
},
payment_experience,
)),
PaypalSyncResponse::PaypalPaymentsSyncResponse(response) => {
Self::try_from(ResponseRouterData {
response,
data: item.data,
http_code: item.http_code,
})
}
PaypalSyncResponse::PaypalThreeDsSyncResponse(response) => {
Self::try_from(ResponseRouterData {
response,
data: item.data,
http_code: item.http_code,
})
}
}
}
}
impl<F, T>
ForeignTryFrom<(
ResponseRouterData<F, PaypalRedirectResponse, T, PaymentsResponseData>,
Option<common_enums::PaymentExperience>,
)> for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, payment_experience): (
ResponseRouterData<F, PaypalRedirectResponse, T, PaymentsResponseData>,
Option<common_enums::PaymentExperience>,
),
) -> Result<Self, Self::Error> {
let status = get_order_status(item.response.clone().status, item.response.intent.clone());
let link = get_redirect_url(item.response.links.clone())?;
// For Paypal SDK flow, we need to trigger SDK client and then complete authorize
let next_action =
if let Some(common_enums::PaymentExperience::InvokeSdkClient) = payment_experience {
Some(api_models::payments::NextActionCall::CompleteAuthorize)
} else {
None
};
let connector_meta = serde_json::json!(PaypalMeta {
authorize_id: None,
capture_id: None,
psync_flow: item.response.intent,
next_action,
order_id: None,
});
let purchase_units = item.response.purchase_units.first();
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(Some(RedirectForm::from((
link.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?,
Method::Get,
)))),
mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: Some(
purchase_units.map_or(item.response.id, |item| item.invoice_id.clone()),
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl
TryFrom<
ResponseRouterData<
Authorize,
PaypalRedirectResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for PaymentsAuthorizeRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
Authorize,
PaypalRedirectResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = get_order_status(item.response.clone().status, item.response.intent.clone());
let link = get_redirect_url(item.response.links.clone())?;
let connector_meta = serde_json::json!(PaypalMeta {
authorize_id: None,
capture_id: None,
psync_flow: item.response.intent,
next_action: None,
order_id: None,
});
let purchase_units = item.response.purchase_units.first();
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(Some(RedirectForm::from((
link.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?,
Method::Get,
)))),
mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: Some(
purchase_units.map_or(item.response.id, |item| item.invoice_id.clone()),
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl
TryFrom<
ResponseRouterData<
PostSessionTokens,
PaypalRedirectResponse,
PaymentsPostSessionTokensData,
PaymentsResponseData,
>,
> for PaymentsPostSessionTokensRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
PostSessionTokens,
PaypalRedirectResponse,
PaymentsPostSessionTokensData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = get_order_status(item.response.clone().status, item.response.intent.clone());
// For Paypal SDK flow, we need to trigger SDK client and then Confirm
let next_action = Some(api_models::payments::NextActionCall::Confirm);
let connector_meta = serde_json::json!(PaypalMeta {
authorize_id: None,
capture_id: None,
psync_flow: item.response.intent,
next_action,
order_id: Some(item.response.id.clone()),
});
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<F>
TryFrom<
ResponseRouterData<F, PaypalThreeDsSyncResponse, PaymentsSyncData, PaymentsResponseData>,
> for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
PaypalThreeDsSyncResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
// status is hardcoded because this try_from will only be reached in card 3ds before the completion of complete authorize flow.
// also force sync won't be hit in terminal status thus leaving us with only one status to get here.
status: storage_enums::AttemptStatus::AuthenticationPending,
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<F>
TryFrom<
ResponseRouterData<F, PaypalThreeDsResponse, PaymentsAuthorizeData, PaymentsResponseData>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
PaypalThreeDsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let connector_meta = serde_json::json!(PaypalMeta {
authorize_id: None,
capture_id: None,
psync_flow: PaypalPaymentIntent::Authenticate, // when there is no capture or auth id present
next_action: None,
order_id: None,
});
let status = get_order_status(
item.response.clone().status,
PaypalPaymentIntent::Authenticate,
);
let link = get_redirect_url(item.response.links.clone())?;
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(Some(paypal_threeds_link((
link,
item.data.request.complete_authorize_url.clone(),
))?)),
mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
fn paypal_threeds_link(
(redirect_url, complete_auth_url): (Option<Url>, Option<String>),
) -> CustomResult<RedirectForm, errors::ConnectorError> {
let mut redirect_url =
redirect_url.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let complete_auth_url =
complete_auth_url.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "complete_authorize_url",
})?;
let mut form_fields = std::collections::HashMap::from_iter(
redirect_url
.query_pairs()
.map(|(key, value)| (key.to_string(), value.to_string())),
);
// paypal requires return url to be passed as a field along with payer_action_url
form_fields.insert(String::from("redirect_uri"), 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,
})
}
impl<F, T> TryFrom<ResponseRouterData<F, PaypalPaymentsSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaypalPaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: storage_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response
.supplementary_data
.related_ids
.order_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
.invoice_id
.clone()
.or(Some(item.response.supplementary_data.related_ids.order_id)),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
pub struct PaypalFulfillRequest {
sender_batch_header: PayoutBatchHeader,
items: Vec<PaypalPayoutItem>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
pub struct PayoutBatchHeader {
sender_batch_id: String,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
pub struct PaypalPayoutItem {
amount: PayoutAmount,
note: Option<String>,
notification_language: String,
#[serde(flatten)]
payout_method_data: PaypalPayoutMethodData,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
pub struct PaypalPayoutMethodData {
recipient_type: PayoutRecipientType,
recipient_wallet: PayoutWalletType,
receiver: PaypalPayoutDataType,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayoutRecipientType {
Email,
PaypalId,
Phone,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayoutWalletType {
Paypal,
Venmo,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaypalPayoutDataType {
EmailType(Email),
OtherType(Secret<String>),
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
pub struct PayoutAmount {
value: StringMajorUnit,
currency: storage_enums::Currency,
}
#[cfg(feature = "payouts")]
impl TryFrom<&PaypalRouterData<&PayoutsRouterData<PoFulfill>>> for PaypalFulfillRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaypalRouterData<&PayoutsRouterData<PoFulfill>>,
) -> Result<Self, Self::Error> {
let item_data = PaypalPayoutItem::try_from(item)?;
Ok(Self {
sender_batch_header: PayoutBatchHeader {
sender_batch_id: item.router_data.request.payout_id.to_owned(),
},
items: vec![item_data],
})
}
}
#[cfg(feature = "payouts")]
impl TryFrom<&PaypalRouterData<&PayoutsRouterData<PoFulfill>>> for PaypalPayoutItem {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaypalRouterData<&PayoutsRouterData<PoFulfill>>,
) -> Result<Self, Self::Error> {
let amount = PayoutAmount {
value: item.amount.clone(),
currency: item.router_data.request.destination_currency,
};
let payout_method_data = match item.router_data.get_payout_method_data()? {
PayoutMethodData::Wallet(wallet_data) => match wallet_data {
WalletPayout::Paypal(data) => {
let (recipient_type, receiver) =
match (data.email, data.telephone_number, data.paypal_id) {
(Some(email), _, _) => (
PayoutRecipientType::Email,
PaypalPayoutDataType::EmailType(email),
),
(_, Some(phone), _) => (
PayoutRecipientType::Phone,
PaypalPayoutDataType::OtherType(phone),
),
(_, _, Some(paypal_id)) => (
PayoutRecipientType::PaypalId,
PaypalPayoutDataType::OtherType(paypal_id),
),
_ => Err(errors::ConnectorError::MissingRequiredField {
field_name: "receiver_data",
})?,
};
PaypalPayoutMethodData {
recipient_type,
recipient_wallet: PayoutWalletType::Paypal,
receiver,
}
}
WalletPayout::Venmo(data) => {
let receiver = PaypalPayoutDataType::OtherType(data.telephone_number.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "telephone_number",
},
)?);
PaypalPayoutMethodData {
recipient_type: PayoutRecipientType::Phone,
recipient_wallet: PayoutWalletType::Venmo,
receiver,
}
}
},
_ => Err(errors::ConnectorError::NotSupported {
message: "PayoutMethodType is not supported".to_string(),
connector: "Paypal",
})?,
};
Ok(Self {
amount,
payout_method_data,
note: item.router_data.description.to_owned(),
notification_language: constants::DEFAULT_NOTIFICATION_SCRIPT_LANGUAGE.to_string(),
})
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
pub struct PaypalFulfillResponse {
batch_header: PaypalBatchResponse,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
pub struct PaypalBatchResponse {
payout_batch_id: String,
batch_status: PaypalFulfillStatus,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaypalFulfillStatus {
Denied,
Pending,
Processing,
Success,
Cancelled,
}
#[cfg(feature = "payouts")]
pub(crate) fn get_payout_status(status: PaypalFulfillStatus) -> storage_enums::PayoutStatus {
match status {
PaypalFulfillStatus::Success => storage_enums::PayoutStatus::Success,
PaypalFulfillStatus::Denied => storage_enums::PayoutStatus::Failed,
PaypalFulfillStatus::Cancelled => storage_enums::PayoutStatus::Cancelled,
PaypalFulfillStatus::Pending | PaypalFulfillStatus::Processing => {
storage_enums::PayoutStatus::Pending
}
}
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, PaypalFulfillResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, PaypalFulfillResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(get_payout_status(item.response.batch_header.batch_status)),
connector_payout_id: Some(item.response.batch_header.payout_batch_id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct PaypalPaymentsCaptureRequest {
amount: OrderAmount,
final_capture: bool,
}
impl TryFrom<&PaypalRouterData<&PaymentsCaptureRouterData>> for PaypalPaymentsCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaypalRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let amount = OrderAmount {
currency_code: item.router_data.request.currency,
value: item.amount.clone(),
};
Ok(Self {
amount,
final_capture: true,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaypalPaymentStatus {
Created,
Captured,
Completed,
Declined,
Voided,
Failed,
Pending,
Denied,
Expired,
PartiallyCaptured,
Refunded,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaypalCaptureResponse {
id: String,
status: PaypalPaymentStatus,
amount: Option<OrderAmount>,
invoice_id: Option<String>,
final_capture: bool,
payment_source: Option<PaymentSourceItemResponse>,
}
impl From<PaypalPaymentStatus> for storage_enums::AttemptStatus {
fn from(item: PaypalPaymentStatus) -> Self {
match item {
PaypalPaymentStatus::Created => Self::Authorized,
PaypalPaymentStatus::Completed
| PaypalPaymentStatus::Captured
| PaypalPaymentStatus::Refunded => Self::Charged,
PaypalPaymentStatus::Declined => Self::Failure,
PaypalPaymentStatus::Failed => Self::CaptureFailed,
PaypalPaymentStatus::Pending => Self::Pending,
PaypalPaymentStatus::Denied | PaypalPaymentStatus::Expired => Self::Failure,
PaypalPaymentStatus::PartiallyCaptured => Self::PartialCharged,
PaypalPaymentStatus::Voided => Self::Voided,
}
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<PaypalCaptureResponse>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<PaypalCaptureResponse>,
) -> Result<Self, Self::Error> {
let status = storage_enums::AttemptStatus::from(item.response.status);
let amount_captured = match status {
storage_enums::AttemptStatus::Pending
| storage_enums::AttemptStatus::Authorized
| storage_enums::AttemptStatus::Failure
| storage_enums::AttemptStatus::RouterDeclined
| storage_enums::AttemptStatus::AuthenticationFailed
| storage_enums::AttemptStatus::CaptureFailed
| storage_enums::AttemptStatus::Started
| storage_enums::AttemptStatus::AuthenticationPending
| storage_enums::AttemptStatus::AuthenticationSuccessful
| storage_enums::AttemptStatus::AuthorizationFailed
| storage_enums::AttemptStatus::Authorizing
| storage_enums::AttemptStatus::VoidInitiated
| storage_enums::AttemptStatus::CodInitiated
| storage_enums::AttemptStatus::CaptureInitiated
| storage_enums::AttemptStatus::VoidFailed
| storage_enums::AttemptStatus::AutoRefunded
| storage_enums::AttemptStatus::Unresolved
| storage_enums::AttemptStatus::PaymentMethodAwaited
| storage_enums::AttemptStatus::ConfirmationAwaited
| storage_enums::AttemptStatus::DeviceDataCollectionPending
| storage_enums::AttemptStatus::Voided => 0,
storage_enums::AttemptStatus::Charged
| storage_enums::AttemptStatus::PartialCharged
| storage_enums::AttemptStatus::PartialChargedAndChargeable => {
item.data.request.amount_to_capture
}
};
let connector_payment_id: PaypalMeta =
to_connector_meta(item.data.request.connector_meta.clone())?;
Ok(Self {
status,
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: Some(serde_json::json!(PaypalMeta {
authorize_id: connector_payment_id.authorize_id,
capture_id: Some(item.response.id.clone()),
psync_flow: PaypalPaymentIntent::Capture,
next_action: None,
order_id: None,
})),
network_txn_id: None,
connector_response_reference_id: item
.response
.invoice_id
.or(Some(item.response.id)),
incremental_authorization_allowed: None,
charges: None,
}),
amount_captured: Some(amount_captured),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaypalCancelStatus {
Voided,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct PaypalPaymentsCancelResponse {
id: String,
status: PaypalCancelStatus,
amount: Option<OrderAmount>,
invoice_id: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, PaypalPaymentsCancelResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaypalPaymentsCancelResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = match item.response.status {
PaypalCancelStatus::Voided => storage_enums::AttemptStatus::Voided,
};
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
.response
.invoice_id
.or(Some(item.response.id)),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct PaypalRefundRequest {
pub amount: OrderAmount,
}
impl<F> TryFrom<&PaypalRouterData<&RefundsRouterData<F>>> for PaypalRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaypalRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: OrderAmount {
currency_code: item.router_data.request.currency,
value: item.amount.clone(),
},
})
}
}
#[allow(dead_code)]
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Completed,
Failed,
Cancelled,
Pending,
}
impl From<RefundStatus> for storage_enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Completed => Self::Success,
RefundStatus::Failed | RefundStatus::Cancelled => Self::Failure,
RefundStatus::Pending => Self::Pending,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
amount: Option<OrderAmount>,
}
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: storage_enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RefundSyncResponse {
id: String,
status: RefundStatus,
}
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> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status: storage_enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct OrderErrorDetails {
pub issue: String,
pub description: String,
pub value: Option<String>,
pub field: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct PaypalOrderErrorResponse {
pub name: Option<String>,
pub message: String,
pub debug_id: Option<String>,
pub details: Option<Vec<OrderErrorDetails>>,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct ErrorDetails {
pub issue: String,
pub description: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct PaypalPaymentErrorResponse {
pub name: Option<String>,
pub message: String,
pub debug_id: Option<String>,
pub details: Option<Vec<ErrorDetails>>,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct PaypalAccessTokenErrorResponse {
pub error: String,
pub error_description: String,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct PaypalWebhooksBody {
pub event_type: PaypalWebhookEventType,
pub resource: PaypalResource,
}
#[derive(Clone, Deserialize, Debug, strum::Display, Serialize)]
pub enum PaypalWebhookEventType {
#[serde(rename = "PAYMENT.AUTHORIZATION.CREATED")]
PaymentAuthorizationCreated,
#[serde(rename = "PAYMENT.AUTHORIZATION.VOIDED")]
PaymentAuthorizationVoided,
#[serde(rename = "PAYMENT.CAPTURE.DECLINED")]
PaymentCaptureDeclined,
#[serde(rename = "PAYMENT.CAPTURE.COMPLETED")]
PaymentCaptureCompleted,
#[serde(rename = "PAYMENT.CAPTURE.PENDING")]
PaymentCapturePending,
#[serde(rename = "PAYMENT.CAPTURE.REFUNDED")]
PaymentCaptureRefunded,
#[serde(rename = "CHECKOUT.ORDER.APPROVED")]
CheckoutOrderApproved,
#[serde(rename = "CHECKOUT.ORDER.COMPLETED")]
CheckoutOrderCompleted,
#[serde(rename = "CHECKOUT.ORDER.PROCESSED")]
CheckoutOrderProcessed,
#[serde(rename = "CUSTOMER.DISPUTE.CREATED")]
CustomerDisputeCreated,
#[serde(rename = "CUSTOMER.DISPUTE.RESOLVED")]
CustomerDisputeResolved,
#[serde(rename = "CUSTOMER.DISPUTE.UPDATED")]
CustomerDisputedUpdated,
#[serde(rename = "RISK.DISPUTE.CREATED")]
RiskDisputeCreated,
#[serde(other)]
Unknown,
}
#[derive(Deserialize, Debug, Serialize)]
#[serde(untagged)]
pub enum PaypalResource {
PaypalCardWebhooks(Box<PaypalCardWebhooks>),
PaypalRedirectsWebhooks(Box<PaypalRedirectsWebhooks>),
PaypalRefundWebhooks(Box<PaypalRefundWebhooks>),
PaypalDisputeWebhooks(Box<PaypalDisputeWebhooks>),
}
#[derive(Deserialize, Debug, Serialize)]
pub struct PaypalDisputeWebhooks {
pub dispute_id: String,
pub disputed_transactions: Vec<DisputeTransaction>,
pub dispute_amount: OrderAmount,
pub dispute_outcome: Option<DisputeOutcome>,
pub dispute_life_cycle_stage: DisputeLifeCycleStage,
pub status: DisputeStatus,
pub reason: Option<String>,
pub external_reason_code: Option<String>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub seller_response_due_date: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub update_time: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub create_time: Option<PrimitiveDateTime>,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct DisputeTransaction {
pub seller_transaction_id: String,
}
#[derive(Clone, Deserialize, Debug, strum::Display, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DisputeLifeCycleStage {
Inquiry,
Chargeback,
PreArbitration,
Arbitration,
}
#[derive(Deserialize, Debug, strum::Display, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DisputeStatus {
Open,
WaitingForBuyerResponse,
WaitingForSellerResponse,
UnderReview,
Resolved,
Other,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct DisputeOutcome {
pub outcome_code: OutcomeCode,
}
#[derive(Deserialize, Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum OutcomeCode {
ResolvedBuyerFavour,
ResolvedSellerFavour,
ResolvedWithPayout,
CanceledByBuyer,
ACCEPTED,
DENIED,
NONE,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct PaypalRefundWebhooks {
pub id: String,
pub amount: OrderAmount,
pub seller_payable_breakdown: PaypalSellerPayableBreakdown,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct PaypalSellerPayableBreakdown {
pub total_refunded_amount: OrderAmount,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct PaypalCardWebhooks {
pub supplementary_data: PaypalSupplementaryData,
pub amount: OrderAmount,
pub invoice_id: Option<String>,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct PaypalRedirectsWebhooks {
pub purchase_units: Vec<PurchaseUnitItem>,
pub links: Vec<PaypalLinks>,
pub id: String,
pub intent: PaypalPaymentIntent,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct PaypalWebhooksPurchaseUnits {
pub reference_id: String,
pub amount: OrderAmount,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct PaypalSupplementaryData {
pub related_ids: PaypalRelatedIds,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct PaypalRelatedIds {
pub order_id: String,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct PaypalWebooksEventType {
pub event_type: PaypalWebhookEventType,
}
pub(crate) fn get_payapl_webhooks_event(
event: PaypalWebhookEventType,
outcome: Option<OutcomeCode>,
) -> IncomingWebhookEvent {
match event {
PaypalWebhookEventType::PaymentCaptureCompleted
| PaypalWebhookEventType::CheckoutOrderCompleted => {
IncomingWebhookEvent::PaymentIntentSuccess
}
PaypalWebhookEventType::PaymentCapturePending
| PaypalWebhookEventType::CheckoutOrderProcessed => {
IncomingWebhookEvent::PaymentIntentProcessing
}
PaypalWebhookEventType::PaymentCaptureDeclined => {
IncomingWebhookEvent::PaymentIntentFailure
}
PaypalWebhookEventType::PaymentCaptureRefunded => IncomingWebhookEvent::RefundSuccess,
PaypalWebhookEventType::CustomerDisputeCreated => IncomingWebhookEvent::DisputeOpened,
PaypalWebhookEventType::RiskDisputeCreated => IncomingWebhookEvent::DisputeAccepted,
PaypalWebhookEventType::CustomerDisputeResolved => {
if let Some(outcome_code) = outcome {
IncomingWebhookEvent::from(outcome_code)
} else {
IncomingWebhookEvent::EventNotSupported
}
}
PaypalWebhookEventType::PaymentAuthorizationCreated
| PaypalWebhookEventType::PaymentAuthorizationVoided
| PaypalWebhookEventType::CheckoutOrderApproved
| PaypalWebhookEventType::CustomerDisputedUpdated
| PaypalWebhookEventType::Unknown => IncomingWebhookEvent::EventNotSupported,
}
}
impl From<OutcomeCode> for IncomingWebhookEvent {
fn from(outcome_code: OutcomeCode) -> Self {
match outcome_code {
OutcomeCode::ResolvedBuyerFavour => Self::DisputeLost,
OutcomeCode::ResolvedSellerFavour => Self::DisputeWon,
OutcomeCode::CanceledByBuyer => Self::DisputeCancelled,
OutcomeCode::ACCEPTED => Self::DisputeAccepted,
OutcomeCode::DENIED => Self::DisputeCancelled,
OutcomeCode::NONE => Self::DisputeCancelled,
OutcomeCode::ResolvedWithPayout => Self::EventNotSupported,
}
}
}
impl From<DisputeLifeCycleStage> for enums::DisputeStage {
fn from(dispute_life_cycle_stage: DisputeLifeCycleStage) -> Self {
match dispute_life_cycle_stage {
DisputeLifeCycleStage::Inquiry => Self::PreDispute,
DisputeLifeCycleStage::Chargeback => Self::Dispute,
DisputeLifeCycleStage::PreArbitration => Self::PreArbitration,
DisputeLifeCycleStage::Arbitration => Self::PreArbitration,
}
}
}
#[derive(Deserialize, Serialize, Debug)]
pub struct PaypalSourceVerificationRequest {
pub transmission_id: String,
pub transmission_time: String,
pub cert_url: String,
pub transmission_sig: String,
pub auth_algo: String,
pub webhook_id: String,
pub webhook_event: serde_json::Value,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct PaypalSourceVerificationResponse {
pub verification_status: PaypalSourceVerificationStatus,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaypalSourceVerificationStatus {
Success,
Failure,
}
impl
TryFrom<
ResponseRouterData<
VerifyWebhookSource,
PaypalSourceVerificationResponse,
VerifyWebhookSourceRequestData,
VerifyWebhookSourceResponseData,
>,
> for VerifyWebhookSourceRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
VerifyWebhookSource,
PaypalSourceVerificationResponse,
VerifyWebhookSourceRequestData,
VerifyWebhookSourceResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(VerifyWebhookSourceResponseData {
verify_webhook_status: VerifyWebhookStatus::from(item.response.verification_status),
}),
..item.data
})
}
}
impl From<PaypalSourceVerificationStatus> for VerifyWebhookStatus {
fn from(item: PaypalSourceVerificationStatus) -> Self {
match item {
PaypalSourceVerificationStatus::Success => Self::SourceVerified,
PaypalSourceVerificationStatus::Failure => Self::SourceNotVerified,
}
}
}
impl TryFrom<(PaypalCardWebhooks, PaypalWebhookEventType)> for PaypalPaymentsSyncResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(webhook_body, webhook_event): (PaypalCardWebhooks, PaypalWebhookEventType),
) -> Result<Self, Self::Error> {
Ok(Self {
id: webhook_body.supplementary_data.related_ids.order_id.clone(),
status: PaypalPaymentStatus::try_from(webhook_event)?,
amount: webhook_body.amount,
supplementary_data: webhook_body.supplementary_data,
invoice_id: webhook_body.invoice_id,
})
}
}
impl TryFrom<(PaypalRedirectsWebhooks, PaypalWebhookEventType)> for PaypalOrdersResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(webhook_body, webhook_event): (PaypalRedirectsWebhooks, PaypalWebhookEventType),
) -> Result<Self, Self::Error> {
Ok(Self {
id: webhook_body.id,
intent: webhook_body.intent,
status: PaypalOrderStatus::try_from(webhook_event)?,
purchase_units: webhook_body.purchase_units,
payment_source: None,
})
}
}
impl TryFrom<(PaypalRefundWebhooks, PaypalWebhookEventType)> for RefundSyncResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(webhook_body, webhook_event): (PaypalRefundWebhooks, PaypalWebhookEventType),
) -> Result<Self, Self::Error> {
Ok(Self {
id: webhook_body.id,
status: RefundStatus::try_from(webhook_event)
.attach_printable("Could not find suitable webhook event")?,
})
}
}
impl TryFrom<PaypalWebhookEventType> for PaypalPaymentStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(event: PaypalWebhookEventType) -> Result<Self, Self::Error> {
match event {
PaypalWebhookEventType::PaymentCaptureCompleted
| PaypalWebhookEventType::CheckoutOrderCompleted => Ok(Self::Completed),
PaypalWebhookEventType::PaymentAuthorizationVoided => Ok(Self::Voided),
PaypalWebhookEventType::PaymentCaptureDeclined => Ok(Self::Declined),
PaypalWebhookEventType::PaymentCapturePending
| PaypalWebhookEventType::CheckoutOrderApproved
| PaypalWebhookEventType::CheckoutOrderProcessed => Ok(Self::Pending),
PaypalWebhookEventType::PaymentAuthorizationCreated => Ok(Self::Created),
PaypalWebhookEventType::PaymentCaptureRefunded => Ok(Self::Refunded),
PaypalWebhookEventType::CustomerDisputeCreated
| PaypalWebhookEventType::CustomerDisputeResolved
| PaypalWebhookEventType::CustomerDisputedUpdated
| PaypalWebhookEventType::RiskDisputeCreated
| PaypalWebhookEventType::Unknown => {
Err(errors::ConnectorError::WebhookEventTypeNotFound.into())
}
}
}
}
impl TryFrom<PaypalWebhookEventType> for RefundStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(event: PaypalWebhookEventType) -> Result<Self, Self::Error> {
match event {
PaypalWebhookEventType::PaymentCaptureRefunded => Ok(Self::Completed),
PaypalWebhookEventType::PaymentAuthorizationCreated
| PaypalWebhookEventType::PaymentAuthorizationVoided
| PaypalWebhookEventType::PaymentCaptureDeclined
| PaypalWebhookEventType::PaymentCaptureCompleted
| PaypalWebhookEventType::PaymentCapturePending
| PaypalWebhookEventType::CheckoutOrderApproved
| PaypalWebhookEventType::CheckoutOrderCompleted
| PaypalWebhookEventType::CheckoutOrderProcessed
| PaypalWebhookEventType::CustomerDisputeCreated
| PaypalWebhookEventType::CustomerDisputeResolved
| PaypalWebhookEventType::CustomerDisputedUpdated
| PaypalWebhookEventType::RiskDisputeCreated
| PaypalWebhookEventType::Unknown => {
Err(errors::ConnectorError::WebhookEventTypeNotFound.into())
}
}
}
}
impl TryFrom<PaypalWebhookEventType> for PaypalOrderStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(event: PaypalWebhookEventType) -> Result<Self, Self::Error> {
match event {
PaypalWebhookEventType::PaymentCaptureCompleted
| PaypalWebhookEventType::CheckoutOrderCompleted => Ok(Self::Completed),
PaypalWebhookEventType::PaymentAuthorizationVoided => Ok(Self::Voided),
PaypalWebhookEventType::PaymentCapturePending
| PaypalWebhookEventType::CheckoutOrderProcessed => Ok(Self::Pending),
PaypalWebhookEventType::PaymentAuthorizationCreated => Ok(Self::Created),
PaypalWebhookEventType::CheckoutOrderApproved
| PaypalWebhookEventType::PaymentCaptureDeclined
| PaypalWebhookEventType::PaymentCaptureRefunded
| PaypalWebhookEventType::CustomerDisputeCreated
| PaypalWebhookEventType::CustomerDisputeResolved
| PaypalWebhookEventType::CustomerDisputedUpdated
| PaypalWebhookEventType::RiskDisputeCreated
| PaypalWebhookEventType::Unknown => {
Err(errors::ConnectorError::WebhookEventTypeNotFound.into())
}
}
}
}
impl TryFrom<&VerifyWebhookSourceRequestData> for PaypalSourceVerificationRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(req: &VerifyWebhookSourceRequestData) -> Result<Self, Self::Error> {
let req_body = serde_json::from_slice(&req.webhook_body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Self {
transmission_id: get_headers(
&req.webhook_headers,
webhook_headers::PAYPAL_TRANSMISSION_ID,
)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?,
transmission_time: get_headers(
&req.webhook_headers,
webhook_headers::PAYPAL_TRANSMISSION_TIME,
)?,
cert_url: get_headers(&req.webhook_headers, webhook_headers::PAYPAL_CERT_URL)?,
transmission_sig: get_headers(
&req.webhook_headers,
webhook_headers::PAYPAL_TRANSMISSION_SIG,
)?,
auth_algo: get_headers(&req.webhook_headers, webhook_headers::PAYPAL_AUTH_ALGO)?,
webhook_id: String::from_utf8(req.merchant_secret.secret.to_vec())
.change_context(errors::ConnectorError::WebhookVerificationSecretNotFound)
.attach_printable("Could not convert secret to UTF-8")?,
webhook_event: req_body,
})
}
}
fn get_headers(
header: &actix_web::http::header::HeaderMap,
key: &'static str,
) -> CustomResult<String, errors::ConnectorError> {
let header_value = header
.get(key)
.map(|value| value.to_str())
.ok_or(errors::ConnectorError::MissingRequiredField { field_name: key })?
.change_context(errors::ConnectorError::InvalidDataFormat { field_name: key })?
.to_owned();
Ok(header_value)
}
impl From<OrderErrorDetails> for utils::ErrorCodeAndMessage {
fn from(error: OrderErrorDetails) -> Self {
Self {
error_code: error.issue.to_string(),
error_message: error.issue.to_string(),
}
}
}
impl From<ErrorDetails> for utils::ErrorCodeAndMessage {
fn from(error: ErrorDetails) -> Self {
Self {
error_code: error.issue.to_string(),
error_message: error.issue.to_string(),
}
}
}
| 23,676 | 2,217 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/zen/transformers.rs | .rs | 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::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::ApplePay(_)
| WalletData::GooglePay(_)
| WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| 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(_) => 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::AtomeRedirect {} => 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 { .. } => 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(_) => {
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,
})
} 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,
})
} 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,
}
| 9,401 | 2,218 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/noon/transformers.rs | .rs | 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::from(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::AmazonPayRedirect(_)
| 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(_) => 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,
}),
_ => {
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,
})
} 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,
})
} 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,
}
| 6,910 | 2,219 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/aci/transformers.rs | .rs | 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::{
payment_method_data::{BankRedirectData, Card, PayLaterData, PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, RouterData},
router_request_types::ResponseId,
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{PaymentsAuthorizeRouterData, PaymentsCancelRouterData, 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, PhoneDetailsData, RouterData as _},
};
type Error = error_stack::Report<errors::ConnectorError>;
#[derive(Debug, Serialize)]
pub struct AciRouterData<T> {
amount: StringMajorUnit,
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)]
#[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>,
}
#[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, Clone, Serialize)]
#[serde(untagged)]
pub enum PaymentDetails {
#[serde(rename = "card")]
AciCard(Box<CardDetails>),
BankRedirect(Box<BankRedirectionPMData>),
Wallet(Box<WalletPMData>),
Klarna,
Mandate,
}
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::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect { .. }
| WalletData::GooglePay(_)
| 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(_) => 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)
}
}
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> {
Ok(Self::AciCard(Box::new(CardDetails {
card_number: card_data.card_number,
card_holder: card_holder_name.unwrap_or(Secret::new("".to_string())),
card_expiry_month: card_data.card_exp_month,
card_expiry_year: card_data.card_exp_year,
card_cvv: card_data.card_cvc,
})))
}
}
#[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, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentBrand {
Eps,
Eft,
Ideal,
Giropay,
Sofortueberweisung,
InteracOnline,
Przelewy,
Trustly,
Mbway,
#[serde(rename = "ALIPAY")]
AliPay,
}
#[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>,
}
#[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::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::NetworkToken(_)
| 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(),
})
}
}
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(),
})
}
}
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(),
})
}
}
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);
Ok(Self {
txn_details,
payment_method,
instruction,
shopper_result_url: 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)?;
Ok(Self {
txn_details,
payment_method: PaymentDetails::Mandate,
instruction,
shopper_result_url: item.router_data.request.router_return_url.clone(),
})
}
}
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)?;
Ok(TransactionDetails {
entity_id: auth.entity_id,
amount: item.amount.to_owned(),
currency: item.router_data.request.currency.to_string(),
payment_type: AciPaymentType::Debit,
})
}
fn get_instruction_details(
item: &AciRouterData<&PaymentsAuthorizeRouterData>,
) -> Option<Instruction> {
if item.router_data.request.setup_mandate_details.is_some() {
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
}
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)
}
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AciPaymentStatus {
Succeeded,
Failed,
#[default]
Pending,
RedirectShopper,
}
impl From<AciPaymentStatus> for enums::AttemptStatus {
fn from(item: AciPaymentStatus) -> Self {
match item {
AciPaymentStatus::Succeeded => Self::Charged,
AciPaymentStatus::Failed => Self::Failure,
AciPaymentStatus::Pending => Self::Authorizing,
AciPaymentStatus::RedirectShopper => Self::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 is an internal unique identifier for the request.
ndc: String,
timestamp: String,
// Number useful for support purposes.
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 {
method: Option<Method>,
parameters: Vec<Parameters>,
url: Url,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
pub struct Parameters {
name: String,
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, T> TryFrom<ResponseRouterData<F, AciPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AciPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirection_data = item.response.redirect.map(|data| {
let form_fields = std::collections::HashMap::<_, _>::from_iter(
data.parameters
.iter()
.map(|parameter| (parameter.name.clone(), parameter.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.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: {
if redirection_data.is_some() {
enums::AttemptStatus::from(AciPaymentStatus::RedirectShopper)
} else {
enums::AttemptStatus::from(AciPaymentStatus::from_str(
&item.response.result.code,
)?)
}
},
response: 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,
}),
..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 is an internal unique identifier for the request.
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> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status: enums::RefundStatus::from(AciRefundStatus::from_str(
&item.response.result.code,
)?),
}),
..item.data
})
}
}
| 6,548 | 2,220 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/aci/aci_result_codes.rs | .rs | pub(super) const FAILURE_CODES: [&str; 501] = [
"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",
];
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",
];
| 7,656 | 2,221 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/placetopay/transformers.rs | .rs | 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,
})
}
}
| 3,905 | 2,222 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs | .rs | use common_enums::enums::{self, AttemptStatus};
use common_utils::{
errors::{CustomResult, ParsingError},
ext_traits::ByteSliceExt,
request::Method,
types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},
router_flow_types::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{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 time::PrimitiveDateTime;
use url::Url;
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
ResponseRouterData, SubmitEvidenceRouterData, UploadFileRouterData,
},
unimplemented_payment_method,
utils::{
self, ApplePayDecrypt, PaymentsCaptureRequestData, 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::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::WeChatPayQr(_)
| WalletData::Mifinity(_) => 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
})
}
}
#[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: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct WalletSource {
#[serde(rename = "type")]
pub source_type: CheckoutSourceTypes,
pub token: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymentSource {
Card(CardSource),
Wallets(WalletSource),
ApplePayPredecrypt(Box<ApplePayPredecrypt>),
}
#[derive(Debug, Serialize)]
pub struct ApplePayPredecrypt {
token: Secret<String>,
#[serde(rename = "type")]
decrypt_type: String,
token_type: String,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
eci: Option<String>,
cryptogram: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CheckoutSourceTypes {
Card,
Token,
}
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>,
}
#[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>>,
}
#[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, Serialize)]
pub struct CheckoutThreeDS {
enabled: bool,
force_3ds: bool,
eci: Option<String>,
cryptogram: Option<String>,
xid: Option<String>,
version: Option<String>,
}
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())
}
}
}
impl TryFrom<&CheckoutRouterData<&PaymentsAuthorizeRouterData>> for PaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CheckoutRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let source_var = match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => {
let a = 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: ccard.card_cvc,
});
Ok(a)
}
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::GooglePay(_) => Ok(PaymentSource::Wallets(WalletSource {
source_type: CheckoutSourceTypes::Token,
token: match item.router_data.get_payment_method_token()? {
PaymentMethodToken::Token(token) => token,
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Checkout"),
)?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Checkout"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Checkout"))?
}
},
})),
WalletData::ApplePay(_) => {
let payment_method_token = item.router_data.get_payment_method_token()?;
match payment_method_token {
PaymentMethodToken::Token(apple_pay_payment_token) => {
Ok(PaymentSource::Wallets(WalletSource {
source_type: CheckoutSourceTypes::Token,
token: apple_pay_payment_token,
}))
}
PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
let exp_month = decrypt_data.get_expiry_month()?;
let expiry_year_4_digit = decrypt_data.get_four_digit_expiry_year()?;
Ok(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,
},
)))
}
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Checkout"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Checkout"))?
}
}
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::WeChatPayQr(_)
| WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)),
},
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"),
))
}
}?;
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())
}),
},
enums::AuthenticationType::NoThreeDs => CheckoutThreeDS {
enabled: false,
force_3ds: false,
eci: None,
cryptogram: None,
xid: None,
version: None,
},
};
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 capture = matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
);
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);
Ok(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,
})
}
}
#[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::Pending
} 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,
}
}
fn get_attempt_status_intent(
item: (CheckoutPaymentStatus, CheckoutPaymentIntent),
) -> AttemptStatus {
let (status, psync_flow) = item;
match status {
CheckoutPaymentStatus::Authorized => {
if psync_flow == CheckoutPaymentIntent::Capture {
AttemptStatus::Pending
} 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,
}
}
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 PaymentsResponse {
id: String,
amount: Option<MinorUnit>,
currency: Option<String>,
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>,
}
#[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 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 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,
})
} else {
None
};
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: None,
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,
})
} else {
None
};
let payments_response_data = 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.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<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,
}
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: None,
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>,
}
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: None,
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,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckoutDisputeWebhookData {
pub id: String,
pub payment_id: Option<String>,
pub action_id: Option<String>,
pub amount: i32,
pub currency: enums::Currency,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub evidence_required_by: Option<PrimitiveDateTime>,
pub reason_code: Option<String>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub date: Option<PrimitiveDateTime>,
}
#[derive(Debug, Deserialize)]
pub struct CheckoutDisputeWebhookBody {
#[serde(rename = "type")]
pub transaction_type: CheckoutDisputeTransactionType,
pub data: CheckoutDisputeWebhookData,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub created_on: Option<PrimitiveDateTime>,
}
#[derive(Debug, Deserialize, strum::Display, Clone)]
#[serde(rename_all = "snake_case")]
pub enum CheckoutDisputeTransactionType {
DisputeReceived,
DisputeExpired,
DisputeAccepted,
DisputeCanceled,
DisputeEvidenceSubmitted,
DisputeEvidenceAcknowledgedByScheme,
DisputeEvidenceRequired,
DisputeArbitrationLost,
DisputeArbitrationWon,
DisputeWon,
DisputeLost,
}
impl From<CheckoutWebhookEventType> for api_models::webhooks::IncomingWebhookEvent {
fn from(transaction_type: CheckoutWebhookEventType) -> Self {
match transaction_type {
CheckoutWebhookEventType::AuthenticationStarted
| CheckoutWebhookEventType::AuthenticationApproved
| CheckoutWebhookEventType::AuthenticationAttempted => Self::EventNotSupported,
CheckoutWebhookEventType::AuthenticationExpired
| CheckoutWebhookEventType::AuthenticationFailed
| CheckoutWebhookEventType::PaymentAuthenticationFailed => {
Self::PaymentIntentAuthorizationFailure
}
CheckoutWebhookEventType::PaymentApproved => Self::EventNotSupported,
CheckoutWebhookEventType::PaymentCaptured => Self::PaymentIntentSuccess,
CheckoutWebhookEventType::PaymentDeclined => Self::PaymentIntentFailure,
CheckoutWebhookEventType::PaymentRefunded => Self::RefundSuccess,
CheckoutWebhookEventType::PaymentRefundDeclined => Self::RefundFailure,
CheckoutWebhookEventType::PaymentCanceled => Self::PaymentIntentCancelFailure,
CheckoutWebhookEventType::PaymentCaptureDeclined => Self::PaymentIntentCaptureFailure,
CheckoutWebhookEventType::PaymentVoided => Self::PaymentIntentCancelled,
CheckoutWebhookEventType::DisputeReceived
| CheckoutWebhookEventType::DisputeEvidenceRequired => Self::DisputeOpened,
CheckoutWebhookEventType::DisputeExpired => Self::DisputeExpired,
CheckoutWebhookEventType::DisputeAccepted => Self::DisputeAccepted,
CheckoutWebhookEventType::DisputeCanceled => Self::DisputeCancelled,
CheckoutWebhookEventType::DisputeEvidenceSubmitted
| CheckoutWebhookEventType::DisputeEvidenceAcknowledgedByScheme => {
Self::DisputeChallenged
}
CheckoutWebhookEventType::DisputeWon
| CheckoutWebhookEventType::DisputeArbitrationWon => Self::DisputeWon,
CheckoutWebhookEventType::DisputeLost
| CheckoutWebhookEventType::DisputeArbitrationLost => Self::DisputeLost,
CheckoutWebhookEventType::Unknown => Self::EventNotSupported,
}
}
}
impl From<CheckoutDisputeTransactionType> for api_models::enums::DisputeStage {
fn from(code: CheckoutDisputeTransactionType) -> Self {
match code {
CheckoutDisputeTransactionType::DisputeArbitrationLost
| CheckoutDisputeTransactionType::DisputeArbitrationWon => Self::PreArbitration,
CheckoutDisputeTransactionType::DisputeReceived
| CheckoutDisputeTransactionType::DisputeExpired
| CheckoutDisputeTransactionType::DisputeAccepted
| CheckoutDisputeTransactionType::DisputeCanceled
| CheckoutDisputeTransactionType::DisputeEvidenceSubmitted
| CheckoutDisputeTransactionType::DisputeEvidenceAcknowledgedByScheme
| CheckoutDisputeTransactionType::DisputeEvidenceRequired
| CheckoutDisputeTransactionType::DisputeWon
| CheckoutDisputeTransactionType::DisputeLost => Self::Dispute,
}
}
}
#[derive(Debug, Deserialize)]
pub struct CheckoutWebhookObjectResource {
pub data: serde_json::Value,
}
pub fn construct_file_upload_request(
file_upload_router_data: UploadFileRouterData,
) -> CustomResult<reqwest::multipart::Form, errors::ConnectorError> {
let request = file_upload_router_data.request;
let mut multipart = reqwest::multipart::Form::new();
multipart = multipart.text("purpose", "dispute_evidence");
let file_data = reqwest::multipart::Part::bytes(request.file)
.file_name(format!(
"{}.{}",
request.file_key,
request
.file_type
.as_ref()
.split('/')
.next_back()
.unwrap_or_default()
))
.mime_str(request.file_type.as_ref())
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failure in constructing file data")?;
multipart = multipart.part("file", file_data);
Ok(multipart)
}
#[derive(Debug, Deserialize, Serialize)]
pub struct FileUploadResponse {
#[serde(rename = "id")]
pub file_id: String,
}
#[derive(Default, Debug, Serialize)]
pub struct Evidence {
pub proof_of_delivery_or_service_file: Option<String>,
pub invoice_or_receipt_file: Option<String>,
pub invoice_showing_distinct_transactions_file: Option<String>,
pub customer_communication_file: Option<String>,
pub refund_or_cancellation_policy_file: Option<String>,
pub recurring_transaction_agreement_file: Option<String>,
pub additional_evidence_file: Option<String>,
}
impl TryFrom<&webhooks::IncomingWebhookRequestDetails<'_>> for PaymentsResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> Result<Self, Self::Error> {
let details: CheckoutWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let data = details.data;
let psync_struct = Self {
id: data.payment_id.unwrap_or(data.id),
amount: Some(data.amount),
status: CheckoutPaymentStatus::try_from(details.transaction_type)?,
links: details.links,
balances: data.balances,
reference: data.reference,
response_code: data.response_code,
response_summary: data.response_summary,
action_id: data.action_id,
currency: Some(data.currency),
processed_on: data.processed_on,
approved: data.approved,
};
Ok(psync_struct)
}
}
impl TryFrom<&webhooks::IncomingWebhookRequestDetails<'_>> for RefundResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> Result<Self, Self::Error> {
let details: CheckoutWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let data = details.data;
let refund_struct = Self {
action_id: data
.action_id
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?,
reference: data
.reference
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?,
};
Ok(refund_struct)
}
}
impl TryFrom<&SubmitEvidenceRouterData> for Evidence {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SubmitEvidenceRouterData) -> Result<Self, Self::Error> {
let submit_evidence_request_data = item.request.clone();
Ok(Self {
proof_of_delivery_or_service_file: submit_evidence_request_data
.shipping_documentation_provider_file_id,
invoice_or_receipt_file: submit_evidence_request_data.receipt_provider_file_id,
invoice_showing_distinct_transactions_file: submit_evidence_request_data
.invoice_showing_distinct_transactions_provider_file_id,
customer_communication_file: submit_evidence_request_data
.customer_communication_provider_file_id,
refund_or_cancellation_policy_file: submit_evidence_request_data
.refund_policy_provider_file_id,
recurring_transaction_agreement_file: submit_evidence_request_data
.recurring_transaction_agreement_provider_file_id,
additional_evidence_file: submit_evidence_request_data
.uncategorized_file_provider_file_id,
})
}
}
impl From<String> for utils::ErrorCodeAndMessage {
fn from(error: String) -> Self {
Self {
error_code: error.clone(),
error_message: error,
}
}
}
| 11,192 | 2,223 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs | .rs | use common_enums::enums;
use common_utils::types::MinorUnit;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::{
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[
{}
]]>
</dts:trnXML>
</dts:SubmitSinglePayment>
</soapenv:Body>
</soapenv:Envelope>
"#,
transaction_data
);
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,
}),
..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,
}),
..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,
}),
..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,
}),
..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>,
}
| 7,073 | 2,224 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs | .rs | 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 => 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 }
}
| 4,330 | 2,225 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/juspaythreedsserver/transformers.rs | .rs | use common_enums::enums;
use common_utils::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, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::PaymentsAuthorizeRequestData,
};
//TODO: Fill the struct with respective fields
pub struct JuspaythreedsserverRouterData<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 JuspaythreedsserverRouterData<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 JuspaythreedsserverPaymentsRequest {
amount: StringMinorUnit,
card: JuspaythreedsserverCard,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct JuspaythreedsserverCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&JuspaythreedsserverRouterData<&PaymentsAuthorizeRouterData>>
for JuspaythreedsserverPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &JuspaythreedsserverRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = JuspaythreedsserverCard {
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 JuspaythreedsserverAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for JuspaythreedsserverAuthType {
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 JuspaythreedsserverPaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<JuspaythreedsserverPaymentStatus> for common_enums::AttemptStatus {
fn from(item: JuspaythreedsserverPaymentStatus) -> Self {
match item {
JuspaythreedsserverPaymentStatus::Succeeded => Self::Charged,
JuspaythreedsserverPaymentStatus::Failed => Self::Failure,
JuspaythreedsserverPaymentStatus::Processing => Self::Authorizing,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct JuspaythreedsserverPaymentsResponse {
status: JuspaythreedsserverPaymentStatus,
id: String,
}
impl<F, T>
TryFrom<ResponseRouterData<F, JuspaythreedsserverPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, JuspaythreedsserverPaymentsResponse, 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 JuspaythreedsserverRefundRequest {
pub amount: StringMinorUnit,
}
impl<F> TryFrom<&JuspaythreedsserverRouterData<&RefundsRouterData<F>>>
for JuspaythreedsserverRefundRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &JuspaythreedsserverRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct JuspaythreedsserverErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
}
| 1,802 | 2,226 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/opayo/transformers.rs | .rs | use common_enums::enums;
use common_utils::types::MinorUnit;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, 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 OpayoRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for OpayoRouterData<T> {
fn from((amount, router_data): (MinorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct OpayoPaymentsRequest {
amount: MinorUnit,
card: OpayoCard,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct OpayoCard {
name: Secret<String>,
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&OpayoRouterData<&PaymentsAuthorizeRouterData>> for OpayoPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item_data: &OpayoRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let item = item_data.router_data.clone();
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = OpayoCard {
name: item
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string())),
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.request.is_auto_capture()?,
};
Ok(Self {
amount: item_data.amount,
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(
crate::utils::get_unimplemented_payment_method_error_message("Opayo"),
)
.into())
}
}
}
}
// Auth Struct
pub struct OpayoAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for OpayoAuthType {
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 OpayoPaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<OpayoPaymentStatus> for enums::AttemptStatus {
fn from(item: OpayoPaymentStatus) -> Self {
match item {
OpayoPaymentStatus::Succeeded => Self::Charged,
OpayoPaymentStatus::Failed => Self::Failure,
OpayoPaymentStatus::Processing => Self::Authorizing,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OpayoPaymentsResponse {
status: OpayoPaymentStatus,
id: String,
transaction_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, OpayoPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, OpayoPaymentsResponse, 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.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
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct OpayoRefundRequest {
pub amount: MinorUnit,
}
impl<F> TryFrom<&OpayoRouterData<&RefundsRouterData<F>>> for OpayoRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &OpayoRouterData<&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
}
}
}
#[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 OpayoErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
}
| 1,790 | 2,227 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs | .rs | 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,
}
| 2,197 | 2,228 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs | .rs | use std::collections::HashMap;
use cards::CardNumber;
use common_enums::enums;
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: common_enums::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: common_enums::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: enums::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>,
pub cvv: 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)]
#[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>,
}
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, 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: 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,
})
} 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, XenditPaymentResponse, PaymentsCaptureData, PaymentsResponseData>>
for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
XenditPaymentResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = map_payment_response_to_attempt_status(item.response.clone(), true);
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,
})
} 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(enums::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,
})
} 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(enums::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 {
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,
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)]
#[serde(rename_all = "camelCase")]
pub struct XenditWebhookEvent {
pub event: XenditEventType,
pub data: EventDetails,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct EventDetails {
pub id: String,
pub payment_request_id: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
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,
}
| 5,760 | 2,229 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs | .rs | use common_enums::enums;
use common_utils::{pii::Email, request::Method};
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::{api::CurrencyUnit, 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: i64,
pub router_data: T,
}
impl<T> TryFrom<(&CurrencyUnit, enums::Currency, i64, T)> for DlocalRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(_currency_unit, _currency, amount, router_data): (&CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data,
})
}
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct DlocalPaymentsRequest {
pub amount: i64,
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())
}
| 4,452 | 2,230 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs | .rs | #[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,
}
#[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,
}
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)
}
}
#[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)?;
Ok(Self {
amount: item.data.object.amount,
currency: item.data.object.currency,
merchant_reference_id,
})
}
}
#[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,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct StripePaymentMethodDetails {
#[serde(rename = "type")]
pub type_of_payment_method: StripebillingPaymentMethod,
#[serde(rename = "card")]
pub card_funding_type: StripeCardFundingTypeDetails,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum StripebillingPaymentMethod {
Card,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct StripeCardFundingTypeDetails {
pub funding: StripebillingFundingTypes,
}
#[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 merchant_reference_id = id_type::PaymentReferenceId::from_str(
&item.response.invoice_id,
)
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "invoice_id",
})?;
let connector_transaction_id = Some(common_utils::types::ConnectorTransactionId::from(
item.response.charge_id,
));
Ok(Self {
response: Ok(
recovery_response_types::BillingConnectorPaymentsSyncResponse {
status: item.response.status.into(),
amount: item.response.amount,
currency: item.response.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: item.response.failure_code,
error_message: item.response.failure_message,
processor_payment_method_token: item.response.payment_method,
connector_customer_id: item.response.customer,
transaction_created_at: Some(item.response.created),
payment_method_sub_type: common_enums::PaymentMethodType::from(
item.response
.payment_method_details
.card_funding_type
.funding,
),
payment_method_type: common_enums::PaymentMethod::from(
item.response.payment_method_details.type_of_payment_method,
),
},
),
..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::RecoveryRecordBack,
StripebillingRecordBackResponse,
recovery_request_types::RevenueRecoveryRecordBackRequest,
recovery_response_types::RevenueRecoveryRecordBackResponse,
>,
> for recovery_router_data_types::RevenueRecoveryRecordBackRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
recovery_router_flows::RecoveryRecordBack,
StripebillingRecordBackResponse,
recovery_request_types::RevenueRecoveryRecordBackRequest,
recovery_response_types::RevenueRecoveryRecordBackResponse,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(recovery_response_types::RevenueRecoveryRecordBackResponse {
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
})
}
}
| 4,033 | 2,231 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs | .rs | use api_models::webhooks::IncomingWebhookEvent;
use base64::Engine;
use cards::CardNumber;
use common_enums::{enums, AttemptStatus, CaptureMethod, CountryAlpha2};
use common_utils::{
consts::BASE64_ENGINE,
errors::CustomResult,
pii::{Email, IpAddress},
types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, 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,
},
}
}
| 8,674 | 2,232 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/globalpay/response.rs | .rs | use common_enums::Currency;
use common_utils::types::StringMinorUnit;
use masking::Secret;
use serde::{Deserialize, Serialize};
use super::requests;
#[derive(Debug, Serialize, Deserialize)]
pub struct GlobalpayPaymentsResponse {
/// A unique identifier for the merchant account set by Global Payments.
pub account_id: Option<Secret<String>>,
/// A meaningful label for the merchant account set by Global Payments.
pub account_name: Option<Secret<String>>,
/// Information about the Action executed.
pub action: Option<Action>,
/// The amount to transfer between Payer and Merchant for a SALE or a REFUND. It is always
/// represented in the lowest denomiation of the related currency.
pub amount: Option<StringMinorUnit>,
/// Indicates if the merchant would accept an authorization for an amount less than the
/// requested amount. This is available for CP channel
/// only where the balance not authorized can be processed again using a different card.
pub authorization_mode: Option<requests::AuthorizationMode>,
/// A Global Payments created reference that uniquely identifies the batch.
pub batch_id: Option<String>,
/// Indicates whether the transaction is to be captured automatically, later or later using
/// more than 1 partial capture.
pub capture_mode: Option<requests::CaptureMode>,
/// Describes whether the transaction was processed in a face to face(CP) scenario or a
/// Customer Not Present (CNP) scenario.
pub channel: Option<requests::Channel>,
/// The country in ISO-3166-1(alpha-2 code) format.
pub country: Option<String>,
/// The currency of the amount in ISO-4217(alpha-3)
pub currency: Option<Currency>,
/// Information relating to a currency conversion.
pub currency_conversion: Option<requests::CurrencyConversion>,
/// A unique identifier generated by Global Payments to identify the transaction.
pub id: String,
/// A unique identifier for the merchant set by Global Payments.
pub merchant_id: Option<String>,
/// A meaningful label for the merchant set by Global Payments.
pub merchant_name: Option<Secret<String>>,
pub payment_method: Option<PaymentMethod>,
/// Merchant defined field to reference the transaction.
pub reference: Option<String>,
/// Indicates where a transaction is in its lifecycle.
pub status: GlobalpayPaymentStatus,
/// Global Payments time indicating when the object was created in ISO-8601 format.
pub time_created: Option<String>,
/// Describes whether the transaction is a SALE, that moves funds from Payer to Merchant, or
/// a REFUND where funds move from Merchant to Payer.
#[serde(rename = "type")]
pub globalpay_payments_response_type: Option<requests::GlobalpayPaymentsRequestType>,
}
/// Information about the Action executed.
#[derive(Debug, Serialize, Deserialize)]
pub struct Action {
/// The id of the app that was used to create the token.
pub app_id: Option<Secret<String>>,
/// The name of the app the user gave to the application.
pub app_name: Option<Secret<String>>,
/// A unique identifier for the object created by Global Payments. The first 3 characters
/// identifies the resource an id relates to.
pub id: Option<Secret<String>>,
/// The result of the action executed.
pub result_code: Option<ResultCode>,
/// Global Payments time indicating when the object was created in ISO-8601 format.
pub time_created: Option<String>,
/// Indicates the action taken.
#[serde(rename = "type")]
pub action_type: Option<ActionType>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GlobalpayRefreshTokenResponse {
pub token: Secret<String>,
pub seconds_to_expire: i64,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GlobalpayRefreshTokenErrorResponse {
pub error_code: String,
pub detailed_error_description: String,
}
/// Information relating to a currency conversion.
#[derive(Debug, Serialize, Deserialize)]
pub struct CurrencyConversion {
/// The percentage commission taken for providing the currency conversion.
pub commission_percentage: Option<String>,
/// The exchange rate used to convert one currency to another.
pub conversion_rate: Option<String>,
/// The source of the base exchange rate was obtained to execute the currency conversion.
pub exchange_rate_source: Option<String>,
/// The time the base exchange rate was obtained from the source.
pub exchange_source_time: Option<String>,
/// The exchange rate used to convert one currency to another.
pub margin_rate_percentage: Option<String>,
/// The amount that will affect the payer's account.
pub payer_amount: Option<StringMinorUnit>,
/// The currency of the amount that will affect the payer's account.
pub payer_currency: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentMethod {
/// Data associated with the response of an APM transaction.
pub apm: Option<Apm>,
/// Information outlining the degree of authentication executed related to a transaction.
pub authentication: Option<Authentication>,
pub bank_transfer: Option<BankTransfer>,
pub card: Option<Card>,
pub digital_wallet: Option<requests::DigitalWallet>,
/// Indicates how the payment method information was obtained by the Merchant for this
/// transaction.
pub entry_mode: Option<requests::PaymentMethodEntryMode>,
/// If enabled, this field contains the unique fingerprint signature for that payment method
/// for that merchant. If the payment method is seen again this same value is generated. For
/// cards the primary account number is checked only. The expiry date or the CVV is not used
/// for this check.
pub fingerprint: Option<Secret<String>>,
/// If enabled, this field indicates whether the payment method has been seen before or is
/// new.
/// * EXISTS - Indicates that the payment method was seen on the platform before by this
/// merchant.
/// * NEW - Indicates that the payment method was not seen on the platform before by this
/// merchant.
pub fingerprint_presence_indicator: Option<String>,
/// Unique Global Payments generated id used to reference a stored payment method on the
/// Global Payments system. Often referred to as the payment method token. This value can be
/// used instead of payment method details such as a card number and expiry date.
pub id: Option<Secret<String>>,
/// Result message from the payment method provider corresponding to the result code.
pub message: Option<String>,
/// Result code from the payment method provider.
pub result: Option<String>,
}
/// Data associated with the response of an APM transaction.
#[derive(Debug, Serialize, Deserialize)]
pub struct Apm {
pub bank: Option<Bank>,
/// A string generated by the payment method that represents to what degree the merchant is
/// funded for the transaction.
#[serde(skip_deserializing)]
pub fund_status: Option<FundStatus>,
pub mandate: Option<Mandate>,
/// A string used to identify the payment method provider being used to execute this
/// transaction.
pub provider: Option<ApmProvider>,
/// A name of the payer from the payment method system.
pub provider_payer_name: Option<Secret<String>>,
/// The time the payment method provider created the transaction at on their system.
pub provider_time_created: Option<String>,
/// The reference the payment method provider created for the transaction.
pub provider_transaction_reference: Option<String>,
/// URL to redirect the payer from the merchant's system to the payment method's system.
//1)paypal sends redirect_url as provider_redirect_url for require_customer_action
//2)bankredirects sends redirect_url as redirect_url for require_customer_action
//3)after completeauthorize in paypal it doesn't send redirect_url
//4)after customer action in bankredirects it sends empty string in redirect_url
#[serde(alias = "provider_redirect_url")]
pub redirect_url: Option<String>,
/// A string generated by the payment method to represent the session created on the payment
/// method's platform to facilitate the creation of a transaction.
pub session_token: Option<Secret<String>>,
pub payment_description: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Bank {
/// The local identifier of the bank account.
pub account_number: Option<Secret<String>>,
/// The local identifier of the bank.
pub code: Option<Secret<String>>,
/// The international identifier of the bank account.
pub iban: Option<Secret<String>>,
/// The international identifier code for the bank.
pub identifier_code: Option<Secret<String>>,
/// The name associated with the bank account
pub name: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Mandate {
/// The reference to identify the mandate.
pub code: Option<Secret<String>>,
}
/// Information outlining the degree of authentication executed related to a transaction.
#[derive(Debug, Serialize, Deserialize)]
pub struct Authentication {
/// Information outlining the degree of 3D Secure authentication executed.
pub three_ds: Option<ThreeDs>,
}
/// Information outlining the degree of 3D Secure authentication executed.
#[derive(Debug, Serialize, Deserialize)]
pub struct ThreeDs {
/// The result of the three_ds value validation by the brands or issuing bank.
pub value_result: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BankTransfer {
/// The last 4 characters of the local reference for a bank account number.
pub masked_number_last4: Option<String>,
/// The name of the bank.
pub name: Option<Secret<String>>,
/// The type of bank account associated with the payer's bank account.
pub number_type: Option<NumberType>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Card {
/// Code generated when the card is successfully authorized.
pub authcode: Option<Secret<String>>,
/// The recommended AVS action to be taken by the agent processing the card transaction.
pub avs_action: Option<String>,
/// The result of the AVS address check.
pub avs_address_result: Option<String>,
/// The result of the AVS postal code check.
pub avs_postal_code_result: Option<String>,
/// Indicates the card brand that issued the card.
pub brand: Option<Brand>,
/// The unique reference created by the brands/schemes to uniquely identify the transaction.
pub brand_reference: Option<Secret<String>>,
/// The time returned by the card brand indicating when the transaction was processed on
/// their system.
pub brand_time_reference: Option<String>,
/// The result of the CVV check.
pub cvv_result: Option<String>,
/// Masked card number with last 4 digits showing.
pub masked_number_last4: Option<String>,
/// The result codes directly from the card issuer.
pub provider: Option<ProviderClass>,
/// The card EMV tag response data from the card issuer for a contactless or chip card
/// transaction.
pub tag_response: Option<Secret<String>>,
}
/// The result codes directly from the card issuer.
#[derive(Debug, Serialize, Deserialize)]
pub struct ProviderClass {
/// The result code of the AVS address check from the card issuer.
#[serde(rename = "card.provider.avs_address_result")]
pub card_provider_avs_address_result: Option<String>,
/// The result of the AVS postal code check from the card issuer..
#[serde(rename = "card.provider.avs_postal_code_result")]
pub card_provider_avs_postal_code_result: Option<String>,
/// The result code of the AVS check from the card issuer.
#[serde(rename = "card.provider.avs_result")]
pub card_provider_avs_result: Option<String>,
/// The result code of the CVV check from the card issuer.
#[serde(rename = "card.provider.cvv_result")]
pub card_provider_cvv_result: Option<String>,
/// Result code from the card issuer.
#[serde(rename = "card.provider.result")]
pub card_provider_result: Option<String>,
}
/// The result of the action executed.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ResultCode {
Declined,
Success,
Pending,
Error,
}
/// Indicates the specific action taken.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ActionType {
Adjust,
Authorize,
Capture,
Confirm,
Force,
Increment,
Initiate,
MultipleCapture,
Preauthorize,
PreauthorizeMultipleCapturere,
Authorization,
RedirectFrom,
RedirectTo,
Refund,
Hold,
Release,
Reverse,
Split,
StatusNotification,
TransactionList,
TransactionSingle,
}
/// A string generated by the payment method that represents to what degree the merchant is
/// funded for the transaction.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FundStatus {
Missing,
NotExpected,
Received,
Waiting,
}
/// 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,
}
/// The type of bank account associated with the payer's bank account.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NumberType {
Checking,
Savings,
}
/// The recommended AVS action to be taken by the agent processing the card transaction.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AvsAction {
Accept,
Decline,
Prompt,
}
/// The result of the AVS address check.
///
/// The result of the AVS postal code check.
///
/// The result of the CVV check.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GlobalPayResult {
Matched,
NotChecked,
NotMatched,
}
/// Indicates the card brand that issued the card.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Brand {
Amex,
Cup,
Diners,
Discover,
Jcb,
Mastercard,
Visa,
}
/// Indicates where a transaction is in its lifecycle.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GlobalpayPaymentStatus {
/// A Transaction has been successfully authorized and captured. The funding
/// process will commence once the transaction remains in this status.
Captured,
/// A Transaction where the payment method provider declined the transfer of
/// funds between the payer and the merchant.
Declined,
/// A Transaction where the funds have transferred between payer and merchant as
/// expected.
Funded,
/// A Transaction has been successfully initiated. An update on its status is
/// expected via a separate asynchronous notification to a webhook.
Initiated,
/// A Transaction has been sent to the payment method provider and are waiting
/// for a result.
Pending,
/// A Transaction has been approved but a capture request is required to
/// commence the movement of funds.
Preauthorized,
/// A Transaction where the funds were expected to transfer between payer and
/// merchant but the transfer was rejected during the funding process. This rarely happens
/// but when it does it is usually addressed by Global Payments operations.
Rejected,
/// A Transaction that had a status of PENDING, PREAUTHORIZED or CAPTURED has
/// subsequently been reversed which voids/cancels a transaction before it is funded.
Reversed,
}
#[derive(Debug, Deserialize)]
pub struct GlobalpayWebhookObjectId {
pub id: String,
}
#[derive(Debug, Deserialize)]
pub struct GlobalpayWebhookObjectEventType {
pub status: GlobalpayWebhookStatus,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GlobalpayWebhookStatus {
Declined,
Captured,
#[serde(other)]
Unknown,
}
| 3,484 | 2,233 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs | .rs | 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, 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,
},
};
use hyperswitch_interfaces::{consts::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::{
types::{PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, construct_captures_response_hashmap, CardData, ForeignTryFrom,
MultipleCaptureSyncResponse, 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> {
let metadata = GlobalPayMeta::try_from(&item.router_data.connector_meta_data)?;
let account_name = metadata.account_name;
let (initiator, stored_credential, brand_reference) =
get_mandate_details(item.router_data)?;
let payment_method_data = get_payment_method_data(item.router_data, brand_reference)?;
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: requests::PaymentMethod {
payment_method_data,
authentication: None,
encryption: None,
entry_mode: Default::default(),
fingerprint_mode: None,
first_name: None,
id: None,
last_name: None,
name: None,
narrative: None,
storage_mode: None,
},
notifications: Some(requests::Notifications {
return_url: get_return_url(item.router_data),
challenge_return_url: None,
decoupled_challenge_return_url: None,
status_url: item.router_data.request.webhook_url.clone(),
three_ds_method_return_url: None,
cancel_url: get_return_url(item.router_data),
}),
authorization_mode: None,
cashback_amount: None,
channel: Default::default(),
convenience_amount: None,
currency_conversion: None,
description: None,
device: None,
gratuity_amount: None,
initiator,
ip_address: None,
language: None,
lodging: None,
order: None,
payer_reference: None,
site_reference: None,
stored_credential,
surcharge_amount: None,
total_capture_count: None,
globalpay_payments_request_type: None,
user_reference: None,
})
}
}
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<&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,
}
}
}
fn get_payment_response(
status: common_enums::AttemptStatus,
response: GlobalpayPaymentsResponse,
redirection_data: Option<RedirectForm>,
) -> Result<PaymentsResponseData, Box<ErrorResponse>> {
let mandate_reference = response.payment_method.as_ref().and_then(|pm| {
pm.card
.as_ref()
.and_then(|card| card.brand_reference.to_owned())
.map(|id| MandateReference {
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})
});
match status {
common_enums::AttemptStatus::Failure => Err(Box::new(ErrorResponse {
message: response
.payment_method
.and_then(|pm| pm.message)
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
..Default::default()
})),
_ => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.id),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: response.reference,
incremental_authorization_allowed: None,
charges: None,
}),
}
}
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)));
Ok(Self {
status,
response: get_payment_response(status, item.response, redirection_data)
.map_err(|err| *err),
..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_payment_method_data(
item: &PaymentsAuthorizeRouterData,
brand_reference: Option<String>,
) -> Result<PaymentMethodData, Error> {
match &item.request.payment_method_data {
payment_method_data::PaymentMethodData::Card(ccard) => {
Ok(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(),
account_type: None,
authcode: None,
avs_address: None,
avs_postal_code: None,
brand_reference,
chip_condition: None,
funding: None,
pin_block: None,
tag: None,
track: None,
}))
}
payment_method_data::PaymentMethodData::Wallet(wallet_data) => get_wallet_data(wallet_data),
payment_method_data::PaymentMethodData::BankRedirect(bank_redirect) => {
PaymentMethodData::try_from(bank_redirect)
}
_ => Err(errors::ConnectorError::NotImplemented(
"Payment methods".to_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(),
}
}
type MandateDetails = (Option<Initiator>, Option<StoredCredential>, Option<String>);
fn get_mandate_details(item: &PaymentsAuthorizeRouterData) -> Result<MandateDetails, Error> {
Ok(if item.request.is_mandate_payment() {
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,
}
});
(
Some(match item.request.off_session {
Some(true) => Initiator::Merchant,
_ => Initiator::Payer,
}),
Some(StoredCredential {
model: Some(requests::Model::Recurring),
sequence: Some(match connector_mandate_id.is_some() {
true => Sequence::Subsequent,
false => Sequence::First,
}),
}),
connector_mandate_id,
)
} else {
(None, None, None)
})
}
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()
}
}
| 4,544 | 2,234 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs | .rs | 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 {
/// A meaningful label for the merchant account set by Global Payments.
pub account_name: Secret<String>,
/// The amount to transfer between Payer and Merchant for a SALE or a REFUND. It is always
/// represented in the lowest denomiation of the related currency.
pub amount: Option<StringMinorUnit>,
/// Indicates if the merchant would accept an authorization for an amount less than the
/// requested amount. This is available for CP channel
/// only where the balance not authorized can be processed again using a different card.
pub authorization_mode: Option<AuthorizationMode>,
/// Indicates whether the transaction is to be captured automatically, later or later using
/// more than 1 partial capture.
pub capture_mode: Option<CaptureMode>,
/// The amount of the transaction that relates to cashback.It is always represented in the
/// lowest denomiation of the related currency.
pub cashback_amount: Option<StringMinorUnit>,
/// Describes whether the transaction was processed in a face to face(CP) scenario or a
/// Customer Not Present (CNP) scenario.
pub channel: Channel,
/// The amount that reflects the charge the merchant applied to the transaction for availing
/// of a more convenient purchase.It is always represented in the lowest denomiation of the
/// related currency.
pub convenience_amount: Option<StringMinorUnit>,
/// The country in ISO-3166-1(alpha-2 code) format.
pub country: api_models::enums::CountryAlpha2,
/// The currency of the amount in ISO-4217(alpha-3)
pub currency: String,
pub currency_conversion: Option<CurrencyConversion>,
/// Merchant defined field to describe the transaction.
pub description: Option<String>,
pub device: Option<Device>,
/// The amount of the gratuity for a transaction.It is always represented in the lowest
/// denomiation of the related currency.
pub gratuity_amount: Option<StringMinorUnit>,
/// Indicates whether the Merchant or the Payer initiated the creation of a transaction.
pub initiator: Option<Initiator>,
/// Indicates the source IP Address of the system used to create the transaction.
pub ip_address: Option<Secret<String, common_utils::pii::IpAddress>>,
/// Indicates the language the transaction was executed in. In the format ISO-639-1 (alpha-2)
/// or ISO-639-1 (alpha-2)_ISO-3166(alpha-2)
pub language: Option<Language>,
pub lodging: Option<Lodging>,
/// Indicates to Global Payments where the merchant wants to receive notifications of certain
/// events that occur on the Global Payments system.
pub notifications: Option<Notifications>,
pub order: Option<Order>,
/// The merchant's payer reference for the transaction
pub payer_reference: Option<String>,
pub payment_method: PaymentMethod,
/// Merchant defined field to reference the transaction.
pub reference: String,
/// A merchant defined reference for the location that created the transaction.
pub site_reference: Option<String>,
/// Stored data information used to create a transaction.
pub stored_credential: Option<StoredCredential>,
/// The amount that reflects the additional charge the merchant applied to the transaction
/// for using a specific payment method.It is always represented in the lowest denomiation of
/// the related currency.
pub surcharge_amount: Option<StringMinorUnit>,
/// Indicates the total or expected total of captures that will executed against a
/// transaction flagged as being captured multiple times.
pub total_capture_count: Option<i64>,
/// Describes whether the transaction is a SALE, that moves funds from Payer to Merchant, or
/// a REFUND where funds move from Merchant to Payer.
#[serde(rename = "type")]
pub globalpay_payments_request_type: Option<GlobalpayPaymentsRequestType>,
/// The merchant's user reference for the transaction. This represents the person who
/// processed the transaction on the merchant's behalf like a clerk or cashier reference.
pub user_reference: Option<String>,
}
#[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)]
pub struct CurrencyConversion {
/// A unique identifier generated by Global Payments to identify the currency conversion. It
/// can be used to reference a currency conversion when processing a sale or a refund
/// transaction.
pub id: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Device {
pub capabilities: Option<Capabilities>,
pub entry_modes: Option<Vec<Vec<DeviceEntryMode>>>,
/// Describes whether a device prompts a payer for a gratuity when the payer is entering
/// their payment method details to the device.
pub gratuity_prompt_mode: Option<GratuityPromptMode>,
/// Describes the receipts a device prints when processing a transaction.
pub print_receipt_mode: Option<PrintReceiptMode>,
/// The sequence number from the device used to align with processing platform.
pub sequence_number: Option<Secret<String>>,
/// A unique identifier for the physical device. This value persists with the device even if
/// it is repurposed.
pub serial_number: Option<Secret<String>>,
/// The time from the device in ISO8601 format
pub time: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Capabilities {
pub authorization_modes: Option<Vec<AuthorizationMode>>,
/// The number of lines that can be used to display information on the device.
pub display_line_count: Option<f64>,
pub enabled_response: Option<Vec<EnabledResponse>>,
pub entry_modes: Option<Vec<CapabilitiesEntryMode>>,
pub fraud: Option<Vec<AuthorizationMode>>,
pub mobile: Option<Vec<Mobile>>,
pub payer_verifications: Option<Vec<PayerVerification>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Lodging {
/// A reference that identifies the booking reference for a lodging stay.
pub booking_reference: Option<String>,
/// The amount charged for one nights lodging.
pub daily_rate_amount: Option<StringMinorUnit>,
/// A reference that identifies the booking reference for a lodging stay.
pub date_checked_in: Option<String>,
/// The check out date for a lodging stay.
pub date_checked_out: Option<String>,
/// The total number of days of the lodging stay.
pub duration_days: Option<f64>,
#[serde(rename = "lodging.charge_items")]
pub lodging_charge_items: Option<Vec<LodgingChargeItem>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LodgingChargeItem {
pub payment_method_program_codes: Option<Vec<PaymentMethodProgramCode>>,
/// A reference that identifies the charge item, such as a lodging folio number.
pub reference: Option<String>,
/// The total amount for the list of charge types for a charge item.
pub total_amount: Option<StringMinorUnit>,
pub types: Option<Vec<TypeElement>>,
}
/// Indicates to Global Payments where the merchant wants to receive notifications of certain
/// events that occur on the Global Payments system.
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Notifications {
/// The merchant URL that will receive the notification when the customer has completed the
/// authentication.
pub challenge_return_url: Option<String>,
/// The merchant URL that will receive the notification when the customer has completed the
/// authentication when the authentication is decoupled and separate to the purchase.
pub decoupled_challenge_return_url: Option<String>,
/// The merchant URL to return the payer to, once the payer has completed payment using the
/// payment method. This returns control of the payer's payment experience to the merchant.
pub return_url: Option<String>,
/// The merchant URL to notify the merchant of the latest status of the transaction.
pub status_url: Option<String>,
/// The merchant URL that will receive the notification when the 3DS ACS successfully gathers
/// de ice informatiSon and tonotification_configurations.cordingly.
pub three_ds_method_return_url: Option<String>,
/// The URL on merchant's website to which the customer should be redirected in the event of
/// the customer canceling the transaction.
pub cancel_url: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Order {
/// Merchant defined field common to all transactions that are part of the same order.
pub reference: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PaymentMethodData {
Card(Card),
Apm(Apm),
BankTransfer(BankTransfer),
DigitalWallet(DigitalWallet),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentMethod {
#[serde(flatten)]
pub payment_method_data: PaymentMethodData,
pub authentication: Option<Authentication>,
pub encryption: Option<Encryption>,
/// Indicates how the payment method information was obtained by the Merchant for this
/// transaction.
pub entry_mode: PaymentMethodEntryMode,
/// Indicates whether to execute the fingerprint signature functionality.
pub fingerprint_mode: Option<FingerprintMode>,
/// Specify the first name of the owner of the payment method.
pub first_name: Option<Secret<String>>,
/// Unique Global Payments generated id used to reference a stored payment method on the
/// Global Payments system. Often referred to as the payment method token. This value can be
/// used instead of payment method details such as a card number and expiry date.
pub id: Option<Secret<String>>,
/// Specify the surname of the owner of the payment method.
pub last_name: Option<Secret<String>>,
/// The full name of the owner of the payment method.
pub name: Option<Secret<String>>,
/// Contains the value a merchant wishes to appear on the payer's payment method statement
/// for this transaction
pub narrative: Option<String>,
/// Indicates whether to store the card as part of a transaction.
pub storage_mode: Option<CardStorageMode>,
}
#[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>,
}
/// Information outlining the degree of authentication executed related to a transaction.
#[derive(Debug, Serialize, Deserialize)]
pub struct Authentication {
/// Information outlining the degree of 3D Secure authentication executed.
pub three_ds: Option<ThreeDs>,
/// A message authentication code that is used to confirm the security and integrity of the
/// messaging to Global Payments.
pub mac: Option<String>,
}
/// Information outlining the degree of 3D Secure authentication executed.
#[derive(Debug, Serialize, Deserialize)]
pub struct ThreeDs {
/// The reference created by the 3DSecure Directory Server to identify the specific
/// authentication attempt.
pub ds_trans_reference: Option<String>,
/// An indication of the degree of the authentication and liability shift obtained for this
/// transaction. It is determined during the 3D Secure process. 2 or 1 for Mastercard
/// indicates the merchant has a liability shift. 5 or 6 for Visa or Amex indicates the
/// merchant has a liability shift. However for Amex if the payer is not enrolled the eci may
/// still be 6 but liability shift has not bee achieved.
pub eci: Option<String>,
/// Indicates if any exemptions apply to this transaction.
pub exempt_status: Option<ExemptStatus>,
/// Indicates the version of 3DS
pub message_version: Option<String>,
/// The reference created by the 3DSecure provider to identify the specific authentication
/// attempt.
pub server_trans_reference: Option<String>,
/// The authentication value created as part of the 3D Secure process.
pub value: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BankTransfer {
/// The number or reference for the payer's bank account.
pub account_number: Option<Secret<String>>,
pub bank: Option<Bank>,
/// The number or reference for the check
pub check_reference: Option<Secret<String>>,
/// The type of bank account associated with the payer's bank account.
pub number_type: Option<NumberType>,
/// Indicates how the transaction was authorized by the merchant.
pub sec_code: Option<SecCode>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Bank {
pub address: Option<Address>,
/// The local identifier code for the bank.
pub code: Option<Secret<String>>,
/// The name of the bank.
pub name: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Address {
/// Merchant defined field common to all transactions that are part of the same order.
pub city: Option<Secret<String>>,
/// The country in ISO-3166-1(alpha-2 code) format.
pub country: Option<String>,
/// First line of the address.
pub line_1: Option<Secret<String>>,
/// Second line of the address.
pub line_2: Option<Secret<String>>,
/// Third line of the address.
pub line_3: Option<Secret<String>>,
/// The city or town of the address.
pub postal_code: Option<Secret<String>>,
/// The state or region of the address. ISO 3166-2 minus the country code itself. For
/// example, US Illinois = IL, or in the case of GB counties Wiltshire = WI or Aberdeenshire
/// = ABD
pub state: Option<String>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Card {
/// The card providers description of their card product.
pub account_type: Option<String>,
/// Code generated when the card is successfully authorized.
pub authcode: Option<Secret<String>>,
/// First line of the address associated with the card.
pub avs_address: Option<String>,
/// Postal code of the address associated with the card.
pub avs_postal_code: Option<String>,
/// The unique reference created by the brands/schemes to uniquely identify the transaction.
pub brand_reference: Option<String>,
/// Indicates if a fallback mechanism was used to obtain the card information when EMV/chip
/// did not work as expected.
pub chip_condition: Option<ChipCondition>,
/// The numeric value printed on the physical card.
pub cvv: Secret<String>,
/// The 2 digit expiry date month of the card.
pub expiry_month: Secret<String>,
/// The 2 digit expiry date year of the card.
pub expiry_year: Secret<String>,
/// Indicates whether the card is a debit or credit card.
pub funding: Option<Funding>,
/// The card account number used to authorize the transaction. Also known as PAN.
pub number: cards::CardNumber,
/// Contains the pin block info, relating to the pin code the Payer entered.
pub pin_block: Option<Secret<String>>,
/// The full card tag data for an EMV/chip card transaction.
pub tag: Option<Secret<String>>,
/// Data from magnetic stripe of a card
pub track: Option<Secret<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>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Encryption {
/// The encryption info used when sending encrypted card data to Global Payments.
pub info: Option<Secret<String>>,
/// The encryption method used when sending encrypted card data to Global Payments.
pub method: Option<Method>,
/// The version of encryption being used.
pub version: Option<String>,
}
/// 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 if the merchant would accept an authorization for an amount less than the
/// requested amount. This is available for CP channel
/// only where the balance not authorized can be processed again using a different card.
///
/// Describes the instruction a device can indicate to the clerk in the case of fraud.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AuthorizationMode {
/// Indicates merchant would accept an authorization for an amount less than the
/// requested amount.
/// pub example: PARTIAL
///
/// Describes whether the device can process partial authorizations.
Partial,
}
/// 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,
}
/// Describes the data the device can handle when it receives a response for a card
/// authorization.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum EnabledResponse {
Avs,
BrandReference,
Cvv,
MaskedNumberLast4,
}
/// Describes the entry mode capabilities a device has.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CapabilitiesEntryMode {
Chip,
Contactless,
ContactlessSwipe,
Manual,
Swipe,
}
/// Describes the mobile features a device has
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Mobile {
IntegratedCardReader,
SeparateCardReader,
}
/// Describes the capabilities a device has to verify a payer.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayerVerification {
ContactlessSignature,
PayerDevice,
Pinpad,
}
/// Describes the allowed entry modes to obtain payment method information from the payer as
/// part of a transaction request.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DeviceEntryMode {
Chip,
Contactless,
Manual,
Swipe,
}
/// Describes whether a device prompts a payer for a gratuity when the payer is entering
/// their payment method details to the device.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GratuityPromptMode {
NotRequired,
Prompt,
}
/// Describes the receipts a device prints when processing a transaction.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PrintReceiptMode {
Both,
Merchant,
None,
Payer,
}
/// Describes whether the transaction is a SALE, that moves funds from Payer to Merchant, or
/// a REFUND where funds move from Merchant to Payer.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GlobalpayPaymentsRequestType {
/// indicates the movement, or the attempt to move, funds from merchant to the
/// payer.
Refund,
/// indicates the movement, or the attempt to move, funds from payer to a
/// merchant.
Sale,
}
/// 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,
}
/// Indicates the language the transaction was executed in. In the format ISO-639-1 (alpha-2)
/// or ISO-639-1 (alpha-2)_ISO-3166(alpha-2)
#[derive(Debug, Serialize, Deserialize)]
pub enum Language {
#[serde(rename = "fr")]
Fr,
#[serde(rename = "fr_CA")]
FrCa,
#[serde(rename = "ISO-639(alpha-2)")]
Iso639Alpha2,
#[serde(rename = "ISO-639(alpha-2)_ISO-3166(alpha-2)")]
Iso639alpha2Iso3166alpha2,
}
/// Describes the payment method programs, typically run by card brands such as Amex, Visa
/// and MC.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentMethodProgramCode {
AssuredReservation,
CardDeposit,
Other,
Purchase,
}
/// Describes the types of charges associated with a transaction. This can be one or more
/// than more charge type.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TypeElement {
GiftShop,
Laundry,
MiniBar,
NoShow,
Other,
Phone,
Restaurant,
}
/// 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,
}
/// Indicates if any exemptions apply to this transaction.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ExemptStatus {
LowValue,
ScaDelegation,
SecureCorporatePayment,
TransactionRiskAnalysis,
TrustedMerchant,
}
/// The type of bank account associated with the payer's bank account.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NumberType {
Checking,
Savings,
}
/// Indicates how the transaction was authorized by the merchant.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SecCode {
/// Cash Concentration or Disbursement - Can be either a credit or debit application
/// where funds are wither distributed or consolidated between corporate entities.
#[serde(rename = "CCD")]
CashConcentrationOrDisbursement,
/// Point of Sale Entry - Point of sale debit applications non-shared (POS)
/// environment. These transactions are most often initiated by the consumer via a plastic
/// access card. This is only support for normal ACH transactions
#[serde(rename = "POP")]
PointOfSaleEntry,
/// Prearranged Payment and Deposits - used to credit or debit a consumer account.
/// Popularity used for payroll direct deposits and pre-authorized bill payments.
#[serde(rename = "PPD")]
PrearrangedPaymentAndDeposits,
/// Telephone-Initiated Entry - Used for the origination of a single entry debit
/// transaction to a consumer's account pursuant to a verbal authorization obtained from the
/// consumer via the telephone.
#[serde(rename = "TEL")]
TelephoneInitiatedEntry,
/// Internet (Web)-Initiated Entry - Used for the origination of debit entries
/// (either Single or Recurring Entry) to a consumer's account pursuant to a to an
/// authorization that is obtained from the Receiver via the Internet.
#[serde(rename = "WEB")]
WebInitiatedEntry,
}
/// Indicates if a fallback mechanism was used to obtain the card information when EMV/chip
/// did not work as expected.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ChipCondition {
/// indicates the previous transaction with this card failed.
PrevFailed,
/// indicates the previous transaction with this card was a success.
PrevSuccess,
}
/// Indicates whether the card is a debit or credit card.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Funding {
/// indicates the card is an, Electronic Benefits Transfer, for cash
/// benefits.
CashBenefits,
/// indicates the card is a credit card where the funds may be available on credit
/// to the payer to fulfill the transaction amount.
Credit,
/// indicates the card is a debit card where the funds may be present in an account
/// to fulfill the transaction amount.
Debit,
/// indicates the card is an, Electronic Benefits Transfer, for food stamps.
FoodStamp,
/// indicates the card is a prepaid card where the funds are loaded to the card
/// account to fulfill the transaction amount. Unlike a debit card, a prepaid is not linked
/// to a bank account.
Prepaid,
}
/// 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 if the actual card number or a token is being used to process the
/// transaction.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TokenFormat {
/// The value in the digital wallet token field is a real card number
/// (PAN)
CardNumber,
/// The value in the digital wallet token field is a temporary token in the
/// format of a card number (PAN) but is not a real card number.
CardToken,
}
/// The encryption method used when sending encrypted card data to Global Payments.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Method {
Ksn,
Ktb,
}
/// 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 whether to execute the fingerprint signature functionality.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FingerprintMode {
/// Always check and create the fingerprint value regardless of the result of the
/// card authorization.
Always,
/// Always check and create the fingerprint value when the card authorization
/// is successful.
OnSuccess,
}
/// Indicates whether to store the card as part of a transaction.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CardStorageMode {
/// /// The card information is always stored irrespective of whether the payment
/// method authorization was successful or not.
Always,
/// The card information is only stored if the payment method authorization was
/// successful.
OnSuccess,
}
/// 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,
}
/// The reason stored credentials are being used to create a transaction.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Reason {
Delayed,
Incremental,
NoShow,
Reauthorization,
Resubmission,
}
/// 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>,
}
| 7,105 | 2,235 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/forte/transformers.rs | .rs | use cards::CardNumber;
use common_enums::enums;
use common_utils::types::FloatMajorUnit;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{PaymentsCaptureResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, CardData as _PaymentsAuthorizeRequestData,
PaymentsAuthorizeRequestData, RouterData as _,
},
};
#[derive(Debug, Serialize)]
pub struct ForteRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for ForteRouterData<T> {
fn from((amount, router_data): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Serialize)]
pub struct FortePaymentsRequest {
action: ForteAction,
authorization_amount: FloatMajorUnit,
billing_address: BillingAddress,
card: Card,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BillingAddress {
first_name: Secret<String>,
last_name: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct Card {
card_type: ForteCardType,
name_on_card: Secret<String>,
account_number: CardNumber,
expire_month: Secret<String>,
expire_year: Secret<String>,
card_verification_value: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ForteCardType {
Visa,
MasterCard,
Amex,
Discover,
DinersClub,
Jcb,
}
impl TryFrom<utils::CardIssuer> for ForteCardType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(issuer: utils::CardIssuer) -> Result<Self, Self::Error> {
match issuer {
utils::CardIssuer::AmericanExpress => Ok(Self::Amex),
utils::CardIssuer::Master => Ok(Self::MasterCard),
utils::CardIssuer::Discover => Ok(Self::Discover),
utils::CardIssuer::Visa => Ok(Self::Visa),
utils::CardIssuer::DinersClub => Ok(Self::DinersClub),
utils::CardIssuer::JCB => Ok(Self::Jcb),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Forte"),
)
.into()),
}
}
}
impl TryFrom<&ForteRouterData<&types::PaymentsAuthorizeRouterData>> for FortePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item_data: &ForteRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let item = item_data.router_data;
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 => enums::AttemptStatus::Charged,
},
ForteResponseCode::A05 | ForteResponseCode::A06 => enums::AttemptStatus::Authorizing,
_ => enums::AttemptStatus::Failure,
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CardResponse {
pub name_on_card: Secret<String>,
pub last_4_account_number: String,
pub masked_account_number: String,
pub card_type: 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,
}
#[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 location_id: Secret<String>,
pub status: FortePaymentStatus,
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,
}
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,
}
| 4,436 | 2,236 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs | .rs | 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,
}
| 5,672 | 2,237 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs | .rs | use std::collections::HashMap;
use api_models::payments::SessionToken;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
pii::{self, Email},
request::Method,
types::StringMajorUnit,
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::{BankRedirectData, BankTransferData, Card, PaymentMethodData},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::{BrowserInformation, PaymentsPreProcessingData, ResponseId},
router_response_types::{
PaymentsResponseData, PreprocessingResponseId, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsPreProcessingRouterData, RefreshTokenRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use reqwest::Url;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, BrowserInformationData, CardData, PaymentsAuthorizeRequestData,
PaymentsPreProcessingRequestData, RouterData as OtherRouterData,
},
};
type Error = error_stack::Report<errors::ConnectorError>;
#[derive(Debug, Serialize)]
pub struct TrustpayRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(StringMajorUnit, T)> for TrustpayRouterData<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,
})
}
}
pub struct TrustpayAuthType {
pub(super) api_key: Secret<String>,
pub(super) project_id: Secret<String>,
pub(super) secret_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for TrustpayAuthType {
type Error = Error;
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(),
project_id: key1.to_owned(),
secret_key: api_secret.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum TrustpayPaymentMethod {
#[serde(rename = "EPS")]
Eps,
Giropay,
IDeal,
Sofort,
Blik,
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum TrustpayBankTransferPaymentMethod {
SepaCreditTransfer,
#[serde(rename = "Wire")]
InstantBankTransfer,
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct MerchantIdentification {
pub project_id: Secret<String>,
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct References {
pub merchant_reference: String,
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct Amount {
pub amount: StringMajorUnit,
pub currency: String,
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct Reason {
pub code: Option<String>,
pub reject_reason: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct StatusReasonInformation {
pub reason: Reason,
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct DebtorInformation {
pub name: Secret<String>,
pub email: Email,
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct BankPaymentInformation {
pub amount: Amount,
pub references: References,
#[serde(skip_serializing_if = "Option::is_none")]
pub debtor: Option<DebtorInformation>,
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct BankPaymentInformationResponse {
pub status: TrustpayBankRedirectPaymentStatus,
pub status_reason_information: Option<StatusReasonInformation>,
pub references: ReferencesResponse,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct CallbackURLs {
pub success: String,
pub cancel: String,
pub error: String,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct PaymentRequestCards {
pub amount: StringMajorUnit,
pub currency: String,
pub pan: cards::CardNumber,
pub cvv: Secret<String>,
#[serde(rename = "exp")]
pub expiry_date: Secret<String>,
pub cardholder: Secret<String>,
pub reference: String,
#[serde(rename = "redirectUrl")]
pub redirect_url: String,
#[serde(rename = "billing[city]")]
pub billing_city: String,
#[serde(rename = "billing[country]")]
pub billing_country: api_models::enums::CountryAlpha2,
#[serde(rename = "billing[street1]")]
pub billing_street1: Secret<String>,
#[serde(rename = "billing[postcode]")]
pub billing_postcode: Secret<String>,
#[serde(rename = "customer[email]")]
pub customer_email: Email,
#[serde(rename = "customer[ipAddress]")]
pub customer_ip_address: Secret<String, pii::IpAddress>,
#[serde(rename = "browser[acceptHeader]")]
pub browser_accept_header: String,
#[serde(rename = "browser[language]")]
pub browser_language: String,
#[serde(rename = "browser[screenHeight]")]
pub browser_screen_height: String,
#[serde(rename = "browser[screenWidth]")]
pub browser_screen_width: String,
#[serde(rename = "browser[timezone]")]
pub browser_timezone: String,
#[serde(rename = "browser[userAgent]")]
pub browser_user_agent: String,
#[serde(rename = "browser[javaEnabled]")]
pub browser_java_enabled: String,
#[serde(rename = "browser[javaScriptEnabled]")]
pub browser_java_script_enabled: String,
#[serde(rename = "browser[screenColorDepth]")]
pub browser_screen_color_depth: String,
#[serde(rename = "browser[challengeWindow]")]
pub browser_challenge_window: String,
#[serde(rename = "browser[paymentAction]")]
pub payment_action: Option<String>,
#[serde(rename = "browser[paymentType]")]
pub payment_type: String,
pub descriptor: Option<String>,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentRequestBankRedirect {
pub payment_method: TrustpayPaymentMethod,
pub merchant_identification: MerchantIdentification,
pub payment_information: BankPaymentInformation,
pub callback_urls: CallbackURLs,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(untagged)]
pub enum TrustpayPaymentsRequest {
CardsPaymentRequest(Box<PaymentRequestCards>),
BankRedirectPaymentRequest(Box<PaymentRequestBankRedirect>),
BankTransferPaymentRequest(Box<PaymentRequestBankTransfer>),
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentRequestBankTransfer {
pub payment_method: TrustpayBankTransferPaymentMethod,
pub merchant_identification: MerchantIdentification,
pub payment_information: BankPaymentInformation,
pub callback_urls: CallbackURLs,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct TrustpayMandatoryParams {
pub billing_city: String,
pub billing_country: api_models::enums::CountryAlpha2,
pub billing_street1: Secret<String>,
pub billing_postcode: Secret<String>,
pub billing_first_name: Secret<String>,
}
impl TryFrom<&BankRedirectData> for TrustpayPaymentMethod {
type Error = Error;
fn try_from(value: &BankRedirectData) -> Result<Self, Self::Error> {
match value {
BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
BankRedirectData::Eps { .. } => Ok(Self::Eps),
BankRedirectData::Ideal { .. } => Ok(Self::IDeal),
BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
BankRedirectData::Blik { .. } => Ok(Self::Blik),
BankRedirectData::BancontactCard { .. }
| 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("trustpay"),
)
.into())
}
}
}
}
impl TryFrom<&BankTransferData> for TrustpayBankTransferPaymentMethod {
type Error = Error;
fn try_from(value: &BankTransferData) -> Result<Self, Self::Error> {
match value {
BankTransferData::SepaBankTransfer { .. } => Ok(Self::SepaCreditTransfer),
BankTransferData::InstantBankTransfer {} => Ok(Self::InstantBankTransfer),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("trustpay"),
)
.into()),
}
}
}
fn get_mandatory_fields(
item: &PaymentsAuthorizeRouterData,
) -> Result<TrustpayMandatoryParams, Error> {
let billing_address = item
.get_billing()?
.address
.as_ref()
.ok_or_else(utils::missing_field_err("billing.address"))?;
Ok(TrustpayMandatoryParams {
billing_city: billing_address.get_city()?.to_owned(),
billing_country: billing_address.get_country()?.to_owned(),
billing_street1: billing_address.get_line1()?.to_owned(),
billing_postcode: billing_address.get_zip()?.to_owned(),
billing_first_name: billing_address.get_first_name()?.to_owned(),
})
}
fn get_card_request_data(
item: &PaymentsAuthorizeRouterData,
browser_info: &BrowserInformation,
params: TrustpayMandatoryParams,
amount: StringMajorUnit,
ccard: &Card,
return_url: String,
) -> Result<TrustpayPaymentsRequest, Error> {
let email = item.request.get_email()?;
let customer_ip_address = browser_info.get_ip_address()?;
let billing_last_name = item
.get_billing()?
.address
.as_ref()
.and_then(|address| address.last_name.clone());
Ok(TrustpayPaymentsRequest::CardsPaymentRequest(Box::new(
PaymentRequestCards {
amount,
currency: item.request.currency.to_string(),
pan: ccard.card_number.clone(),
cvv: ccard.card_cvc.clone(),
expiry_date: ccard.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?,
cardholder: get_full_name(params.billing_first_name, billing_last_name),
reference: item.connector_request_reference_id.clone(),
redirect_url: return_url,
billing_city: params.billing_city,
billing_country: params.billing_country,
billing_street1: params.billing_street1,
billing_postcode: params.billing_postcode,
customer_email: email,
customer_ip_address,
browser_accept_header: browser_info.get_accept_header()?,
browser_language: browser_info.get_language()?,
browser_screen_height: browser_info.get_screen_height()?.to_string(),
browser_screen_width: browser_info.get_screen_width()?.to_string(),
browser_timezone: browser_info.get_time_zone()?.to_string(),
browser_user_agent: browser_info.get_user_agent()?,
browser_java_enabled: browser_info.get_java_enabled()?.to_string(),
browser_java_script_enabled: browser_info.get_java_script_enabled()?.to_string(),
browser_screen_color_depth: browser_info.get_color_depth()?.to_string(),
browser_challenge_window: "1".to_string(),
payment_action: None,
payment_type: "Plain".to_string(),
descriptor: item.request.statement_descriptor.clone(),
},
)))
}
fn get_full_name(
billing_first_name: Secret<String>,
billing_last_name: Option<Secret<String>>,
) -> Secret<String> {
match billing_last_name {
Some(last_name) => format!("{} {}", billing_first_name.peek(), last_name.peek()).into(),
None => billing_first_name,
}
}
fn get_debtor_info(
item: &PaymentsAuthorizeRouterData,
pm: TrustpayPaymentMethod,
params: TrustpayMandatoryParams,
) -> CustomResult<Option<DebtorInformation>, errors::ConnectorError> {
let billing_last_name = item
.get_billing()?
.address
.as_ref()
.and_then(|address| address.last_name.clone());
Ok(match pm {
TrustpayPaymentMethod::Blik => Some(DebtorInformation {
name: get_full_name(params.billing_first_name, billing_last_name),
email: item.request.get_email()?,
}),
TrustpayPaymentMethod::Eps
| TrustpayPaymentMethod::Giropay
| TrustpayPaymentMethod::IDeal
| TrustpayPaymentMethod::Sofort => None,
})
}
fn get_bank_transfer_debtor_info(
item: &PaymentsAuthorizeRouterData,
pm: TrustpayBankTransferPaymentMethod,
params: TrustpayMandatoryParams,
) -> CustomResult<Option<DebtorInformation>, errors::ConnectorError> {
let billing_last_name = item
.get_billing()?
.address
.as_ref()
.and_then(|address| address.last_name.clone());
Ok(match pm {
TrustpayBankTransferPaymentMethod::SepaCreditTransfer
| TrustpayBankTransferPaymentMethod::InstantBankTransfer => Some(DebtorInformation {
name: get_full_name(params.billing_first_name, billing_last_name),
email: item.request.get_email()?,
}),
})
}
fn get_bank_redirection_request_data(
item: &PaymentsAuthorizeRouterData,
bank_redirection_data: &BankRedirectData,
params: TrustpayMandatoryParams,
amount: StringMajorUnit,
auth: TrustpayAuthType,
) -> Result<TrustpayPaymentsRequest, error_stack::Report<errors::ConnectorError>> {
let pm = TrustpayPaymentMethod::try_from(bank_redirection_data)?;
let return_url = item.request.get_router_return_url()?;
let payment_request =
TrustpayPaymentsRequest::BankRedirectPaymentRequest(Box::new(PaymentRequestBankRedirect {
payment_method: pm.clone(),
merchant_identification: MerchantIdentification {
project_id: auth.project_id,
},
payment_information: BankPaymentInformation {
amount: Amount {
amount,
currency: item.request.currency.to_string(),
},
references: References {
merchant_reference: item.connector_request_reference_id.clone(),
},
debtor: get_debtor_info(item, pm, params)?,
},
callback_urls: CallbackURLs {
success: format!("{return_url}?status=SuccessOk"),
cancel: return_url.clone(),
error: return_url,
},
}));
Ok(payment_request)
}
fn get_bank_transfer_request_data(
item: &PaymentsAuthorizeRouterData,
bank_transfer_data: &BankTransferData,
params: TrustpayMandatoryParams,
amount: StringMajorUnit,
auth: TrustpayAuthType,
) -> Result<TrustpayPaymentsRequest, error_stack::Report<errors::ConnectorError>> {
let pm = TrustpayBankTransferPaymentMethod::try_from(bank_transfer_data)?;
let return_url = item.request.get_router_return_url()?;
let payment_request =
TrustpayPaymentsRequest::BankTransferPaymentRequest(Box::new(PaymentRequestBankTransfer {
payment_method: pm.clone(),
merchant_identification: MerchantIdentification {
project_id: auth.project_id,
},
payment_information: BankPaymentInformation {
amount: Amount {
amount,
currency: item.request.currency.to_string(),
},
references: References {
merchant_reference: item.connector_request_reference_id.clone(),
},
debtor: get_bank_transfer_debtor_info(item, pm, params)?,
},
callback_urls: CallbackURLs {
success: format!("{return_url}?status=SuccessOk"),
cancel: return_url.clone(),
error: return_url,
},
}));
Ok(payment_request)
}
impl TryFrom<&TrustpayRouterData<&PaymentsAuthorizeRouterData>> for TrustpayPaymentsRequest {
type Error = Error;
fn try_from(
item: &TrustpayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let browser_info = item
.router_data
.request
.browser_info
.clone()
.unwrap_or_default();
let default_browser_info = BrowserInformation {
color_depth: Some(browser_info.color_depth.unwrap_or(24)),
java_enabled: Some(browser_info.java_enabled.unwrap_or(false)),
java_script_enabled: Some(browser_info.java_enabled.unwrap_or(true)),
language: Some(browser_info.language.unwrap_or("en-US".to_string())),
screen_height: Some(browser_info.screen_height.unwrap_or(1080)),
screen_width: Some(browser_info.screen_width.unwrap_or(1920)),
time_zone: Some(browser_info.time_zone.unwrap_or(3600)),
accept_header: Some(browser_info.accept_header.unwrap_or("*".to_string())),
user_agent: browser_info.user_agent,
ip_address: browser_info.ip_address,
os_type: None,
os_version: None,
device_model: None,
accept_language: Some(browser_info.accept_language.unwrap_or("en".to_string())),
};
let params = get_mandatory_fields(item.router_data)?;
let amount = item.amount.to_owned();
let auth = TrustpayAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => Ok(get_card_request_data(
item.router_data,
&default_browser_info,
params,
amount,
ccard,
item.router_data.request.get_router_return_url()?,
)?),
PaymentMethodData::BankRedirect(ref bank_redirection_data) => {
get_bank_redirection_request_data(
item.router_data,
bank_redirection_data,
params,
amount,
auth,
)
}
PaymentMethodData::BankTransfer(ref bank_transfer_data) => {
get_bank_transfer_request_data(
item.router_data,
bank_transfer_data,
params,
amount,
auth,
)
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| 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("trustpay"),
)
.into())
}
}
}
}
fn is_payment_failed(payment_status: &str) -> (bool, &'static str) {
match payment_status {
"100.100.600" => (true, "Empty CVV for VISA, MASTER not allowed"),
"100.350.100" => (true, "Referenced session is rejected (no action possible)"),
"100.380.401" => (true, "User authentication failed"),
"100.380.501" => (true, "Risk management transaction timeout"),
"100.390.103" => (true, "PARes validation failed - problem with signature"),
"100.390.105" => (
true,
"Transaction rejected because of technical error in 3DSecure system",
),
"100.390.111" => (
true,
"Communication error to VISA/Mastercard Directory Server",
),
"100.390.112" => (true, "Technical error in 3D system"),
"100.390.115" => (true, "Authentication failed due to invalid message format"),
"100.390.118" => (true, "Authentication failed due to suspected fraud"),
"100.400.304" => (true, "Invalid input data"),
"100.550.312" => (true, "Amount is outside allowed ticket size boundaries"),
"200.300.404" => (true, "Invalid or missing parameter"),
"300.100.100" => (
true,
"Transaction declined (additional customer authentication required)",
),
"400.001.301" => (true, "Card not enrolled in 3DS"),
"400.001.600" => (true, "Authentication error"),
"400.001.601" => (true, "Transaction declined (auth. declined)"),
"400.001.602" => (true, "Invalid transaction"),
"400.001.603" => (true, "Invalid transaction"),
"400.003.600" => (true, "No description available."),
"700.400.200" => (
true,
"Cannot refund (refund volume exceeded or tx reversed or invalid workflow)",
),
"700.500.001" => (true, "Referenced session contains too many transactions"),
"700.500.003" => (true, "Test accounts not allowed in production"),
"800.100.100" => (true, "Transaction declined for unknown reason"),
"800.100.151" => (true, "Transaction declined (invalid card)"),
"800.100.152" => (true, "Transaction declined by authorization system"),
"800.100.153" => (true, "Transaction declined (invalid CVV)"),
"800.100.155" => (true, "Transaction declined (amount exceeds credit)"),
"800.100.157" => (true, "Transaction declined (wrong expiry date)"),
"800.100.158" => (true, "transaction declined (suspecting manipulation)"),
"800.100.160" => (true, "transaction declined (card blocked)"),
"800.100.162" => (true, "Transaction declined (limit exceeded)"),
"800.100.163" => (
true,
"Transaction declined (maximum transaction frequency exceeded)",
),
"800.100.165" => (true, "Transaction declined (card lost)"),
"800.100.168" => (true, "Transaction declined (restricted card)"),
"800.100.170" => (true, "Transaction declined (transaction not permitted)"),
"800.100.171" => (true, "transaction declined (pick up card)"),
"800.100.172" => (true, "Transaction declined (account blocked)"),
"800.100.190" => (true, "Transaction declined (invalid configuration data)"),
"800.100.202" => (true, "Account Closed"),
"800.100.203" => (true, "Insufficient Funds"),
"800.120.100" => (true, "Rejected by throttling"),
"800.300.102" => (true, "Country blacklisted"),
"800.300.401" => (true, "Bin blacklisted"),
"800.700.100" => (
true,
"Transaction for the same session is currently being processed, please try again later",
),
"900.100.100" => (
true,
"Unexpected communication error with connector/acquirer",
),
"900.100.300" => (true, "Timeout, uncertain result"),
_ => (false, ""),
}
}
fn is_payment_successful(payment_status: &str) -> CustomResult<bool, errors::ConnectorError> {
match payment_status {
"000.400.100" => Ok(true),
_ => {
let allowed_prefixes = [
"000.000.",
"000.100.1",
"000.3",
"000.6",
"000.400.01",
"000.400.02",
"000.400.04",
"000.400.05",
"000.400.06",
"000.400.07",
"000.400.08",
"000.400.09",
];
let is_valid = allowed_prefixes
.iter()
.any(|&prefix| payment_status.starts_with(prefix));
Ok(is_valid)
}
}
}
fn get_pending_status_based_on_redirect_url(redirect_url: Option<Url>) -> enums::AttemptStatus {
match redirect_url {
Some(_url) => enums::AttemptStatus::AuthenticationPending,
None => enums::AttemptStatus::Pending,
}
}
fn get_transaction_status(
payment_status: Option<String>,
redirect_url: Option<Url>,
) -> CustomResult<(enums::AttemptStatus, Option<String>), errors::ConnectorError> {
// We don't get payment_status only in case, when the user doesn't complete the authentication step.
// If we receive status, then return the proper status based on the connector response
if let Some(payment_status) = payment_status {
let (is_failed, failure_message) = is_payment_failed(&payment_status);
if is_failed {
return Ok((
enums::AttemptStatus::Failure,
Some(failure_message.to_string()),
));
}
if is_payment_successful(&payment_status)? {
return Ok((enums::AttemptStatus::Charged, None));
}
let pending_status = get_pending_status_based_on_redirect_url(redirect_url);
Ok((pending_status, None))
} else {
Ok((enums::AttemptStatus::AuthenticationPending, None))
}
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
pub enum TrustpayBankRedirectPaymentStatus {
Paid,
Authorized,
Rejected,
Authorizing,
Pending,
}
impl From<TrustpayBankRedirectPaymentStatus> for enums::AttemptStatus {
fn from(item: TrustpayBankRedirectPaymentStatus) -> Self {
match item {
TrustpayBankRedirectPaymentStatus::Paid => Self::Charged,
TrustpayBankRedirectPaymentStatus::Rejected => Self::AuthorizationFailed,
TrustpayBankRedirectPaymentStatus::Authorized => Self::Authorized,
TrustpayBankRedirectPaymentStatus::Authorizing => Self::Authorizing,
TrustpayBankRedirectPaymentStatus::Pending => Self::Authorizing,
}
}
}
impl From<TrustpayBankRedirectPaymentStatus> for enums::RefundStatus {
fn from(item: TrustpayBankRedirectPaymentStatus) -> Self {
match item {
TrustpayBankRedirectPaymentStatus::Paid => Self::Success,
TrustpayBankRedirectPaymentStatus::Rejected => Self::Failure,
_ => Self::Pending,
}
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentsResponseCards {
pub status: i64,
pub description: Option<String>,
pub instance_id: String,
pub payment_status: Option<String>,
pub payment_description: Option<String>,
pub redirect_url: Option<Url>,
pub redirect_params: Option<HashMap<String, String>>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct PaymentsResponseBankRedirect {
pub payment_request_id: i64,
pub gateway_url: Url,
pub payment_result_info: Option<ResultInfo>,
pub payment_method_response: Option<TrustpayPaymentMethod>,
pub merchant_identification_response: Option<MerchantIdentification>,
pub payment_information_response: Option<BankPaymentInformationResponse>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct ErrorResponseBankRedirect {
#[serde(rename = "ResultInfo")]
pub payment_result_info: ResultInfo,
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct ReferencesResponse {
pub payment_request_id: String,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct SyncResponseBankRedirect {
pub payment_information: BankPaymentInformationResponse,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum TrustpayPaymentsResponse {
CardsPayments(Box<PaymentsResponseCards>),
BankRedirectPayments(Box<PaymentsResponseBankRedirect>),
BankRedirectSync(Box<SyncResponseBankRedirect>),
BankRedirectError(Box<ErrorResponseBankRedirect>),
WebhookResponse(Box<WebhookPaymentInformation>),
}
impl<F, T> TryFrom<ResponseRouterData<F, TrustpayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, TrustpayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, error, payment_response_data) =
get_trustpay_response(item.response, item.http_code, item.data.status)?;
Ok(Self {
status,
response: error.map_or_else(|| Ok(payment_response_data), Err),
..item.data
})
}
}
fn handle_cards_response(
response: PaymentsResponseCards,
status_code: u16,
) -> CustomResult<
(
enums::AttemptStatus,
Option<ErrorResponse>,
PaymentsResponseData,
),
errors::ConnectorError,
> {
let (status, msg) = get_transaction_status(
response.payment_status.to_owned(),
response.redirect_url.to_owned(),
)?;
let form_fields = response.redirect_params.unwrap_or_default();
let redirection_data = response.redirect_url.map(|url| RedirectForm::Form {
endpoint: url.to_string(),
method: Method::Post,
form_fields,
});
let error = if msg.is_some() {
Some(ErrorResponse {
code: response
.payment_status
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: msg
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: msg,
status_code,
attempt_status: None,
connector_transaction_id: Some(response.instance_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
None
};
let payment_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.instance_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))
}
fn handle_bank_redirects_response(
response: PaymentsResponseBankRedirect,
) -> CustomResult<
(
enums::AttemptStatus,
Option<ErrorResponse>,
PaymentsResponseData,
),
errors::ConnectorError,
> {
let status = enums::AttemptStatus::AuthenticationPending;
let error = None;
let payment_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.payment_request_id.to_string()),
redirection_data: Box::new(Some(RedirectForm::from((
response.gateway_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,
};
Ok((status, error, payment_response_data))
}
fn handle_bank_redirects_error_response(
response: ErrorResponseBankRedirect,
status_code: u16,
previous_attempt_status: enums::AttemptStatus,
) -> CustomResult<
(
enums::AttemptStatus,
Option<ErrorResponse>,
PaymentsResponseData,
),
errors::ConnectorError,
> {
let status = if matches!(response.payment_result_info.result_code, 1132014 | 1132005) {
previous_attempt_status
} else {
enums::AttemptStatus::AuthorizationFailed
};
let error = Some(ErrorResponse {
code: response.payment_result_info.result_code.to_string(),
// message vary for the same code, so relying on code alone as it is unique
message: response.payment_result_info.result_code.to_string(),
reason: response.payment_result_info.additional_info,
status_code,
attempt_status: Some(status),
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
});
let payment_response_data = 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((status, error, payment_response_data))
}
fn handle_bank_redirects_sync_response(
response: SyncResponseBankRedirect,
status_code: u16,
) -> CustomResult<
(
enums::AttemptStatus,
Option<ErrorResponse>,
PaymentsResponseData,
),
errors::ConnectorError,
> {
let status = enums::AttemptStatus::from(response.payment_information.status);
let error = if utils::is_payment_failure(status) {
let reason_info = response
.payment_information
.status_reason_information
.unwrap_or_default();
Some(ErrorResponse {
code: reason_info
.reason
.code
.clone()
.unwrap_or(consts::NO_ERROR_CODE.to_string()),
// message vary for the same code, so relying on code alone as it is unique
message: reason_info
.reason
.code
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: reason_info.reason.reject_reason,
status_code,
attempt_status: None,
connector_transaction_id: Some(
response
.payment_information
.references
.payment_request_id
.clone(),
),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
None
};
let payment_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response
.payment_information
.references
.payment_request_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,
};
Ok((status, error, payment_response_data))
}
pub fn handle_webhook_response(
payment_information: WebhookPaymentInformation,
status_code: u16,
) -> CustomResult<
(
enums::AttemptStatus,
Option<ErrorResponse>,
PaymentsResponseData,
),
errors::ConnectorError,
> {
let status = enums::AttemptStatus::try_from(payment_information.status)?;
let error = if utils::is_payment_failure(status) {
let reason_info = payment_information
.status_reason_information
.unwrap_or_default();
Some(ErrorResponse {
code: reason_info
.reason
.code
.clone()
.unwrap_or(consts::NO_ERROR_CODE.to_string()),
// message vary for the same code, so relying on code alone as it is unique
message: reason_info
.reason
.code
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: reason_info.reason.reject_reason,
status_code,
attempt_status: None,
connector_transaction_id: payment_information.references.payment_request_id.clone(),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
None
};
let payment_response_data = 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((status, error, payment_response_data))
}
pub fn get_trustpay_response(
response: TrustpayPaymentsResponse,
status_code: u16,
previous_attempt_status: enums::AttemptStatus,
) -> CustomResult<
(
enums::AttemptStatus,
Option<ErrorResponse>,
PaymentsResponseData,
),
errors::ConnectorError,
> {
match response {
TrustpayPaymentsResponse::CardsPayments(response) => {
handle_cards_response(*response, status_code)
}
TrustpayPaymentsResponse::BankRedirectPayments(response) => {
handle_bank_redirects_response(*response)
}
TrustpayPaymentsResponse::BankRedirectSync(response) => {
handle_bank_redirects_sync_response(*response, status_code)
}
TrustpayPaymentsResponse::BankRedirectError(response) => {
handle_bank_redirects_error_response(*response, status_code, previous_attempt_status)
}
TrustpayPaymentsResponse::WebhookResponse(response) => {
handle_webhook_response(*response, status_code)
}
}
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct TrustpayAuthUpdateRequest {
pub grant_type: String,
}
impl TryFrom<&RefreshTokenRouterData> for TrustpayAuthUpdateRequest {
type Error = Error;
fn try_from(_item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
Ok(Self {
grant_type: "client_credentials".to_string(),
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct ResultInfo {
pub result_code: i64,
pub additional_info: Option<String>,
pub correlation_id: Option<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct TrustpayAuthUpdateResponse {
pub access_token: Option<Secret<String>>,
pub token_type: Option<String>,
pub expires_in: Option<i64>,
#[serde(rename = "ResultInfo")]
pub result_info: ResultInfo,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct TrustpayAccessTokenErrorResponse {
pub result_info: ResultInfo,
}
impl<F, T> TryFrom<ResponseRouterData<F, TrustpayAuthUpdateResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, TrustpayAuthUpdateResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
match (item.response.access_token, item.response.expires_in) {
(Some(access_token), Some(expires_in)) => Ok(Self {
response: Ok(AccessToken {
token: access_token,
expires: expires_in,
}),
..item.data
}),
_ => Ok(Self {
response: Err(ErrorResponse {
code: item.response.result_info.result_code.to_string(),
// message vary for the same code, so relying on code alone as it is unique
message: item.response.result_info.result_code.to_string(),
reason: item.response.result_info.additional_info,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
..item.data
}),
}
}
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TrustpayCreateIntentRequest {
pub amount: StringMajorUnit,
pub currency: String,
// If true, Apple Pay will be initialized
pub init_apple_pay: Option<bool>,
// If true, Google pay will be initialized
pub init_google_pay: Option<bool>,
pub reference: String,
}
impl TryFrom<&TrustpayRouterData<&PaymentsPreProcessingRouterData>>
for TrustpayCreateIntentRequest
{
type Error = Error;
fn try_from(
item: &TrustpayRouterData<&PaymentsPreProcessingRouterData>,
) -> Result<Self, Self::Error> {
let is_apple_pay = item
.router_data
.request
.payment_method_type
.as_ref()
.map(|pmt| matches!(pmt, enums::PaymentMethodType::ApplePay));
let is_google_pay = item
.router_data
.request
.payment_method_type
.as_ref()
.map(|pmt| matches!(pmt, enums::PaymentMethodType::GooglePay));
let currency = item.router_data.request.get_currency()?;
let amount = item.amount.to_owned();
Ok(Self {
amount,
currency: currency.to_string(),
init_apple_pay: is_apple_pay,
init_google_pay: is_google_pay,
reference: item.router_data.connector_request_reference_id.clone(),
})
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TrustpayCreateIntentResponse {
// TrustPay's authorization secrets used by client
pub secrets: SdkSecretInfo,
// Data object to be used for Apple Pay or Google Pay
#[serde(flatten)]
pub init_result_data: InitResultData,
// Unique operation/transaction identifier
pub instance_id: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum InitResultData {
AppleInitResultData(TrustpayApplePayResponse),
GoogleInitResultData(TrustpayGooglePayResponse),
}
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayTransactionInfo {
pub country_code: api_models::enums::CountryAlpha2,
pub currency_code: api_models::enums::Currency,
pub total_price_status: String,
pub total_price: StringMajorUnit,
}
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayMerchantInfo {
pub merchant_name: Secret<String>,
pub merchant_id: Secret<String>,
}
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayAllowedPaymentMethods {
#[serde(rename = "type")]
pub payment_method_type: String,
pub parameters: GpayAllowedMethodsParameters,
pub tokenization_specification: GpayTokenizationSpecification,
}
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GpayTokenParameters {
pub gateway: String,
pub gateway_merchant_id: Secret<String>,
}
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GpayTokenizationSpecification {
#[serde(rename = "type")]
pub token_specification_type: String,
pub parameters: GpayTokenParameters,
}
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GpayAllowedMethodsParameters {
pub allowed_auth_methods: Vec<String>,
pub allowed_card_networks: Vec<String>,
pub assurance_details_required: Option<bool>,
}
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TrustpayGooglePayResponse {
pub merchant_info: GooglePayMerchantInfo,
pub allowed_payment_methods: Vec<GooglePayAllowedPaymentMethods>,
pub transaction_info: GooglePayTransactionInfo,
}
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SdkSecretInfo {
pub display: Secret<String>,
pub payment: Secret<String>,
}
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TrustpayApplePayResponse {
pub country_code: api_models::enums::CountryAlpha2,
pub currency_code: api_models::enums::Currency,
pub supported_networks: Vec<String>,
pub merchant_capabilities: Vec<String>,
pub total: ApplePayTotalInfo,
}
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayTotalInfo {
pub label: String,
pub amount: StringMajorUnit,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
TrustpayCreateIntentResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<
F,
TrustpayCreateIntentResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let create_intent_response = item.response.init_result_data.to_owned();
let secrets = item.response.secrets.to_owned();
let instance_id = item.response.instance_id.to_owned();
let pmt = PaymentsPreProcessingData::get_payment_method_type(&item.data.request)?;
match (pmt, create_intent_response) {
(
enums::PaymentMethodType::ApplePay,
InitResultData::AppleInitResultData(apple_pay_response),
) => get_apple_pay_session(instance_id, &secrets, apple_pay_response, item),
(
enums::PaymentMethodType::GooglePay,
InitResultData::GoogleInitResultData(google_pay_response),
) => get_google_pay_session(instance_id, &secrets, google_pay_response, item),
_ => Err(report!(errors::ConnectorError::InvalidWallet)),
}
}
}
pub fn get_apple_pay_session<F, T>(
instance_id: String,
secrets: &SdkSecretInfo,
apple_pay_init_result: TrustpayApplePayResponse,
item: ResponseRouterData<F, TrustpayCreateIntentResponse, T, PaymentsResponseData>,
) -> Result<RouterData<F, T, PaymentsResponseData>, error_stack::Report<errors::ConnectorError>> {
Ok(RouterData {
response: Ok(PaymentsResponseData::PreProcessingResponse {
connector_metadata: None,
pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(instance_id),
session_token: Some(SessionToken::ApplePay(Box::new(
api_models::payments::ApplepaySessionTokenResponse {
session_token_data: Some(
api_models::payments::ApplePaySessionResponse::ThirdPartySdk(
api_models::payments::ThirdPartySdkSessionResponse {
secrets: secrets.to_owned().into(),
},
),
),
payment_request_data: Some(api_models::payments::ApplePayPaymentRequest {
country_code: apple_pay_init_result.country_code,
currency_code: apple_pay_init_result.currency_code,
supported_networks: Some(apple_pay_init_result.supported_networks.clone()),
merchant_capabilities: Some(
apple_pay_init_result.merchant_capabilities.clone(),
),
total: apple_pay_init_result.total.into(),
merchant_identifier: None,
required_billing_contact_fields: None,
required_shipping_contact_fields: None,
recurring_payment_request: None,
}),
connector: "trustpay".to_string(),
delayed_session_token: true,
sdk_next_action: {
api_models::payments::SdkNextAction {
next_action: api_models::payments::NextActionCall::Sync,
}
},
connector_reference_id: None,
connector_sdk_public_key: None,
connector_merchant_id: None,
},
))),
connector_response_reference_id: None,
}),
// We don't get status from TrustPay but status should be AuthenticationPending by default for session response
status: enums::AttemptStatus::AuthenticationPending,
..item.data
})
}
pub fn get_google_pay_session<F, T>(
instance_id: String,
secrets: &SdkSecretInfo,
google_pay_init_result: TrustpayGooglePayResponse,
item: ResponseRouterData<F, TrustpayCreateIntentResponse, T, PaymentsResponseData>,
) -> Result<RouterData<F, T, PaymentsResponseData>, error_stack::Report<errors::ConnectorError>> {
Ok(RouterData {
response: Ok(PaymentsResponseData::PreProcessingResponse {
connector_metadata: None,
pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(instance_id),
session_token: Some(SessionToken::GooglePay(Box::new(
api_models::payments::GpaySessionTokenResponse::GooglePaySession(
api_models::payments::GooglePaySessionResponse {
connector: "trustpay".to_string(),
delayed_session_token: true,
sdk_next_action: {
api_models::payments::SdkNextAction {
next_action: api_models::payments::NextActionCall::Sync,
}
},
merchant_info: google_pay_init_result.merchant_info.into(),
allowed_payment_methods: google_pay_init_result
.allowed_payment_methods
.into_iter()
.map(Into::into)
.collect(),
transaction_info: google_pay_init_result.transaction_info.into(),
secrets: Some((*secrets).clone().into()),
shipping_address_required: false,
email_required: false,
shipping_address_parameters:
api_models::payments::GpayShippingAddressParameters {
phone_number_required: false,
},
},
),
))),
connector_response_reference_id: None,
}),
// We don't get status from TrustPay but status should be AuthenticationPending by default for session response
status: enums::AttemptStatus::AuthenticationPending,
..item.data
})
}
impl From<GooglePayTransactionInfo> for api_models::payments::GpayTransactionInfo {
fn from(value: GooglePayTransactionInfo) -> Self {
Self {
country_code: value.country_code,
currency_code: value.currency_code,
total_price_status: value.total_price_status,
total_price: value.total_price,
}
}
}
impl From<GooglePayMerchantInfo> for api_models::payments::GpayMerchantInfo {
fn from(value: GooglePayMerchantInfo) -> Self {
Self {
merchant_id: Some(value.merchant_id.expose()),
merchant_name: value.merchant_name.expose(),
}
}
}
impl From<GooglePayAllowedPaymentMethods> for api_models::payments::GpayAllowedPaymentMethods {
fn from(value: GooglePayAllowedPaymentMethods) -> Self {
Self {
payment_method_type: value.payment_method_type,
parameters: value.parameters.into(),
tokenization_specification: value.tokenization_specification.into(),
}
}
}
impl From<GpayAllowedMethodsParameters> for api_models::payments::GpayAllowedMethodsParameters {
fn from(value: GpayAllowedMethodsParameters) -> Self {
Self {
allowed_auth_methods: value.allowed_auth_methods,
allowed_card_networks: value.allowed_card_networks,
billing_address_required: None,
billing_address_parameters: None,
assurance_details_required: value.assurance_details_required,
}
}
}
impl From<GpayTokenizationSpecification> for api_models::payments::GpayTokenizationSpecification {
fn from(value: GpayTokenizationSpecification) -> Self {
Self {
token_specification_type: value.token_specification_type,
parameters: value.parameters.into(),
}
}
}
impl From<GpayTokenParameters> for api_models::payments::GpayTokenParameters {
fn from(value: GpayTokenParameters) -> Self {
Self {
gateway: Some(value.gateway),
gateway_merchant_id: Some(value.gateway_merchant_id.expose()),
stripe_version: None,
stripe_publishable_key: None,
public_key: None,
protocol_version: None,
}
}
}
impl From<SdkSecretInfo> for api_models::payments::SecretInfoToInitiateSdk {
fn from(value: SdkSecretInfo) -> Self {
Self {
display: value.display,
payment: value.payment,
}
}
}
impl From<ApplePayTotalInfo> for api_models::payments::AmountInfo {
fn from(value: ApplePayTotalInfo) -> Self {
Self {
label: value.label,
amount: value.amount,
total_type: None,
}
}
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TrustpayRefundRequestCards {
instance_id: String,
amount: StringMajorUnit,
currency: String,
reference: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TrustpayRefundRequestBankRedirect {
pub merchant_identification: MerchantIdentification,
pub payment_information: BankPaymentInformation,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum TrustpayRefundRequest {
CardsRefund(Box<TrustpayRefundRequestCards>),
BankRedirectRefund(Box<TrustpayRefundRequestBankRedirect>),
}
impl<F> TryFrom<&TrustpayRouterData<&RefundsRouterData<F>>> for TrustpayRefundRequest {
type Error = Error;
fn try_from(item: &TrustpayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let amount = item.amount.to_owned();
match item.router_data.payment_method {
enums::PaymentMethod::BankRedirect => {
let auth = TrustpayAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(Self::BankRedirectRefund(Box::new(
TrustpayRefundRequestBankRedirect {
merchant_identification: MerchantIdentification {
project_id: auth.project_id,
},
payment_information: BankPaymentInformation {
amount: Amount {
amount,
currency: item.router_data.request.currency.to_string(),
},
references: References {
merchant_reference: item.router_data.request.refund_id.clone(),
},
debtor: None,
},
},
)))
}
_ => Ok(Self::CardsRefund(Box::new(TrustpayRefundRequestCards {
instance_id: item.router_data.request.connector_transaction_id.clone(),
amount,
currency: item.router_data.request.currency.to_string(),
reference: item.router_data.request.refund_id.clone(),
}))),
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardsRefundResponse {
pub status: i64,
pub description: Option<String>,
pub instance_id: String,
pub payment_status: String,
pub payment_description: Option<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct BankRedirectRefundResponse {
pub payment_request_id: i64,
pub result_info: ResultInfo,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RefundResponse {
CardsRefund(Box<CardsRefundResponse>),
WebhookRefund(Box<WebhookPaymentInformation>),
BankRedirectRefund(Box<BankRedirectRefundResponse>),
BankRedirectRefundSyncResponse(Box<SyncResponseBankRedirect>),
BankRedirectError(Box<ErrorResponseBankRedirect>),
}
fn handle_cards_refund_response(
response: CardsRefundResponse,
status_code: u16,
) -> CustomResult<(Option<ErrorResponse>, RefundsResponseData), errors::ConnectorError> {
let (refund_status, msg) = get_refund_status(&response.payment_status)?;
let error = if msg.is_some() {
Some(ErrorResponse {
code: response.payment_status,
message: msg
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: msg,
status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
None
};
let refund_response_data = RefundsResponseData {
connector_refund_id: response.instance_id,
refund_status,
};
Ok((error, refund_response_data))
}
fn handle_webhooks_refund_response(
response: WebhookPaymentInformation,
status_code: u16,
) -> CustomResult<(Option<ErrorResponse>, RefundsResponseData), errors::ConnectorError> {
let refund_status = enums::RefundStatus::try_from(response.status)?;
let error = if utils::is_refund_failure(refund_status) {
let reason_info = response.status_reason_information.unwrap_or_default();
Some(ErrorResponse {
code: reason_info
.reason
.code
.clone()
.unwrap_or(consts::NO_ERROR_CODE.to_string()),
// message vary for the same code, so relying on code alone as it is unique
message: reason_info
.reason
.code
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: reason_info.reason.reject_reason,
status_code,
attempt_status: None,
connector_transaction_id: response.references.payment_request_id.clone(),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
None
};
let refund_response_data = RefundsResponseData {
connector_refund_id: response
.references
.payment_request_id
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?,
refund_status,
};
Ok((error, refund_response_data))
}
fn handle_bank_redirects_refund_response(
response: BankRedirectRefundResponse,
status_code: u16,
) -> (Option<ErrorResponse>, RefundsResponseData) {
let (refund_status, msg) = get_refund_status_from_result_info(response.result_info.result_code);
let error = if msg.is_some() {
Some(ErrorResponse {
code: response.result_info.result_code.to_string(),
// message vary for the same code, so relying on code alone as it is unique
message: response.result_info.result_code.to_string(),
reason: msg.map(|message| message.to_string()),
status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
None
};
let refund_response_data = RefundsResponseData {
connector_refund_id: response.payment_request_id.to_string(),
refund_status,
};
(error, refund_response_data)
}
fn handle_bank_redirects_refund_sync_response(
response: SyncResponseBankRedirect,
status_code: u16,
) -> (Option<ErrorResponse>, RefundsResponseData) {
let refund_status = enums::RefundStatus::from(response.payment_information.status);
let error = if utils::is_refund_failure(refund_status) {
let reason_info = response
.payment_information
.status_reason_information
.unwrap_or_default();
Some(ErrorResponse {
code: reason_info
.reason
.code
.clone()
.unwrap_or(consts::NO_ERROR_CODE.to_string()),
// message vary for the same code, so relying on code alone as it is unique
message: reason_info
.reason
.code
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: reason_info.reason.reject_reason,
status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
None
};
let refund_response_data = RefundsResponseData {
connector_refund_id: response.payment_information.references.payment_request_id,
refund_status,
};
(error, refund_response_data)
}
fn handle_bank_redirects_refund_sync_error_response(
response: ErrorResponseBankRedirect,
status_code: u16,
) -> (Option<ErrorResponse>, RefundsResponseData) {
let error = Some(ErrorResponse {
code: response.payment_result_info.result_code.to_string(),
// message vary for the same code, so relying on code alone as it is unique
message: response.payment_result_info.result_code.to_string(),
reason: response.payment_result_info.additional_info,
status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
});
//unreachable case as we are sending error as Some()
let refund_response_data = RefundsResponseData {
connector_refund_id: "".to_string(),
refund_status: enums::RefundStatus::Failure,
};
(error, refund_response_data)
}
impl<F> TryFrom<RefundsResponseRouterData<F, RefundResponse>> for RefundsRouterData<F> {
type Error = Error;
fn try_from(item: RefundsResponseRouterData<F, RefundResponse>) -> Result<Self, Self::Error> {
let (error, response) = match item.response {
RefundResponse::CardsRefund(response) => {
handle_cards_refund_response(*response, item.http_code)?
}
RefundResponse::WebhookRefund(response) => {
handle_webhooks_refund_response(*response, item.http_code)?
}
RefundResponse::BankRedirectRefund(response) => {
handle_bank_redirects_refund_response(*response, item.http_code)
}
RefundResponse::BankRedirectRefundSyncResponse(response) => {
handle_bank_redirects_refund_sync_response(*response, item.http_code)
}
RefundResponse::BankRedirectError(response) => {
handle_bank_redirects_refund_sync_error_response(*response, item.http_code)
}
};
Ok(Self {
response: error.map_or_else(|| Ok(response), Err),
..item.data
})
}
}
fn get_refund_status(
payment_status: &str,
) -> CustomResult<(enums::RefundStatus, Option<String>), errors::ConnectorError> {
let (is_failed, failure_message) = is_payment_failed(payment_status);
if payment_status == "000.200.000" {
Ok((enums::RefundStatus::Pending, None))
} else if is_failed {
Ok((
enums::RefundStatus::Failure,
Some(failure_message.to_string()),
))
} else if is_payment_successful(payment_status)? {
Ok((enums::RefundStatus::Success, None))
} else {
Ok((enums::RefundStatus::Pending, None))
}
}
fn get_refund_status_from_result_info(
result_code: i64,
) -> (enums::RefundStatus, Option<&'static str>) {
match result_code {
1001000 => (enums::RefundStatus::Success, None),
1130001 => (enums::RefundStatus::Pending, Some("MapiPending")),
1130000 => (enums::RefundStatus::Pending, Some("MapiSuccess")),
1130004 => (enums::RefundStatus::Pending, Some("MapiProcessing")),
1130002 => (enums::RefundStatus::Pending, Some("MapiAnnounced")),
1130003 => (enums::RefundStatus::Pending, Some("MapiAuthorized")),
1130005 => (enums::RefundStatus::Pending, Some("MapiAuthorizedOnly")),
1112008 => (enums::RefundStatus::Failure, Some("InvalidPaymentState")),
1112009 => (enums::RefundStatus::Failure, Some("RefundRejected")),
1122006 => (
enums::RefundStatus::Failure,
Some("AccountCurrencyNotAllowed"),
),
1132000 => (enums::RefundStatus::Failure, Some("InvalidMapiRequest")),
1132001 => (enums::RefundStatus::Failure, Some("UnknownAccount")),
1132002 => (
enums::RefundStatus::Failure,
Some("MerchantAccountDisabled"),
),
1132003 => (enums::RefundStatus::Failure, Some("InvalidSign")),
1132004 => (enums::RefundStatus::Failure, Some("DisposableBalance")),
1132005 => (enums::RefundStatus::Failure, Some("TransactionNotFound")),
1132006 => (enums::RefundStatus::Failure, Some("UnsupportedTransaction")),
1132007 => (enums::RefundStatus::Failure, Some("GeneralMapiError")),
1132008 => (
enums::RefundStatus::Failure,
Some("UnsupportedCurrencyConversion"),
),
1132009 => (enums::RefundStatus::Failure, Some("UnknownMandate")),
1132010 => (enums::RefundStatus::Failure, Some("CanceledMandate")),
1132011 => (enums::RefundStatus::Failure, Some("MissingCid")),
1132012 => (enums::RefundStatus::Failure, Some("MandateAlreadyPaid")),
1132013 => (enums::RefundStatus::Failure, Some("AccountIsTesting")),
1132014 => (enums::RefundStatus::Failure, Some("RequestThrottled")),
1133000 => (enums::RefundStatus::Failure, Some("InvalidAuthentication")),
1133001 => (enums::RefundStatus::Failure, Some("ServiceNotAllowed")),
1133002 => (enums::RefundStatus::Failure, Some("PaymentRequestNotFound")),
1133003 => (enums::RefundStatus::Failure, Some("UnexpectedGateway")),
1133004 => (enums::RefundStatus::Failure, Some("MissingExternalId")),
1152000 => (enums::RefundStatus::Failure, Some("RiskDecline")),
_ => (enums::RefundStatus::Pending, None),
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct TrustpayRedirectResponse {
pub status: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct Errors {
pub code: i64,
pub description: String,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TrustpayErrorResponse {
pub status: i64,
pub description: Option<String>,
pub errors: Option<Vec<Errors>>,
pub instance_id: Option<String>,
pub payment_description: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum CreditDebitIndicator {
Crdt,
Dbit,
}
#[derive(strum::Display, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum WebhookStatus {
Paid,
Rejected,
Refunded,
Chargebacked,
#[serde(other)]
Unknown,
}
impl TryFrom<WebhookStatus> for enums::AttemptStatus {
type Error = errors::ConnectorError;
fn try_from(item: WebhookStatus) -> Result<Self, Self::Error> {
match item {
WebhookStatus::Paid => Ok(Self::Charged),
WebhookStatus::Rejected => Ok(Self::AuthorizationFailed),
_ => Err(errors::ConnectorError::WebhookEventTypeNotFound),
}
}
}
impl TryFrom<WebhookStatus> for enums::RefundStatus {
type Error = errors::ConnectorError;
fn try_from(item: WebhookStatus) -> Result<Self, Self::Error> {
match item {
WebhookStatus::Paid => Ok(Self::Success),
WebhookStatus::Refunded => Ok(Self::Success),
WebhookStatus::Rejected => Ok(Self::Failure),
_ => Err(errors::ConnectorError::WebhookEventTypeNotFound),
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct WebhookReferences {
pub merchant_reference: String,
pub payment_id: Option<String>,
pub payment_request_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct WebhookAmount {
pub amount: f64,
pub currency: enums::Currency,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct WebhookPaymentInformation {
pub credit_debit_indicator: CreditDebitIndicator,
pub references: WebhookReferences,
pub status: WebhookStatus,
pub amount: WebhookAmount,
pub status_reason_information: Option<StatusReasonInformation>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct TrustpayWebhookResponse {
pub payment_information: WebhookPaymentInformation,
pub signature: String,
}
impl From<Errors> for utils::ErrorCodeAndMessage {
fn from(error: Errors) -> Self {
Self {
error_code: error.code.to_string(),
error_message: error.description,
}
}
}
| 15,691 | 2,238 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs | .rs | use common_enums::enums;
use common_utils::{
pii::{self, Email},
types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, UpiCollectData, UpiData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::{
configs::Connectors,
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::generate_12_digit_number,
};
pub struct RazorpayRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(FloatMajorUnit, T)> for RazorpayRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (FloatMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
pub const VERSION: i32 = 1;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RazorpayPaymentsRequest {
second_factor: SecondFactor,
merchant_account: MerchantAccount,
order_reference: OrderReference,
txn_detail: TxnDetail,
txn_card_info: TxnCardInfo,
merchant_gateway_account: MerchantGatewayAccount,
gateway: Gateway,
transaction_create_req: TransactionCreateReq,
is_mesh_enabled: bool,
order_metadata_v2: OrderMetadataV2,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SecondFactor {
txn_id: String,
id: String,
status: SecondFactorStatus,
#[serde(rename = "type")]
sf_type: SecondFactorType,
version: i32,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
date_created: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
last_updated: Option<PrimitiveDateTime>,
transaction_id: Option<String>,
url: Option<String>,
epg_txn_id: Option<String>,
transaction_detail_id: Option<String>,
gateway_auth_required_params: Option<String>,
authentication_account_id: Option<String>,
can_accept_response: Option<bool>,
challenges_attempted: Option<i32>,
response_attempted: Option<i32>,
partition_key: Option<String>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SecondFactorType {
Otp,
#[default]
Vbv,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SecondFactorStatus {
Pending,
#[default]
Init,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MerchantAccount {
id: u64,
merchant_id: Secret<String>,
use_code_for_gateway_priority: bool,
auto_refund_multiple_charged_transactions: bool,
gateway_success_rate_based_outage_input: Option<String>,
gateway_success_rate_based_decider_input: Option<String>,
card_encoding_key: Option<String>,
enable_unauthenticated_order_status_api: Option<bool>,
enabled_instant_refund: Option<bool>,
enable_reauthentication: Option<bool>,
return_url: Option<String>,
credit_balance: Option<i64>,
internal_metadata: Option<String>,
gateway_decided_by_health_enabled: Option<bool>,
zip: Option<String>,
enable_3d_secure_help_mail: Option<String>,
payout_mid: Option<String>,
gateway_priority_logic: Option<String>,
enable_success_rate_based_gateway_elimination: Option<bool>,
otp_enabled: Option<bool>,
enable_sending_card_isin: Option<bool>,
state: Option<String>,
must_use_given_order_id_for_txn: Option<bool>,
gateway_priority: Option<String>,
timezone: Option<String>,
user_id: Option<i64>,
office_line_1: Option<String>,
enable_save_card_before_auth: Option<bool>,
office_line_2: Option<String>,
merchant_legal_name: Option<String>,
settlement_account_id: Option<i64>,
external_metadata: Option<String>,
office_line_3: Option<String>,
enable_payment_response_hash: Option<bool>,
prefix_merchant_id_for_card_key: Option<bool>,
admin_contact_email: Option<String>,
enable_reauthorization: Option<bool>,
locker_id: Option<String>,
enable_recapture: Option<bool>,
contact_person_email: Option<String>,
basilisk_key_id: Option<String>,
whitelabel_enabled: Option<bool>,
inline_checkout_enabled: Option<bool>,
payu_merchant_key: Option<String>,
encryption_key_ids: Option<String>,
enable_gateway_reference_id_based_routing: Option<bool>,
enabled: Option<bool>,
enable_automatic_retry: Option<bool>,
about_business: Option<String>,
redirect_to_merchant_with_http_post: Option<bool>,
webhook_api_version: Option<String>,
express_checkout_enabled: Option<bool>,
city: Option<String>,
webhook_url: Option<String>,
webhook_username: Option<String>,
webhook_custom_headers: Option<String>,
reverse_token_enabled: Option<bool>,
webhook_configs: Option<String>,
last_modified: Option<String>,
network_token_locker_id: Option<String>,
enable_sending_last_four_digits: Option<bool>,
website: Option<String>,
mobile: Option<String>,
webhook_password: Option<String>,
reseller_id: Option<String>,
mobile_version: Option<String>,
contact_person_primary: Option<String>,
conflict_status_email: Option<String>,
payu_test_mode: Option<bool>,
payment_response_hash_key: Option<String>,
enable_refunds_in_dashboard: Option<bool>,
tenant_account_id: Option<String>,
merchant_name: Option<String>,
hdfc_test_mode: Option<bool>,
enable_unauthenticated_card_add: Option<bool>,
payu_salt: Option<String>,
api_key: Option<String>,
date_created: Option<String>,
internal_hash_key: Option<String>,
version: Option<i32>,
mandatory_2fa: Option<bool>,
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct OrderReference {
id: String,
amount: FloatMajorUnit,
currency: String,
order_id: String,
status: OrderStatus,
merchant_id: Secret<String>,
order_uuid: String,
order_type: OrderType,
version: i32,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
date_created: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
last_modified: Option<PrimitiveDateTime>,
return_url: Option<String>,
billing_address_id: Option<String>,
internal_metadata: Option<String>,
mandate_feature: Option<MandateFeature>,
udf6: Option<String>,
udf1: Option<String>,
partition_key: Option<String>,
amount_refunded: Option<FloatMajorUnit>,
customer_phone: Option<String>,
description: Option<String>,
customer_email: Option<Email>,
customer_id: Option<String>,
refunded_entirely: Option<bool>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum OrderType {
MandatePayment,
#[default]
OrderPayment,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum MandateFeature {
Disabled,
Required,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum OrderStatus {
Success,
#[default]
PendingAuthentication,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TxnDetail {
status: TxnStatus,
merchant_id: Secret<String>,
txn_id: String,
express_checkout: bool,
is_emi: bool,
net_amount: FloatMajorUnit,
txn_amount: FloatMajorUnit,
emi_tenure: i32,
txn_uuid: String,
currency: String,
version: i32,
redirect: bool,
id: String,
#[serde(rename = "type")]
txn_type: TxnType,
order_id: String,
add_to_locker: bool,
merchant_gateway_account_id: u64,
txn_mode: TxnMode,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
date_created: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
last_modified: Option<PrimitiveDateTime>,
gateway: Gateway,
internal_metadata: Option<String>,
txn_flow_type: Option<String>,
source_object: Option<String>,
partition_key: Option<String>,
username: Option<String>,
txn_object_type: Option<String>,
internal_tracking_info: Option<String>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TxnType {
AuthAndSettle,
#[default]
PreAuthAndSettle,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TxnMode {
Prod,
#[default]
Test,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TxnCardInfo {
txn_detail_id: String,
txn_id: String,
payment_method_type: String,
id: String,
payment_method: String,
payment_source: Secret<String, pii::UpiVpaMaskingStrategy>,
date_created: Option<PrimitiveDateTime>,
partition_key: Option<String>,
card_type: Option<String>,
card_issuer_bank_name: Option<String>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MerchantGatewayAccount {
merchant_id: Secret<String>,
gateway: Gateway,
account_details: String,
version: i32,
id: u64,
test_mode: bool,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
date_created: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
last_modified: Option<PrimitiveDateTime>,
disabled: bool,
payment_methods: Option<String>,
enforce_payment_method_acceptance: Option<bool>,
supported_payment_flows: Option<String>,
is_juspay_account: Option<bool>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct TransactionCreateReq {
merchant_id: Secret<String>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct OrderMetadataV2 {
id: String,
order_reference_id: String,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
date_created: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
last_updated: Option<PrimitiveDateTime>,
browser: Option<String>,
operating_system: Option<String>,
ip_address: Option<String>,
partition_key: Option<String>,
user_agent: Option<String>,
browser_version: Option<String>,
mobile: Option<String>,
metadata: Option<String>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Gateway {
#[default]
Razorpay,
YesBiz,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct RazorpayCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl
TryFrom<(
&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>,
&Connectors,
)> for RazorpayPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, data): (
&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>,
&Connectors,
),
) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
let txn_card_info = match request.payment_method_data.clone() {
PaymentMethodData::Upi(upi_type) => match upi_type {
UpiData::UpiCollect(upi_data) => TxnCardInfo::try_from((item, upi_data)),
UpiData::UpiIntent(_) => Err(errors::ConnectorError::NotImplemented(
"Payment methods".to_string(),
)
.into()),
},
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into())
}
}?;
let merchant_data = JuspayAuthData::try_from(data)?;
let second_factor = SecondFactor::try_from(item)?;
let merchant_account = MerchantAccount::try_from((item, data))?;
let order_reference = OrderReference::try_from((item, data))?;
let txn_detail = TxnDetail::try_from((item, data))?;
let merchant_gateway_account = MerchantGatewayAccount::try_from((item, data))?;
let gateway = Gateway::Razorpay;
let transaction_create_req = TransactionCreateReq {
merchant_id: merchant_data.merchant_id,
};
let is_mesh_enabled = false;
let order_metadata_v2 = OrderMetadataV2::try_from(item)?;
Ok(Self {
second_factor,
merchant_account,
order_reference,
txn_detail,
txn_card_info,
merchant_gateway_account,
gateway,
transaction_create_req,
is_mesh_enabled,
order_metadata_v2,
})
}
}
impl TryFrom<&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>> for SecondFactor {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RazorpayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let ref_id = generate_12_digit_number();
Ok(Self {
txn_id: item.router_data.connector_request_reference_id.clone(),
id: ref_id.to_string(),
status: SecondFactorStatus::Pending,
version: VERSION,
sf_type: SecondFactorType::Vbv,
date_created: Some(common_utils::date_time::now()),
last_updated: Some(common_utils::date_time::now()),
..Default::default()
})
}
}
impl
TryFrom<(
&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>,
&Connectors,
)> for MerchantAccount
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(_item, data): (
&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>,
&Connectors,
),
) -> Result<Self, Self::Error> {
let merchant_data = JuspayAuthData::try_from(data)?;
let ref_id = generate_12_digit_number();
Ok(Self {
id: ref_id,
merchant_id: merchant_data.merchant_id,
auto_refund_multiple_charged_transactions: false,
use_code_for_gateway_priority: true,
..Default::default()
})
}
}
impl
TryFrom<(
&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>,
&Connectors,
)> for OrderReference
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, data): (
&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>,
&Connectors,
),
) -> Result<Self, Self::Error> {
let ref_id = generate_12_digit_number();
let merchant_data = JuspayAuthData::try_from(data)?;
Ok(Self {
id: ref_id.to_string(),
amount: item.amount,
currency: item.router_data.request.currency.to_string(),
status: OrderStatus::PendingAuthentication,
merchant_id: merchant_data.merchant_id.clone(),
order_id: item.router_data.connector_request_reference_id.clone(),
version: VERSION,
order_type: OrderType::OrderPayment,
order_uuid: uuid::Uuid::new_v4().to_string(),
date_created: Some(common_utils::date_time::now()),
last_modified: Some(common_utils::date_time::now()),
..Default::default()
})
}
}
impl
TryFrom<(
&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>,
UpiCollectData,
)> for TxnCardInfo
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
payment_data: (
&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>,
UpiCollectData,
),
) -> Result<Self, Self::Error> {
let item = payment_data.0;
let upi_data = payment_data.1;
let ref_id = generate_12_digit_number();
let pm = enums::PaymentMethod::Upi;
Ok(Self {
txn_detail_id: ref_id.to_string(),
txn_id: item.router_data.connector_request_reference_id.clone(),
payment_method_type: pm.to_string().to_uppercase(),
id: ref_id.to_string(),
payment_method: pm.to_string().to_uppercase(),
payment_source: upi_data.vpa_id.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "vpa_id",
},
)?,
date_created: Some(common_utils::date_time::now()),
..Default::default()
})
}
}
impl
TryFrom<(
&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>,
&Connectors,
)> for TxnDetail
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, data): (
&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>,
&Connectors,
),
) -> Result<Self, Self::Error> {
let ref_id = generate_12_digit_number();
let merchant_data = JuspayAuthData::try_from(data)?;
let txn_mode: TxnMode = match item.router_data.test_mode {
Some(true) | None => TxnMode::Test,
Some(false) => TxnMode::Prod,
};
Ok(Self {
order_id: item.router_data.connector_request_reference_id.clone(),
express_checkout: false,
txn_mode,
merchant_id: merchant_data.merchant_id,
status: TxnStatus::PendingVbv,
net_amount: item.amount,
txn_id: item.router_data.connector_request_reference_id.clone(),
txn_amount: item.amount,
emi_tenure: 0,
txn_uuid: uuid::Uuid::new_v4().to_string(),
id: ref_id.to_string(),
merchant_gateway_account_id: ref_id,
txn_type: TxnType::AuthAndSettle,
redirect: true,
version: VERSION,
add_to_locker: false,
currency: item.router_data.request.currency.to_string(),
is_emi: false,
gateway: Gateway::Razorpay,
date_created: Some(common_utils::date_time::now()),
last_modified: Some(common_utils::date_time::now()),
..Default::default()
})
}
}
impl
TryFrom<(
&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>,
&Connectors,
)> for MerchantGatewayAccount
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, data): (
&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>,
&Connectors,
),
) -> Result<Self, Self::Error> {
let ref_id = generate_12_digit_number();
let auth = RazorpayAuthType::try_from(&item.router_data.connector_auth_type)?;
let merchant_data = JuspayAuthData::try_from(data)?;
let account_details = AccountDetails {
razorpay_id: auth.razorpay_id.clone(),
razorpay_secret: auth.razorpay_secret,
};
Ok(Self {
merchant_id: merchant_data.merchant_id,
gateway: Gateway::Razorpay,
disabled: false,
id: ref_id,
account_details: serde_json::to_string(&account_details)
.change_context(errors::ConnectorError::ParsingFailed)?,
test_mode: false,
..Default::default()
})
}
}
impl TryFrom<&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>> for OrderMetadataV2 {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
_item: &RazorpayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let ref_id = generate_12_digit_number();
Ok(Self {
id: ref_id.to_string(),
order_reference_id: ref_id.to_string(),
date_created: Some(common_utils::date_time::now()),
last_updated: Some(common_utils::date_time::now()),
..Default::default()
})
}
}
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()),
}
}
}
pub struct JuspayAuthData {
pub(super) merchant_id: Secret<String>,
}
impl TryFrom<&Connectors> for JuspayAuthData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(connector_param: &Connectors) -> Result<Self, Self::Error> {
let Connectors { razorpay, .. } = connector_param;
Ok(Self {
merchant_id: razorpay.merchant_id.clone(),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RazorpayPaymentsResponse {
contents: Contents,
tag: Tag,
code: u16,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Tag {
Stateless,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiMetadata {
ext_api_tag: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Contents {
send_webhook: bool,
second_factor: Option<SecondFactorResponse>,
pgr_response: Option<String>,
api_metadata: ApiMetadata,
pgr_info: PgrInfo,
txn_status: TxnStatus,
#[serde(rename = "updatePGR")]
update_pgr: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SecondFactorResponse {
id: u64,
#[serde(rename = "type")]
sf_type: String,
version: i32,
date_created: String,
last_updated: String,
epg_txn_id: String,
status: String,
txn_id: String,
authentication_account_id: Option<String>,
can_accept_response: Option<bool>,
challenges_attempted: Option<i32>,
gateway_auth_req_params: Option<String>,
partition_key: Option<String>,
response_attempted: Option<i32>,
txn_detail_id: Option<String>,
url: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PgrInfo {
resp_code: String,
resp_message: Option<String>,
response_xml: String,
resptype: Option<String>,
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TxnStatus {
Charged,
Authorizing,
#[default]
PendingVbv,
}
impl From<TxnStatus> for enums::AttemptStatus {
fn from(item: TxnStatus) -> Self {
match item {
TxnStatus::Authorizing => Self::Pending,
TxnStatus::PendingVbv => Self::Failure,
TxnStatus::Charged => Self::Charged,
}
}
}
impl From<enums::AttemptStatus> for TxnStatus {
fn from(item: enums::AttemptStatus) -> Self {
match item {
enums::AttemptStatus::Pending => Self::Authorizing,
enums::AttemptStatus::Failure => Self::PendingVbv,
enums::AttemptStatus::Charged => Self::Charged,
_ => Self::PendingVbv,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, RazorpayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, RazorpayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let second_factor = item.response.contents.second_factor;
let status = enums::AttemptStatus::from(item.response.contents.txn_status);
match second_factor {
Some(second_factor) => Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(second_factor.epg_txn_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(second_factor.txn_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
None => {
let message_code = item
.response
.contents
.pgr_info
.resp_message
.clone()
.unwrap_or(NO_ERROR_MESSAGE.to_string());
Ok(Self {
status,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: item.response.contents.pgr_info.resp_code.clone(),
message: message_code.clone(),
reason: Some(message_code.clone()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
..item.data
})
}
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RazorpayCreateSyncRequest {
txn_detail: TxnDetail,
merchant_gateway_account: MerchantGatewayAccount,
order_reference: OrderReference,
second_factor: SecondFactor,
gateway_txn_data: GatewayTxnData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GatewayTxnData {
id: String,
version: i32,
gateway_data: String,
gateway_status: String,
match_status: String,
txn_detail_id: String,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
date_created: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
last_updated: Option<PrimitiveDateTime>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountDetails {
razorpay_id: Secret<String>,
razorpay_secret: Secret<String>,
}
impl
TryFrom<(
RazorpayRouterData<&types::PaymentsSyncRouterData>,
&Connectors,
)> for RazorpayCreateSyncRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, data): (
RazorpayRouterData<&types::PaymentsSyncRouterData>,
&Connectors,
),
) -> Result<Self, Self::Error> {
let ref_id = generate_12_digit_number();
let auth = RazorpayAuthType::try_from(&item.router_data.connector_auth_type)?;
let merchant_data = JuspayAuthData::try_from(data)?;
let connector_transaction_id = item
.router_data
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
let connector_request_reference_id = &item.router_data.connector_request_reference_id;
let second_factor = SecondFactor {
txn_id: connector_request_reference_id.clone(),
id: ref_id.to_string(),
status: SecondFactorStatus::Pending,
version: VERSION,
sf_type: SecondFactorType::Vbv,
date_created: Some(common_utils::date_time::now()),
last_updated: Some(common_utils::date_time::now()),
epg_txn_id: Some(connector_transaction_id.clone()),
..Default::default()
};
let order_reference = OrderReference {
id: ref_id.to_string(),
amount: item.amount,
currency: item.router_data.request.currency.to_string(),
status: OrderStatus::PendingAuthentication,
merchant_id: merchant_data.merchant_id.clone(),
order_id: connector_request_reference_id.clone(),
version: VERSION,
order_type: OrderType::OrderPayment,
order_uuid: uuid::Uuid::new_v4().to_string(),
date_created: Some(common_utils::date_time::now()),
last_modified: Some(common_utils::date_time::now()),
..Default::default()
};
let txn_mode: TxnMode = match item.router_data.test_mode {
Some(true) | None => TxnMode::Test,
Some(false) => TxnMode::Prod,
};
let txn_detail = TxnDetail {
order_id: connector_request_reference_id.clone(),
express_checkout: false,
txn_mode,
merchant_id: merchant_data.merchant_id.clone(),
status: TxnStatus::from(item.router_data.status),
net_amount: item.amount,
txn_id: connector_request_reference_id.clone(),
txn_amount: item.amount,
emi_tenure: 0,
txn_uuid: uuid::Uuid::new_v4().to_string(),
id: ref_id.to_string(),
merchant_gateway_account_id: 11476,
txn_type: TxnType::AuthAndSettle,
redirect: true,
version: VERSION,
add_to_locker: false,
currency: item.router_data.request.currency.to_string(),
is_emi: false,
gateway: Gateway::Razorpay,
date_created: Some(common_utils::date_time::now()),
last_modified: Some(common_utils::date_time::now()),
..Default::default()
};
let account_details = AccountDetails {
razorpay_id: auth.razorpay_id.clone(),
razorpay_secret: auth.razorpay_secret,
};
let merchant_gateway_account = MerchantGatewayAccount {
gateway: Gateway::Razorpay,
disabled: false,
id: ref_id,
account_details: serde_json::to_string(&account_details)
.change_context(errors::ConnectorError::ParsingFailed)?,
test_mode: false,
merchant_id: merchant_data.merchant_id,
..Default::default()
};
let gateway_txn_data = GatewayTxnData {
id: ref_id.to_string(),
version: VERSION,
gateway_data: "".to_string(),
gateway_status: "S".to_string(),
match_status: "S".to_string(),
txn_detail_id: ref_id.to_string(),
date_created: Some(common_utils::date_time::now()),
last_updated: Some(common_utils::date_time::now()),
};
Ok(Self {
second_factor,
merchant_gateway_account,
order_reference,
txn_detail,
gateway_txn_data,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RazorpaySyncResponse {
status: PsyncStatus,
is_stateful: bool,
second_factor: SecondFactorResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PsyncStatus {
Charged,
Pending,
Authorizing,
}
impl From<PsyncStatus> for enums::AttemptStatus {
fn from(item: PsyncStatus) -> Self {
match item {
PsyncStatus::Charged => Self::Charged,
PsyncStatus::Pending => Self::Pending,
PsyncStatus::Authorizing => Self::Pending,
}
}
}
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> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.second_factor.epg_txn_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.second_factor.txn_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RazorpayRefundRequest {
order_metadata_v2: OrderMetadataV2,
second_factor: SecondFactor,
order_reference: OrderReference,
txn_detail: TxnDetail,
refund: Refund,
payment_gateway_response: PaymentGatewayResponse,
txn_card_info: TxnCardInfo,
merchant_gateway_account: MerchantGatewayAccount,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Refund {
id: u64,
status: RefundStatus,
amount: FloatMajorUnit,
merchant_id: Option<Secret<String>>,
gateway: Gateway,
txn_detail_id: u64,
unique_request_id: String,
processed: bool,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
date_created: Option<PrimitiveDateTime>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundStatus {
Success,
Failure,
#[default]
Pending,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentGatewayResponse {
id: String,
version: i32,
}
impl<F>
TryFrom<(
&RazorpayRouterData<&types::RefundsRouterData<F>>,
&Connectors,
)> for RazorpayRefundRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, data): (
&RazorpayRouterData<&types::RefundsRouterData<F>>,
&Connectors,
),
) -> Result<Self, Self::Error> {
let ref_id = generate_12_digit_number();
let auth = RazorpayAuthType::try_from(&item.router_data.connector_auth_type)?;
let merchant_data = JuspayAuthData::try_from(data)?;
let connector_transaction_id = item.router_data.request.connector_transaction_id.clone();
let connector_request_reference_id = &item.router_data.connector_request_reference_id;
let order_metadata_v2 = OrderMetadataV2 {
id: ref_id.to_string(),
order_reference_id: ref_id.to_string(),
date_created: Some(common_utils::date_time::now()),
last_updated: Some(common_utils::date_time::now()),
..Default::default()
};
let second_factor = SecondFactor {
txn_id: connector_request_reference_id.clone(),
id: ref_id.to_string(),
status: SecondFactorStatus::Pending,
version: VERSION,
sf_type: SecondFactorType::Vbv,
date_created: Some(common_utils::date_time::now()),
last_updated: Some(common_utils::date_time::now()),
epg_txn_id: Some(connector_transaction_id.clone()),
..Default::default()
};
let order_reference = OrderReference {
id: ref_id.to_string(),
amount: item.amount,
currency: item.router_data.request.currency.to_string(),
status: OrderStatus::Success,
merchant_id: merchant_data.merchant_id.clone(),
order_id: connector_request_reference_id.clone(),
version: VERSION,
order_type: OrderType::OrderPayment,
order_uuid: uuid::Uuid::new_v4().to_string(),
date_created: Some(common_utils::date_time::now()),
last_modified: Some(common_utils::date_time::now()),
..Default::default()
};
let txn_mode: TxnMode = match item.router_data.test_mode {
Some(true) | None => TxnMode::Test,
Some(false) => TxnMode::Prod,
};
let txn_detail = TxnDetail {
order_id: connector_request_reference_id.clone(),
express_checkout: false,
txn_mode,
merchant_id: merchant_data.merchant_id.clone(),
status: TxnStatus::from(item.router_data.status),
net_amount: item.amount,
txn_id: connector_request_reference_id.clone(),
txn_amount: item.amount,
emi_tenure: 0,
txn_uuid: uuid::Uuid::new_v4().to_string(),
id: ref_id.to_string(),
merchant_gateway_account_id: 11476,
txn_type: TxnType::AuthAndSettle,
redirect: true,
version: VERSION,
add_to_locker: false,
currency: item.router_data.request.currency.to_string(),
is_emi: false,
gateway: Gateway::Razorpay,
date_created: Some(common_utils::date_time::now()),
last_modified: Some(common_utils::date_time::now()),
..Default::default()
};
let refund = Refund {
id: ref_id,
status: RefundStatus::Pending,
amount: item.amount,
merchant_id: Some(merchant_data.merchant_id.clone()),
gateway: Gateway::Razorpay,
txn_detail_id: ref_id,
unique_request_id: item.router_data.request.refund_id.clone(),
processed: false,
date_created: Some(common_utils::date_time::now()),
};
let payment_gateway_response = PaymentGatewayResponse {
id: ref_id.to_string(),
version: VERSION,
};
let payment_source: Secret<String, pii::UpiVpaMaskingStrategy> =
Secret::new("".to_string());
let pm = enums::PaymentMethod::Upi;
let txn_card_info = TxnCardInfo {
txn_detail_id: ref_id.to_string(),
txn_id: item.router_data.connector_request_reference_id.clone(),
payment_method_type: pm.to_string().to_uppercase(),
id: ref_id.to_string(),
payment_method: pm.to_string().to_uppercase(),
payment_source,
date_created: Some(common_utils::date_time::now()),
..Default::default()
};
let account_details = AccountDetails {
razorpay_id: auth.razorpay_id.clone(),
razorpay_secret: auth.razorpay_secret,
};
let merchant_gateway_account = MerchantGatewayAccount {
gateway: Gateway::Razorpay,
disabled: false,
id: ref_id,
account_details: serde_json::to_string(&account_details)
.change_context(errors::ConnectorError::ParsingFailed)?,
test_mode: false,
merchant_id: merchant_data.merchant_id,
..Default::default()
};
Ok(Self {
order_metadata_v2,
second_factor,
order_reference,
txn_detail,
refund,
payment_gateway_response,
txn_card_info,
merchant_gateway_account,
})
}
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Success => Self::Success,
RefundStatus::Failure => Self::Failure,
RefundStatus::Pending => Self::Pending,
}
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
txn_id: Option<String>,
refund: RefundRes,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundRes {
id: u64,
status: RefundStatus,
amount: FloatMajorUnit,
merchant_id: Option<Secret<String>>,
gateway: Gateway,
txn_detail_id: u64,
unique_request_id: String,
epg_txn_id: Option<String>,
response_code: Option<String>,
error_message: Option<String>,
processed: bool,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
date_created: Option<PrimitiveDateTime>,
}
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 epg_txn_id = item.response.refund.epg_txn_id.clone();
let refund_status = enums::RefundStatus::from(item.response.refund.status);
let response = match epg_txn_id {
Some(epg_txn_id) => Ok(RefundsResponseData {
connector_refund_id: epg_txn_id,
refund_status,
}),
None => Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: item
.response
.refund
.error_message
.clone()
.unwrap_or(NO_ERROR_CODE.to_string()),
message: item
.response
.refund
.response_code
.clone()
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: item.response.refund.response_code.clone(),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.refund.unique_request_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
};
Ok(Self {
response,
..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
.data
.request
.connector_refund_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?,
refund_status: enums::RefundStatus::from(item.response.refund.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum ErrorResponse {
RazorpayErrorResponse(RazorpayErrorResponse),
RazorpayStringError(String),
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct RazorpayErrorResponse {
pub code: u16,
pub error_code: Option<String>,
pub status: String,
pub error: bool,
pub error_message: String,
pub error_info: ErrorInfo,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct ErrorInfo {
pub code: String,
pub user_message: String,
pub developer_message: String,
pub fields: Vec<Fields>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct Fields {
pub field_name: String,
pub reason: String,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum RazorpayWebhookEventType {
Disabled,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RazorpayWebhookEvent {
pub payload: RazorpayWebhookPayload,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RazorpayWebhookPayload {
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: RazorpayRefundStatus,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct WebhookPaymentEntity {
pub id: String,
pub status: RazorpayPaymentStatus,
}
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RazorpayPaymentStatus {
Created,
Authorized,
Captured,
Failed,
Refunded,
}
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RazorpayRefundStatus {
Pending,
Processed,
Failed,
}
impl TryFrom<RazorpayWebhookPayload> for api_models::webhooks::IncomingWebhookEvent {
type Error = errors::ConnectorError;
fn try_from(webhook_payload: RazorpayWebhookPayload) -> Result<Self, Self::Error> {
webhook_payload
.refund
.map_or(
match webhook_payload.payment.entity.status {
RazorpayPaymentStatus::Created => Some(Self::PaymentIntentProcessing),
RazorpayPaymentStatus::Authorized => {
Some(Self::PaymentIntentAuthorizationSuccess)
}
RazorpayPaymentStatus::Captured => Some(Self::PaymentIntentSuccess),
RazorpayPaymentStatus::Failed => Some(Self::PaymentIntentFailure),
RazorpayPaymentStatus::Refunded => None,
},
|refund_data| match refund_data.entity.status {
RazorpayRefundStatus::Pending => None,
RazorpayRefundStatus::Processed => Some(Self::RefundSuccess),
RazorpayRefundStatus::Failed => Some(Self::RefundFailure),
},
)
.ok_or(errors::ConnectorError::WebhookEventTypeNotFound)
}
}
| 10,514 | 2,239 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs | .rs | 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::AmazonPayRedirect(_)
| 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(_) => 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,
}
}
#[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,
}
| 3,256 | 2,240 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs | .rs | use std::collections::HashMap;
use cards::CardNumber;
use common_enums::{enums, PaymentMethod};
use common_utils::{ext_traits::ValueExt, pii::Email, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankDebitData, PaymentMethodData},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
payments::{Authorize, Capture, CompleteAuthorize, PSync},
refunds::{Execute, RSync},
},
router_request_types::{
CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCaptureData, PaymentsSyncData,
ResponseId,
},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{PaymentsCancelResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, RefundsRequestData, RouterData as OtherRouterData,
},
};
pub struct DeutschebankRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for DeutschebankRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub struct DeutschebankAuthType {
pub(super) client_id: Secret<String>,
pub(super) merchant_id: Secret<String>,
pub(super) client_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for DeutschebankAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
client_id: api_key.to_owned(),
merchant_id: key1.to_owned(),
client_key: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct DeutschebankAccessTokenRequest {
pub grant_type: String,
pub client_id: Secret<String>,
pub client_secret: Secret<String>,
pub scope: String,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct DeutschebankAccessTokenResponse {
pub access_token: Secret<String>,
pub expires_in: i64,
pub expires_on: i64,
pub scope: String,
pub token_type: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, DeutschebankAccessTokenResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DeutschebankAccessTokenResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum DeutschebankSEPAApproval {
Click,
Email,
Sms,
Dynamic,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankMandatePostRequest {
approval_by: DeutschebankSEPAApproval,
email_address: Email,
iban: Secret<String>,
first_name: Secret<String>,
last_name: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum DeutschebankPaymentsRequest {
MandatePost(DeutschebankMandatePostRequest),
DirectDebit(DeutschebankDirectDebitRequest),
CreditCard(Box<DeutschebankThreeDSInitializeRequest>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequest {
means_of_payment: DeutschebankThreeDSInitializeRequestMeansOfPayment,
tds_20_data: DeutschebankThreeDSInitializeRequestTds20Data,
amount_total: DeutschebankThreeDSInitializeRequestAmountTotal,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestMeansOfPayment {
credit_card: DeutschebankThreeDSInitializeRequestCreditCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCreditCard {
number: CardNumber,
expiry_date: DeutschebankThreeDSInitializeRequestCreditCardExpiry,
code: Secret<String>,
cardholder: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCreditCardExpiry {
year: Secret<String>,
month: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestAmountTotal {
amount: MinorUnit,
currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestTds20Data {
communication_data: DeutschebankThreeDSInitializeRequestCommunicationData,
customer_data: DeutschebankThreeDSInitializeRequestCustomerData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCommunicationData {
method_notification_url: String,
cres_notification_url: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCustomerData {
billing_address: DeutschebankThreeDSInitializeRequestCustomerBillingData,
cardholder_email: Email,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCustomerBillingData {
street: Secret<String>,
postal_code: Secret<String>,
city: String,
state: Secret<String>,
country: String,
}
impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>>
for DeutschebankPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DeutschebankRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item
.router_data
.request
.mandate_id
.clone()
.and_then(|mandate_id| mandate_id.mandate_reference_id)
{
None => {
// To facilitate one-off payments via SEPA with Deutsche Bank, we are considering not storing the connector mandate ID in our system if future usage is on-session.
// We will only check for customer acceptance to make a one-off payment. we will be storing the connector mandate details only when setup future usage is off-session.
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => {
if item.router_data.request.customer_acceptance.is_some() {
let billing_address = item.router_data.get_billing_address()?;
Ok(Self::MandatePost(DeutschebankMandatePostRequest {
approval_by: DeutschebankSEPAApproval::Click,
email_address: item.router_data.request.get_email()?,
iban: Secret::from(iban.peek().replace(" ", "")),
first_name: billing_address.get_first_name()?.clone(),
last_name: billing_address.get_last_name()?.clone(),
}))
} else {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "customer_acceptance",
}
.into())
}
}
PaymentMethodData::Card(ccard) => {
if !item.router_data.clone().is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Non-ThreeDs".to_owned(),
connector: "deutschebank",
}
.into())
} else {
let billing_address = item.router_data.get_billing_address()?;
Ok(Self::CreditCard(Box::new(DeutschebankThreeDSInitializeRequest {
means_of_payment: DeutschebankThreeDSInitializeRequestMeansOfPayment {
credit_card: DeutschebankThreeDSInitializeRequestCreditCard {
number: ccard.clone().card_number,
expiry_date: DeutschebankThreeDSInitializeRequestCreditCardExpiry {
year: ccard.get_expiry_year_4_digit(),
month: ccard.card_exp_month,
},
code: ccard.card_cvc,
cardholder: item.router_data.get_billing_full_name()?,
}},
amount_total: DeutschebankThreeDSInitializeRequestAmountTotal {
amount: item.amount,
currency: item.router_data.request.currency,
},
tds_20_data: DeutschebankThreeDSInitializeRequestTds20Data {
communication_data: DeutschebankThreeDSInitializeRequestCommunicationData {
method_notification_url: item.router_data.request.get_complete_authorize_url()?,
cres_notification_url: item.router_data.request.get_complete_authorize_url()?,
},
customer_data: DeutschebankThreeDSInitializeRequestCustomerData {
billing_address: DeutschebankThreeDSInitializeRequestCustomerBillingData {
street: billing_address.get_line1()?.clone(),
postal_code: billing_address.get_zip()?.clone(),
city: billing_address.get_city()?.to_string(),
state: billing_address.get_state()?.clone(),
country: item.router_data.get_billing_country()?.to_string(),
},
cardholder_email: item.router_data.request.get_email()?,
}
}
})))
}
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("deutschebank"),
)
.into()),
}
}
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(mandate_data)) => {
let mandate_metadata: DeutschebankMandateMetadata = mandate_data
.get_mandate_metadata()
.ok_or(errors::ConnectorError::MissingConnectorMandateMetadata)?
.clone()
.parse_value("DeutschebankMandateMetadata")
.change_context(errors::ConnectorError::ParsingFailed)?;
Ok(Self::DirectDebit(DeutschebankDirectDebitRequest {
amount_total: DeutschebankAmount {
amount: item.amount,
currency: item.router_data.request.currency,
},
means_of_payment: DeutschebankMeansOfPayment {
bank_account: DeutschebankBankAccount {
account_holder: mandate_metadata.account_holder,
iban: mandate_metadata.iban,
},
},
mandate: DeutschebankMandate {
reference: mandate_metadata.reference,
signed_on: mandate_metadata.signed_on,
},
}))
}
Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_))
| Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => {
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,
}),
..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,
}
}
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),
}
| 8,725 | 2,241 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs | .rs | use common_enums::enums::{self, AuthenticationType};
use common_utils::pii::IpAddress;
use hyperswitch_domain_models::{
payment_method_data::{Card, PaymentMethodData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::Execute,
router_request_types::{
BrowserInformation, PaymentsCancelData, PaymentsCaptureData, ResponseId,
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData as _},
};
const ISO_SUCCESS_CODES: [&str; 7] = ["00", "3D0", "3D1", "HP0", "TK0", "SP4", "FC0"];
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct PowertranzPaymentsRequest {
transaction_identifier: String,
total_amount: f64,
currency_code: String,
three_d_secure: bool,
source: Source,
order_identifier: String,
// billing and shipping are optional fields and requires state in iso codes, hence commenting it
// can be added later if we have iso code for state
// billing_address: Option<PowertranzAddressDetails>,
// shipping_address: Option<PowertranzAddressDetails>,
extended_data: Option<ExtendedData>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct ExtendedData {
three_d_secure: ThreeDSecure,
merchant_response_url: String,
browser_info: BrowserInfo,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct BrowserInfo {
java_enabled: Option<bool>,
javascript_enabled: Option<bool>,
accept_header: Option<String>,
language: Option<String>,
screen_height: Option<String>,
screen_width: Option<String>,
time_zone: Option<String>,
user_agent: Option<String>,
i_p: Option<Secret<String, IpAddress>>,
color_depth: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct ThreeDSecure {
challenge_window_size: u8,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum Source {
Card(PowertranzCard),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct PowertranzCard {
cardholder_name: Secret<String>,
card_pan: cards::CardNumber,
card_expiration: Secret<String>,
card_cvv: Secret<String>,
}
// #[derive(Debug, Serialize)]
// #[serde(rename_all = "PascalCase")]
// pub struct PowertranzAddressDetails {
// first_name: Option<Secret<String>>,
// last_name: Option<Secret<String>>,
// line1: Option<Secret<String>>,
// line2: Option<Secret<String>>,
// city: Option<String>,
// country: Option<enums::CountryAlpha2>,
// state: Option<Secret<String>>,
// postal_code: Option<Secret<String>>,
// email_address: Option<Email>,
// phone_number: Option<Secret<String>>,
// }
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct RedirectResponsePayload {
pub spi_token: Secret<String>,
}
impl TryFrom<&PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let source = match item.request.payment_method_data.clone() {
PaymentMethodData::Card(card) => {
let card_holder_name = item.get_optional_billing_full_name();
Source::try_from((&card, card_holder_name))
}
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::NotSupported {
message: utils::SELECTED_PAYMENT_METHOD.to_string(),
connector: "powertranz",
}
.into())
}
}?;
// let billing_address = get_address_details(&item.address.billing, &item.request.email);
// let shipping_address = get_address_details(&item.address.shipping, &item.request.email);
let (three_d_secure, extended_data) = match item.auth_type {
AuthenticationType::ThreeDs => (true, Some(ExtendedData::try_from(item)?)),
AuthenticationType::NoThreeDs => (false, None),
};
Ok(Self {
transaction_identifier: Uuid::new_v4().to_string(),
total_amount: utils::to_currency_base_unit_asf64(
item.request.amount,
item.request.currency,
)?,
currency_code: item.request.currency.iso_4217().to_string(),
three_d_secure,
source,
order_identifier: item.connector_request_reference_id.clone(),
// billing_address,
// shipping_address,
extended_data,
})
}
}
impl TryFrom<&PaymentsAuthorizeRouterData> for ExtendedData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
Ok(Self {
three_d_secure: ThreeDSecure {
// Merchants preferred sized of challenge window presented to cardholder.
// 5 maps to 100% of challenge window size
challenge_window_size: 5,
},
merchant_response_url: item.request.get_complete_authorize_url()?,
browser_info: BrowserInfo::try_from(&item.request.get_browser_info()?)?,
})
}
}
impl TryFrom<&BrowserInformation> for BrowserInfo {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &BrowserInformation) -> Result<Self, Self::Error> {
Ok(Self {
java_enabled: item.java_enabled,
javascript_enabled: item.java_script_enabled,
accept_header: item.accept_header.clone(),
language: item.language.clone(),
screen_height: item.screen_height.map(|height| height.to_string()),
screen_width: item.screen_width.map(|width| width.to_string()),
time_zone: item.time_zone.map(|zone| zone.to_string()),
user_agent: item.user_agent.clone(),
i_p: item
.ip_address
.map(|ip_address| Secret::new(ip_address.to_string())),
color_depth: item.color_depth.map(|depth| depth.to_string()),
})
}
}
/*fn get_address_details(
address: &Option<Address>,
email: &Option<Email>,
) -> Option<PowertranzAddressDetails> {
let phone_number = address
.as_ref()
.and_then(|address| address.phone.as_ref())
.and_then(|phone| {
phone.number.as_ref().and_then(|number| {
phone.country_code.as_ref().map(|country_code| {
Secret::new(format!("{}{}", country_code, number.clone().expose()))
})
})
});
address
.as_ref()
.and_then(|address| address.address.as_ref())
.map(|address_details| PowertranzAddressDetails {
first_name: address_details.first_name.clone(),
last_name: address_details.last_name.clone(),
line1: address_details.line1.clone(),
line2: address_details.line2.clone(),
city: address_details.city.clone(),
country: address_details.country,
state: address_details.state.clone(),
postal_code: address_details.zip.clone(),
email_address: email.clone(),
phone_number,
})
}*/
impl TryFrom<(&Card, Option<Secret<String>>)> for Source {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(card, card_holder_name): (&Card, Option<Secret<String>>),
) -> Result<Self, Self::Error> {
let card = PowertranzCard {
cardholder_name: card_holder_name.unwrap_or(Secret::new("".to_string())),
card_pan: card.card_number.clone(),
card_expiration: card.get_expiry_date_as_yymm()?,
card_cvv: card.card_cvc.clone(),
};
Ok(Self::Card(card))
}
}
// Auth Struct
pub struct PowertranzAuthType {
pub(super) power_tranz_id: Secret<String>,
pub(super) power_tranz_password: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PowertranzAuthType {
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 {
power_tranz_id: key1.to_owned(),
power_tranz_password: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// Common struct used in Payment, Capture, Void, Refund
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct PowertranzBaseResponse {
transaction_type: u8,
approved: bool,
transaction_identifier: String,
original_trxn_identifier: Option<String>,
errors: Option<Vec<Error>>,
iso_response_code: String,
redirect_data: Option<Secret<String>>,
response_message: String,
order_identifier: String,
}
fn get_status((transaction_type, approved, is_3ds): (u8, bool, bool)) -> enums::AttemptStatus {
match transaction_type {
// Auth
1 => match approved {
true => enums::AttemptStatus::Authorized,
false => match is_3ds {
true => enums::AttemptStatus::AuthenticationPending,
false => enums::AttemptStatus::Failure,
},
},
// Sale
2 => match approved {
true => enums::AttemptStatus::Charged,
false => match is_3ds {
true => enums::AttemptStatus::AuthenticationPending,
false => enums::AttemptStatus::Failure,
},
},
// Capture
3 => match approved {
true => enums::AttemptStatus::Charged,
false => enums::AttemptStatus::Failure,
},
// Void
4 => match approved {
true => enums::AttemptStatus::Voided,
false => enums::AttemptStatus::VoidFailed,
},
// Refund
5 => match approved {
true => enums::AttemptStatus::AutoRefunded,
false => enums::AttemptStatus::Failure,
},
// Risk Management
_ => match approved {
true => enums::AttemptStatus::Pending,
false => enums::AttemptStatus::Failure,
},
}
}
impl<F, T> TryFrom<ResponseRouterData<F, PowertranzBaseResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PowertranzBaseResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let error_response = build_error_response(&item.response, item.http_code);
// original_trxn_identifier will be present only in capture and void
let connector_transaction_id = item
.response
.original_trxn_identifier
.unwrap_or(item.response.transaction_identifier.clone());
let redirection_data = item.response.redirect_data.map(|redirect_data| {
hyperswitch_domain_models::router_response_types::RedirectForm::Html {
html_data: redirect_data.expose(),
}
});
let response = error_response.map_or(
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(connector_transaction_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.order_identifier),
incremental_authorization_allowed: None,
charges: None,
}),
Err,
);
Ok(Self {
status: get_status((
item.response.transaction_type,
item.response.approved,
is_3ds_payment(item.response.iso_response_code),
)),
response,
..item.data
})
}
}
fn is_3ds_payment(response_code: String) -> bool {
matches!(response_code.as_str(), "SP4")
}
// Type definition for Capture, Void, Refund Request
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct PowertranzBaseRequest {
transaction_identifier: String,
total_amount: Option<f64>,
refund: Option<bool>,
}
impl TryFrom<&PaymentsCancelData> for PowertranzBaseRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelData) -> Result<Self, Self::Error> {
Ok(Self {
transaction_identifier: item.connector_transaction_id.clone(),
total_amount: None,
refund: None,
})
}
}
impl TryFrom<&PaymentsCaptureData> for PowertranzBaseRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCaptureData) -> Result<Self, Self::Error> {
let total_amount = Some(utils::to_currency_base_unit_asf64(
item.amount_to_capture,
item.currency,
)?);
Ok(Self {
transaction_identifier: item.connector_transaction_id.clone(),
total_amount,
refund: None,
})
}
}
impl<F> TryFrom<&RefundsRouterData<F>> for PowertranzBaseRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> {
let total_amount = Some(utils::to_currency_base_unit_asf64(
item.request.refund_amount,
item.request.currency,
)?);
Ok(Self {
transaction_identifier: item.request.connector_transaction_id.clone(),
total_amount,
refund: Some(true),
})
}
}
impl TryFrom<RefundsResponseRouterData<Execute, PowertranzBaseResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, PowertranzBaseResponse>,
) -> Result<Self, Self::Error> {
let error_response = build_error_response(&item.response, item.http_code);
let response = error_response.map_or(
Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_identifier.to_string(),
refund_status: match item.response.approved {
true => enums::RefundStatus::Success,
false => enums::RefundStatus::Failure,
},
}),
Err,
);
Ok(Self {
response,
..item.data
})
}
}
fn build_error_response(item: &PowertranzBaseResponse, status_code: u16) -> Option<ErrorResponse> {
// errors object has highest precedence to get error message and code
let error_response = if item.errors.is_some() {
item.errors.as_ref().map(|errors| {
let first_error = errors.first();
let code = first_error.map(|error| error.code.clone());
let message = first_error.map(|error| error.message.clone());
ErrorResponse {
status_code,
code: code.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: message.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: Some(
errors
.iter()
.map(|error| format!("{} : {}", error.code, error.message))
.collect::<Vec<_>>()
.join(", "),
),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}
})
} else if !ISO_SUCCESS_CODES.contains(&item.iso_response_code.as_str()) {
// Incase error object is not present the error message and code should be propagated based on iso_response_code
Some(ErrorResponse {
status_code,
code: item.iso_response_code.clone(),
message: item.response_message.clone(),
reason: Some(item.response_message.clone()),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
None
};
error_response
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PowertranzErrorResponse {
pub errors: Vec<Error>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct Error {
pub code: String,
pub message: String,
}
| 3,837 | 2,242 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs | .rs | 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::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, 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)?;
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, Deserialize)]
pub enum ElavonPaymentsResponse {
#[serde(rename = "txn")]
Success(PaymentResponse),
#[serde(rename = "txn")]
Error(ElavonErrorResponse),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ElavonErrorResponse {
error_code: 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<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, item.data.request.is_auto_capture()?);
let response = match &item.response {
ElavonPaymentsResponse::Error(error) => Err(ErrorResponse {
code: error.error_code.clone(),
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,
}),
ElavonPaymentsResponse::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,
})
} 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, enums::AttemptStatus::Charged);
let response = match &item.response {
ElavonPaymentsResponse::Error(error) => Err(ErrorResponse {
code: error.error_code.clone(),
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,
}),
ElavonPaymentsResponse::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,
})
} 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);
let response = match &item.response {
ElavonPaymentsResponse::Error(error) => Err(ErrorResponse {
code: error.error_code.clone(),
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,
}),
ElavonPaymentsResponse::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,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: response.ssl_txn_id.clone(),
refund_status: enums::RefundStatus::from(&item.response),
})
}
}
};
Ok(Self {
response,
..item.data
})
}
}
trait ElavonResponseValidator {
fn is_successful(&self) -> bool;
}
impl ElavonResponseValidator for ElavonPaymentsResponse {
fn is_successful(&self) -> bool {
matches!(self, Self::Success(response) if response.ssl_result == SslResult::ImportedBatchFile)
}
}
fn map_payment_status(
item: &ElavonPaymentsResponse,
success_status: enums::AttemptStatus,
) -> enums::AttemptStatus {
if item.is_successful() {
success_status
} else {
enums::AttemptStatus::Failure
}
}
impl From<&ElavonPaymentsResponse> for enums::RefundStatus {
fn from(item: &ElavonPaymentsResponse) -> 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: &ElavonPaymentsResponse,
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
}
}
| 4,744 | 2,243 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs | .rs | use common_enums::enums::CaptureMethod;
use common_utils::types::MinorUnit;
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::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<String>,
year: Secret<String>,
}
#[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: req_card.card_exp_month.clone(),
year: req_card.get_expiry_year_4_digit(),
};
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: MerchantSoftware,
merchant_category_code: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantSoftware {
company_name: Secret<String>,
product_name: Secret<String>,
version: Option<Secret<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,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantRefundReq {
pub merchant_software: MerchantSoftware,
}
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> {
Err(errors::ConnectorError::NotImplemented("Refunds".to_string()).into())
}
}
#[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>,
}
#[allow(dead_code)]
#[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,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
pub fn refund_status_from_transaction_state(
transaction_state: JpmorganTransactionState,
) -> common_enums::RefundStatus {
match transaction_state {
JpmorganTransactionState::Voided | JpmorganTransactionState::Closed => {
common_enums::RefundStatus::Success
}
JpmorganTransactionState::Declined | JpmorganTransactionState::Error => {
common_enums::RefundStatus::Failure
}
JpmorganTransactionState::Pending | JpmorganTransactionState::Authorized => {
common_enums::RefundStatus::Pending
}
}
}
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: refund_status_from_transaction_state(
item.response.transaction_state,
),
}),
..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: refund_status_from_transaction_state(
item.response.transaction_state,
),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCancelRequest {
pub amount: Option<i64>,
pub is_void: Option<bool>,
pub reversal_reason: Option<String>,
}
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.clone(),
})
}
}
#[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>,
}
| 5,317 | 2,244 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs | .rs | #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
use std::str::FromStr;
use common_enums::enums;
use common_utils::{errors::CustomResult, ext_traits::ByteSliceExt, pii, types::MinorUnit};
use error_stack::ResultExt;
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
use hyperswitch_domain_models::revenue_recovery;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::{
refunds::{Execute, RSync},
RecoveryRecordBack,
},
router_request_types::{revenue_recovery::RevenueRecoveryRecordBackRequest, ResponseId},
router_response_types::{
revenue_recovery::RevenueRecoveryRecordBackResponse, PaymentsResponseData,
RefundsResponseData,
},
types::{PaymentsAuthorizeRouterData, RefundsRouterData, RevenueRecoveryRecordBackRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, PaymentsAuthorizeRequestData},
};
//TODO: Fill the struct with respective fields
pub struct ChargebeeRouterData<T> {
pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for ChargebeeRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct ChargebeePaymentsRequest {
amount: MinorUnit,
card: ChargebeeCard,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct ChargebeeCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&ChargebeeRouterData<&PaymentsAuthorizeRouterData>> for ChargebeePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ChargebeeRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = ChargebeeCard {
number: req_card.card_number,
expiry_month: req_card.card_exp_month,
expiry_year: req_card.card_exp_year,
cvc: req_card.card_cvc,
complete: item.router_data.request.is_auto_capture()?,
};
Ok(Self {
amount: item.amount,
card,
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
// Auth Struct
pub struct ChargebeeAuthType {
pub(super) full_access_key_v1: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ChargebeeMetadata {
pub(super) site: Secret<String>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for ChargebeeMetadata {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
impl TryFrom<&ConnectorAuthType> for ChargebeeAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
full_access_key_v1: api_key.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
//TODO: Append the remaining status flags
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ChargebeePaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<ChargebeePaymentStatus> for common_enums::AttemptStatus {
fn from(item: ChargebeePaymentStatus) -> Self {
match item {
ChargebeePaymentStatus::Succeeded => Self::Charged,
ChargebeePaymentStatus::Failed => Self::Failure,
ChargebeePaymentStatus::Processing => Self::Authorizing,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ChargebeePaymentsResponse {
status: ChargebeePaymentStatus,
id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, ChargebeePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ChargebeePaymentsResponse, 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 ChargebeeRefundRequest {
pub amount: MinorUnit,
}
impl<F> TryFrom<&ChargebeeRouterData<&RefundsRouterData<F>>> for ChargebeeRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ChargebeeRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct ChargebeeErrorResponse {
pub api_error_code: String,
pub message: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeWebhookBody {
pub content: ChargebeeWebhookContent,
pub event_type: ChargebeeEventType,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeInvoiceBody {
pub content: ChargebeeInvoiceContent,
pub event_type: ChargebeeEventType,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeInvoiceContent {
pub invoice: ChargebeeInvoiceData,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeWebhookContent {
pub transaction: ChargebeeTransactionData,
pub invoice: ChargebeeInvoiceData,
pub customer: Option<ChargebeeCustomer>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeEventType {
PaymentSucceeded,
PaymentFailed,
InvoiceDeleted,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeInvoiceData {
// invoice id
pub id: String,
pub total: MinorUnit,
pub currency_code: enums::Currency,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeTransactionData {
id_at_gateway: Option<String>,
status: ChargebeeTranasactionStatus,
error_code: Option<String>,
error_text: Option<String>,
gateway_account_id: String,
currency_code: enums::Currency,
amount: MinorUnit,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
date: Option<PrimitiveDateTime>,
payment_method: ChargebeeTransactionPaymentMethod,
payment_method_details: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeTransactionPaymentMethod {
Card,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeePaymentMethodDetails {
card: ChargebeeCardDetails,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeCardDetails {
funding_type: ChargebeeFundingType,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeFundingType {
Credit,
Debit,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeTranasactionStatus {
// Waiting for response from the payment gateway.
InProgress,
// The transaction is successful.
Success,
// Transaction failed.
Failure,
// No response received while trying to charge the card.
Timeout,
// Indicates that a successful payment transaction has failed now due to a late failure notification from the payment gateway,
// typically caused by issues like insufficient funds or a closed bank account.
LateFailure,
// Connection with Gateway got terminated abruptly. So, status of this transaction needs to be resolved manually
NeedsAttention,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeCustomer {
pub payment_method: ChargebeePaymentMethod,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeePaymentMethod {
pub reference_id: String,
pub gateway: ChargebeeGateway,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeGateway {
Stripe,
Braintree,
}
impl ChargebeeWebhookBody {
pub fn get_webhook_object_from_body(body: &[u8]) -> CustomResult<Self, errors::ConnectorError> {
let webhook_body = body
.parse_struct::<Self>("ChargebeeWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(webhook_body)
}
}
impl ChargebeeInvoiceBody {
pub fn get_invoice_webhook_data_from_body(
body: &[u8],
) -> CustomResult<Self, errors::ConnectorError> {
let webhook_body = body
.parse_struct::<Self>("ChargebeeInvoiceBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(webhook_body)
}
}
pub struct ChargebeeMandateDetails {
pub customer_id: String,
pub mandate_id: String,
}
impl ChargebeeCustomer {
// the logic to find connector customer id & mandate id is different for different gateways, reference : https://apidocs.chargebee.com/docs/api/customers?prod_cat_ver=2#customer_payment_method_reference_id .
pub fn find_connector_ids(&self) -> Result<ChargebeeMandateDetails, errors::ConnectorError> {
match self.payment_method.gateway {
ChargebeeGateway::Stripe | ChargebeeGateway::Braintree => {
let mut parts = self.payment_method.reference_id.split('/');
let customer_id = parts
.next()
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?
.to_string();
let mandate_id = parts
.next_back()
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?
.to_string();
Ok(ChargebeeMandateDetails {
customer_id,
mandate_id,
})
}
}
}
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
impl TryFrom<ChargebeeWebhookBody> for revenue_recovery::RevenueRecoveryAttemptData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: ChargebeeWebhookBody) -> Result<Self, Self::Error> {
let amount = item.content.transaction.amount;
let currency = item.content.transaction.currency_code.to_owned();
let merchant_reference_id =
common_utils::id_type::PaymentReferenceId::from_str(&item.content.invoice.id)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let connector_transaction_id = item
.content
.transaction
.id_at_gateway
.map(common_utils::types::ConnectorTransactionId::TxnId);
let error_code = item.content.transaction.error_code.clone();
let error_message = item.content.transaction.error_text.clone();
let connector_mandate_details = item
.content
.customer
.as_ref()
.map(|customer| customer.find_connector_ids())
.transpose()?
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_details",
})?;
let connector_account_reference_id = item.content.transaction.gateway_account_id.clone();
let transaction_created_at = item.content.transaction.date;
let status = enums::AttemptStatus::from(item.content.transaction.status);
let payment_method_type =
enums::PaymentMethod::from(item.content.transaction.payment_method);
let payment_method_details: ChargebeePaymentMethodDetails =
serde_json::from_str(&item.content.transaction.payment_method_details)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let payment_method_sub_type =
enums::PaymentMethodType::from(payment_method_details.card.funding_type);
Ok(Self {
amount,
currency,
merchant_reference_id,
connector_transaction_id,
error_code,
error_message,
processor_payment_method_token: connector_mandate_details.mandate_id,
connector_customer_id: connector_mandate_details.customer_id,
connector_account_reference_id,
transaction_created_at,
status,
payment_method_type,
payment_method_sub_type,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
impl From<ChargebeeTranasactionStatus> for enums::AttemptStatus {
fn from(status: ChargebeeTranasactionStatus) -> Self {
match status {
ChargebeeTranasactionStatus::InProgress
| ChargebeeTranasactionStatus::NeedsAttention => Self::Pending,
ChargebeeTranasactionStatus::Success => Self::Charged,
ChargebeeTranasactionStatus::Failure
| ChargebeeTranasactionStatus::Timeout
| ChargebeeTranasactionStatus::LateFailure => Self::Failure,
}
}
}
impl From<ChargebeeTransactionPaymentMethod> for enums::PaymentMethod {
fn from(payment_method: ChargebeeTransactionPaymentMethod) -> Self {
match payment_method {
ChargebeeTransactionPaymentMethod::Card => Self::Card,
}
}
}
impl From<ChargebeeFundingType> for enums::PaymentMethodType {
fn from(funding_type: ChargebeeFundingType) -> Self {
match funding_type {
ChargebeeFundingType::Credit => Self::Credit,
ChargebeeFundingType::Debit => Self::Debit,
}
}
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
impl From<ChargebeeEventType> for api_models::webhooks::IncomingWebhookEvent {
fn from(event: ChargebeeEventType) -> Self {
match event {
ChargebeeEventType::PaymentSucceeded => Self::RecoveryPaymentSuccess,
ChargebeeEventType::PaymentFailed => Self::RecoveryPaymentFailure,
ChargebeeEventType::InvoiceDeleted => Self::RecoveryInvoiceCancel,
}
}
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
impl TryFrom<ChargebeeInvoiceBody> for revenue_recovery::RevenueRecoveryInvoiceData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: ChargebeeInvoiceBody) -> Result<Self, Self::Error> {
let merchant_reference_id =
common_utils::id_type::PaymentReferenceId::from_str(&item.content.invoice.id)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Self {
amount: item.content.invoice.total,
currency: item.content.invoice.currency_code,
merchant_reference_id,
})
}
}
#[derive(Debug, Serialize)]
pub struct ChargebeeRecordPaymentRequest {
#[serde(rename = "transaction[amount]")]
pub amount: MinorUnit,
#[serde(rename = "transaction[payment_method]")]
pub payment_method: ChargebeeRecordPaymentMethod,
#[serde(rename = "transaction[id_at_gateway]")]
pub connector_payment_id: Option<String>,
#[serde(rename = "transaction[status]")]
pub status: ChargebeeRecordStatus,
}
#[derive(Debug, Serialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeRecordPaymentMethod {
Other,
}
#[derive(Debug, Serialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeRecordStatus {
Success,
Failure,
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl TryFrom<&ChargebeeRouterData<&RevenueRecoveryRecordBackRouterData>>
for ChargebeeRecordPaymentRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ChargebeeRouterData<&RevenueRecoveryRecordBackRouterData>,
) -> Result<Self, Self::Error> {
let req = &item.router_data.request;
Ok(Self {
amount: req.amount,
payment_method: ChargebeeRecordPaymentMethod::Other,
connector_payment_id: req
.connector_transaction_id
.as_ref()
.map(|connector_payment_id| connector_payment_id.get_id().to_string()),
status: ChargebeeRecordStatus::try_from(req.attempt_status)?,
})
}
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl TryFrom<enums::AttemptStatus> for ChargebeeRecordStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(status: enums::AttemptStatus) -> Result<Self, Self::Error> {
match status {
enums::AttemptStatus::Charged
| enums::AttemptStatus::PartialCharged
| enums::AttemptStatus::PartialChargedAndChargeable => Ok(Self::Success),
enums::AttemptStatus::Failure
| enums::AttemptStatus::CaptureFailed
| enums::AttemptStatus::RouterDeclined => Ok(Self::Failure),
enums::AttemptStatus::AuthenticationFailed
| enums::AttemptStatus::Started
| enums::AttemptStatus::AuthenticationPending
| enums::AttemptStatus::AuthenticationSuccessful
| enums::AttemptStatus::Authorized
| enums::AttemptStatus::AuthorizationFailed
| enums::AttemptStatus::Authorizing
| enums::AttemptStatus::CodInitiated
| enums::AttemptStatus::Voided
| 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 => {
Err(errors::ConnectorError::NotSupported {
message: "Record back flow is only supported for terminal status".to_string(),
connector: "chargebee",
}
.into())
}
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ChargebeeRecordbackResponse {
pub invoice: ChargebeeRecordbackInvoice,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ChargebeeRecordbackInvoice {
pub id: common_utils::id_type::PaymentReferenceId,
}
impl
TryFrom<
ResponseRouterData<
RecoveryRecordBack,
ChargebeeRecordbackResponse,
RevenueRecoveryRecordBackRequest,
RevenueRecoveryRecordBackResponse,
>,
> for RevenueRecoveryRecordBackRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
RecoveryRecordBack,
ChargebeeRecordbackResponse,
RevenueRecoveryRecordBackRequest,
RevenueRecoveryRecordBackResponse,
>,
) -> Result<Self, Self::Error> {
let merchant_reference_id = item.response.invoice.id;
Ok(Self {
response: Ok(RevenueRecoveryRecordBackResponse {
merchant_reference_id,
}),
..item.data
})
}
}
| 4,854 | 2,245 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs | .rs | 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::StringMinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{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,
}
#[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,
}
#[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>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NovalnetMandate {
token: Secret<String>,
}
#[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),
}
#[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>,
scheme_tid: Option<Secret<String>>, // Card network's transaction ID
}
#[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 => Ok(Self::CREDITCARD),
api_enums::PaymentMethodType::GooglePay => Ok(Self::GOOGLEPAY),
api_enums::PaymentMethodType::Paypal => Ok(Self::PAYPAL),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Novalnet"),
))?,
}
}
}
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,
};
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,
scheme_tid: None,
};
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.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,
scheme_tid: None,
};
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,
scheme_tid: None,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
WalletDataPaymentMethod::AliPayQr(_)
| WalletDataPaymentMethod::AliPayRedirect(_)
| WalletDataPaymentMethod::AliPayHkRedirect(_)
| WalletDataPaymentMethod::AmazonPayRedirect(_)
| WalletDataPaymentMethod::MomoRedirect(_)
| WalletDataPaymentMethod::KakaoPayRedirect(_)
| WalletDataPaymentMethod::GoPayRedirect(_)
| WalletDataPaymentMethod::GcashRedirect(_)
| WalletDataPaymentMethod::ApplePayRedirect(_)
| WalletDataPaymentMethod::ApplePayThirdPartySdk(_)
| WalletDataPaymentMethod::DanaRedirect {}
| WalletDataPaymentMethod::GooglePayRedirect(_)
| WalletDataPaymentMethod::GooglePayThirdPartySdk(_)
| WalletDataPaymentMethod::MbWayRedirect(_)
| WalletDataPaymentMethod::MobilePayRedirect(_) => {
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,
scheme_tid: None,
};
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())
}
},
_ => 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,
scheme_tid: 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(),
});
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,
scheme_tid: Some(network_transaction_id.into()),
};
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<u64>,
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,
}
}
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: 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<u64>,
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>>,
}
#[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<u64>,
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.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: 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<u64>,
pub capture: CaptureData,
pub currency: Option<common_enums::Currency>,
pub order_no: Option<String>,
pub payment_type: String,
pub status: NovalnetTransactionStatus,
pub status_code: Option<u64>,
pub test_mode: Option<u8>,
pub tid: Secret<i64>,
}
#[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()
.map(|data| data.tid.expose().to_string());
let transaction_status = item
.response
.transaction
.map(|transaction_data| transaction_data.status)
.unwrap_or(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(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,
};
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,
scheme_tid: None,
};
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.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,
scheme_tid: None,
};
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: Secret::new(payment_method_data.payment_data.clone()),
})),
enforce_3d: None,
create_token,
scheme_tid: None,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
WalletDataPaymentMethod::AliPayQr(_)
| WalletDataPaymentMethod::AliPayRedirect(_)
| WalletDataPaymentMethod::AliPayHkRedirect(_)
| WalletDataPaymentMethod::AmazonPayRedirect(_)
| WalletDataPaymentMethod::MomoRedirect(_)
| WalletDataPaymentMethod::KakaoPayRedirect(_)
| WalletDataPaymentMethod::GoPayRedirect(_)
| WalletDataPaymentMethod::GcashRedirect(_)
| WalletDataPaymentMethod::ApplePayRedirect(_)
| WalletDataPaymentMethod::ApplePayThirdPartySdk(_)
| WalletDataPaymentMethod::DanaRedirect {}
| WalletDataPaymentMethod::GooglePayRedirect(_)
| WalletDataPaymentMethod::GooglePayThirdPartySdk(_)
| WalletDataPaymentMethod::MbWayRedirect(_)
| WalletDataPaymentMethod::MobilePayRedirect(_) => {
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,
scheme_tid: None,
};
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"),
))?,
}
}
}
| 12,231 | 2,246 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs | .rs | use common_enums::{enums, CountryAlpha2, UsStatesAbbreviation};
use common_utils::{
id_type,
pii::{self, IpAddress},
};
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::{MandateReference, PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::{api, 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: i64, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for GocardlessRouterData<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> {
Ok(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 {
connector_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 { .. } => 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::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 { .. } => 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: i64,
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.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: i64,
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)?
}
}
}
}
| 6,595 | 2,247 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs | .rs | use std::collections::HashMap;
use common_enums::enums;
use common_utils::{pii, request::Method};
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,
};
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, Default, Eq, PartialEq, Serialize)]
pub struct LocalPrice {
pub amount: String,
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<&types::PaymentsAuthorizeRouterData> for CoinbasePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::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: &types::PaymentsAuthorizeRouterData,
) -> Result<CoinbasePaymentsRequest, error_stack::Report<errors::ConnectorError>> {
let billing_address = item
.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.get_description().ok();
let connector_meta = CoinbaseConnectorMeta::try_from(&item.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.request.get_router_return_url()?;
let cancel_url = item.request.get_router_return_url()?;
Ok(CoinbasePaymentsRequest {
name,
description,
pricing_type,
local_price,
redirect_url,
cancel_url,
})
}
fn get_local_price(item: &types::PaymentsAuthorizeRouterData) -> LocalPrice {
LocalPrice {
amount: format!("{:?}", item.request.amount),
currency: item.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 CoinbasePaymentResponseData {
pub id: String,
pub code: String,
pub name: Option<Secret<String>>,
pub utxo: bool,
pub pricing: HashMap<String, OverpaymentAbsoluteThreshold>,
pub fee_rate: f64,
pub logo_url: String,
pub metadata: Option<Metadata>,
pub payments: Vec<PaymentElement>,
pub resource: String,
pub timeline: Vec<Timeline>,
pub pwcb_only: bool,
pub cancel_url: String,
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: bool,
pub pricing_type: String,
pub redirect_url: String,
pub support_email: pii::Email,
pub brand_logo_url: String,
pub offchain_eligible: bool,
pub organization_name: String,
pub payment_threshold: PaymentThreshold,
pub coinbase_managed_merchant: 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: String,
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,
}
| 2,962 | 2,248 |
hyperswitch | crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs | .rs | use base64::Engine;
use common_enums::{enums, FutureUsage};
use common_utils::{consts, ext_traits::OptionExt, pii};
use hyperswitch_domain_models::{
payment_method_data::{
ApplePayWalletData, GooglePayWalletData, PaymentMethodData, SamsungPayWalletData,
WalletData,
},
router_data::{
AdditionalPaymentMethodConnectorResponse, ApplePayPredecryptData, ConnectorAuthType,
ConnectorResponseData, ErrorResponse, PaymentMethodToken, RouterData,
},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData,
ResponseId,
},
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{api, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
constants,
types::{RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
utils::{
self, AddressDetailsData, ApplePayDecrypt, CardData, PaymentsAuthorizeRequestData,
PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RecurringMandateData,
RouterData as OtherRouterData,
},
};
pub struct BankOfAmericaAuthType {
pub(super) api_key: Secret<String>,
pub(super) merchant_account: Secret<String>,
pub(super) api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BankOfAmericaAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = auth_type
{
Ok(Self {
api_key: api_key.to_owned(),
merchant_account: key1.to_owned(),
api_secret: api_secret.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
pub struct BankOfAmericaRouterData<T> {
pub amount: String,
pub router_data: T,
}
impl<T> TryFrom<(&api::CurrencyUnit, api_models::enums::Currency, i64, T)>
for BankOfAmericaRouterData<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(currency_unit, currency, amount, item): (
&api::CurrencyUnit,
api_models::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,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaPaymentsRequest {
processing_information: ProcessingInformation,
payment_information: PaymentInformation,
order_information: OrderInformationWithBill,
client_reference_information: ClientReferenceInformation,
#[serde(skip_serializing_if = "Option::is_none")]
consumer_authentication_information: Option<BankOfAmericaConsumerAuthInformation>,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_defined_information: Option<Vec<MerchantDefinedInformation>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingInformation {
action_list: Option<Vec<BankOfAmericaActionsList>>,
action_token_types: Option<Vec<BankOfAmericaActionsTokenType>>,
authorization_options: Option<BankOfAmericaAuthorizationOptions>,
commerce_indicator: String,
capture: Option<bool>,
capture_options: Option<CaptureOptions>,
payment_solution: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BankOfAmericaActionsList {
TokenCreate,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum BankOfAmericaActionsTokenType {
PaymentInstrument,
Customer,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaAuthorizationOptions {
initiator: Option<BankOfAmericaPaymentInitiator>,
merchant_intitiated_transaction: Option<MerchantInitiatedTransaction>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaPaymentInitiator {
#[serde(rename = "type")]
initiator_type: Option<BankOfAmericaPaymentInitiatorTypes>,
credential_stored_on_file: Option<bool>,
stored_credential_used: Option<bool>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum BankOfAmericaPaymentInitiatorTypes {
Customer,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantInitiatedTransaction {
reason: Option<String>,
//Required for recurring mandates payment
original_authorized_amount: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantDefinedInformation {
key: u8,
value: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaConsumerAuthInformation {
ucaf_collection_indicator: Option<String>,
cavv: Option<String>,
ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
directory_server_transaction_id: Option<Secret<String>>,
specification_version: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureOptions {
capture_sequence_number: u32,
total_capture_count: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BankOfAmericaPaymentInstrument {
id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardPaymentInformation {
card: Card,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayPaymentInformation {
fluid_data: FluidData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayTokenizedCard {
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayTokenPaymentInformation {
fluid_data: FluidData,
tokenized_card: ApplePayTokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayPaymentInformation {
tokenized_card: TokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymentInformation {
Cards(Box<CardPaymentInformation>),
GooglePay(Box<GooglePayPaymentInformation>),
ApplePay(Box<ApplePayPaymentInformation>),
ApplePayToken(Box<ApplePayTokenPaymentInformation>),
MandatePayment(Box<MandatePaymentInformation>),
SamsungPay(Box<SamsungPayPaymentInformation>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MandatePaymentInformation {
payment_instrument: BankOfAmericaPaymentInstrument,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
number: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
security_code: Secret<String>,
#[serde(rename = "type")]
card_type: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCard {
number: Secret<String>,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
cryptogram: Secret<String>,
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FluidData {
value: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
descriptor: Option<String>,
}
pub const FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY: &str = "FID=COMMON.SAMSUNG.INAPP.PAYMENT";
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderInformationWithBill {
amount_details: Amount,
bill_to: Option<BillTo>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
total_amount: String,
currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BillTo {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address1: Option<Secret<String>>,
locality: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
administrative_area: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
postal_code: Option<Secret<String>>,
country: Option<enums::CountryAlpha2>,
email: pii::Email,
}
impl TryFrom<&SetupMandateRouterData> for BankOfAmericaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(card_data) => Self::try_from((item, card_data)),
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::ApplePay(apple_pay_data) => Self::try_from((item, apple_pay_data)),
WalletData::GooglePay(google_pay_data) => Self::try_from((item, google_pay_data)),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::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(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("BankOfAmerica"),
))?,
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("BankOfAmerica"),
))?
}
}
}
}
impl<F, T>
TryFrom<ResponseRouterData<F, BankOfAmericaSetupMandatesResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BankOfAmericaSetupMandatesResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
BankOfAmericaSetupMandatesResponse::ClientReferenceInformation(info_response) => {
let mandate_reference =
info_response
.token_information
.clone()
.map(|token_info| MandateReference {
connector_mandate_id: token_info
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
let mut mandate_status =
map_boa_attempt_status((info_response.status.clone(), false));
if matches!(mandate_status, enums::AttemptStatus::Authorized) {
//In case of zero auth mandates we want to make the payment reach the terminal status so we are converting the authorized status to charged as well.
mandate_status = enums::AttemptStatus::Charged
}
let error_response =
get_error_response_if_failure((&info_response, mandate_status, item.http_code));
let connector_response = match item.data.payment_method {
common_enums::PaymentMethod::Card => info_response
.processor_information
.as_ref()
.and_then(|processor_information| {
info_response
.consumer_authentication_information
.as_ref()
.map(|consumer_auth_information| {
convert_to_additional_payment_method_connector_response(
processor_information,
consumer_auth_information,
)
})
})
.map(ConnectorResponseData::with_additional_payment_method_data),
common_enums::PaymentMethod::CardRedirect
| common_enums::PaymentMethod::PayLater
| common_enums::PaymentMethod::Wallet
| common_enums::PaymentMethod::BankRedirect
| common_enums::PaymentMethod::BankTransfer
| common_enums::PaymentMethod::Crypto
| common_enums::PaymentMethod::BankDebit
| common_enums::PaymentMethod::Reward
| common_enums::PaymentMethod::RealTimePayment
| common_enums::PaymentMethod::MobilePayment
| common_enums::PaymentMethod::Upi
| common_enums::PaymentMethod::Voucher
| common_enums::PaymentMethod::OpenBanking
| common_enums::PaymentMethod::GiftCard => None,
};
Ok(Self {
status: mandate_status,
response: match error_response {
Some(error) => Err(error),
None => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
info_response.id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
info_response
.client_reference_information
.code
.clone()
.unwrap_or(info_response.id),
),
incremental_authorization_allowed: None,
charges: None,
}),
},
connector_response,
..item.data
})
}
BankOfAmericaSetupMandatesResponse::ErrorInformation(error_response) => {
let response = Err(convert_to_error_response_from_error_info(
&error_response,
item.http_code,
));
Ok(Self {
response,
status: enums::AttemptStatus::Failure,
..item.data
})
}
}
}
}
// for bankofamerica each item in Billing is mandatory
// fn build_bill_to(
// address_details: &payments::Address,
// email: pii::Email,
// ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> {
// let address = address_details
// .address
// .as_ref()
// .ok_or_else(utils::missing_field_err("billing.address"))?;
// let country = address.get_country()?.to_owned();
// let first_name = address.get_first_name()?;
// let (administrative_area, postal_code) =
// if country == api_enums::CountryAlpha2::US || country == api_enums::CountryAlpha2::CA {
// let mut state = address.to_state_code()?.peek().clone();
// state.truncate(20);
// (
// Some(Secret::from(state)),
// Some(address.get_zip()?.to_owned()),
// )
// } else {
// let zip = address.zip.clone();
// let mut_state = address.state.clone().map(|state| state.expose());
// match mut_state {
// Some(mut state) => {
// state.truncate(20);
// (Some(Secret::from(state)), zip)
// }
// None => (None, zip),
// }
// };
// Ok(BillTo {
// first_name: first_name.clone(),
// last_name: address.get_last_name().unwrap_or(first_name).clone(),
// address1: address.get_line1()?.to_owned(),
// locality: Secret::new(address.get_city()?.to_owned()),
// administrative_area,
// postal_code,
// country,
// email,
// })
// }
fn build_bill_to(
address_details: Option<&hyperswitch_domain_models::address::Address>,
email: pii::Email,
) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> {
let default_address = BillTo {
first_name: None,
last_name: None,
address1: None,
locality: None,
administrative_area: None,
postal_code: None,
country: None,
email: email.clone(),
};
Ok(address_details
.and_then(|addr| {
addr.address.as_ref().map(|addr| {
let administrative_area = addr.to_state_code_as_optional().unwrap_or_else(|_| {
addr.state
.clone()
.map(|state| Secret::new(format!("{:.20}", state.expose())))
});
BillTo {
first_name: addr.first_name.clone(),
last_name: addr.last_name.clone(),
address1: addr.line1.clone(),
locality: addr.city.clone(),
administrative_area,
postal_code: addr.zip.clone(),
country: addr.country,
email,
}
})
})
.unwrap_or(default_address))
}
fn get_boa_card_type(card_network: common_enums::CardNetwork) -> Option<&'static str> {
match card_network {
common_enums::CardNetwork::Visa => Some("001"),
common_enums::CardNetwork::Mastercard => Some("002"),
common_enums::CardNetwork::AmericanExpress => Some("003"),
common_enums::CardNetwork::JCB => Some("007"),
common_enums::CardNetwork::DinersClub => Some("005"),
common_enums::CardNetwork::Discover => Some("004"),
common_enums::CardNetwork::CartesBancaires => Some("006"),
common_enums::CardNetwork::UnionPay => Some("062"),
//"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024"
common_enums::CardNetwork::Maestro => Some("042"),
common_enums::CardNetwork::Interac | common_enums::CardNetwork::RuPay => None,
}
}
#[derive(Debug, Serialize)]
pub enum PaymentSolution {
ApplePay,
GooglePay,
SamsungPay,
}
impl From<PaymentSolution> for String {
fn from(solution: PaymentSolution) -> Self {
let payment_solution = match solution {
PaymentSolution::ApplePay => "001",
PaymentSolution::GooglePay => "012",
PaymentSolution::SamsungPay => "008",
};
payment_solution.to_string()
}
}
#[derive(Debug, Serialize)]
pub enum TransactionType {
#[serde(rename = "1")]
ApplePay,
#[serde(rename = "1")]
SamsungPay,
}
impl
From<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Option<BillTo>,
)> for OrderInformationWithBill
{
fn from(
(item, bill_to): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Option<BillTo>,
),
) -> Self {
Self {
amount_details: Amount {
total_amount: item.amount.to_owned(),
currency: item.router_data.request.currency,
},
bill_to,
}
}
}
impl
TryFrom<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
)> for ProcessingInformation
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, solution, network): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
),
) -> Result<Self, Self::Error> {
let (action_list, action_token_types, authorization_options) =
if item.router_data.request.setup_future_usage == Some(FutureUsage::OffSession)
&& (item.router_data.request.customer_acceptance.is_some()
|| item
.router_data
.request
.setup_mandate_details
.clone()
.is_some_and(|mandate_details| {
mandate_details.customer_acceptance.is_some()
}))
{
get_boa_mandate_action_details()
} else if item.router_data.request.connector_mandate_id().is_some() {
let original_amount = item
.router_data
.get_recurring_mandate_payment_data()?
.get_original_payment_amount()?;
let original_currency = item
.router_data
.get_recurring_mandate_payment_data()?
.get_original_payment_currency()?;
(
None,
None,
Some(BankOfAmericaAuthorizationOptions {
initiator: None,
merchant_intitiated_transaction: Some(MerchantInitiatedTransaction {
reason: None,
original_authorized_amount: Some(utils::get_amount_as_string(
&api::CurrencyUnit::Base,
original_amount,
original_currency,
)?),
}),
}),
)
} else {
(None, None, None)
};
let commerce_indicator = get_commerce_indicator(network);
Ok(Self {
capture: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
)),
payment_solution: solution.map(String::from),
action_list,
action_token_types,
authorization_options,
capture_options: None,
commerce_indicator,
})
}
}
impl From<&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>> for ClientReferenceInformation {
fn from(item: &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>) -> Self {
Self {
code: Some(item.router_data.connector_request_reference_id.clone()),
}
}
}
impl From<&SetupMandateRouterData> for ClientReferenceInformation {
fn from(item: &SetupMandateRouterData) -> Self {
Self {
code: Some(item.connector_request_reference_id.clone()),
}
}
}
fn convert_metadata_to_merchant_defined_info(metadata: Value) -> Vec<MerchantDefinedInformation> {
let hashmap: std::collections::BTreeMap<String, Value> =
serde_json::from_str(&metadata.to_string()).unwrap_or(std::collections::BTreeMap::new());
let mut vector = Vec::new();
let mut iter = 1;
for (key, value) in hashmap {
vector.push(MerchantDefinedInformation {
key: iter,
value: format!("{key}={value}"),
});
iter += 1;
}
vector
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientReferenceInformation {
code: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientProcessorInformation {
avs: Option<Avs>,
card_verification: Option<CardVerification>,
processor: Option<ProcessorResponse>,
network_transaction_id: Option<Secret<String>>,
approval_code: Option<String>,
merchant_advice: Option<MerchantAdvice>,
response_code: Option<String>,
ach_verification: Option<AchVerification>,
system_trace_audit_number: Option<String>,
event_status: Option<String>,
retrieval_reference_number: Option<String>,
consumer_authentication_response: Option<ConsumerAuthenticationResponse>,
response_details: Option<String>,
transaction_id: Option<Secret<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantAdvice {
code: Option<String>,
code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConsumerAuthenticationResponse {
code: Option<String>,
code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AchVerification {
result_code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessorResponse {
name: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardVerification {
result_code: Option<String>,
result_code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientRiskInformation {
rules: Option<Vec<ClientRiskInformationRules>>,
profile: Option<Profile>,
score: Option<Score>,
info_codes: Option<InfoCodes>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InfoCodes {
address: Option<Vec<String>>,
identity_change: Option<Vec<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Score {
factor_codes: Option<Vec<String>>,
result: Option<RiskResult>,
model_used: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum RiskResult {
StringVariant(String),
IntVariant(u64),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Profile {
early_decision: Option<String>,
name: Option<String>,
decision: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ClientRiskInformationRules {
name: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Avs {
code: Option<String>,
code_raw: Option<String>,
}
impl
TryFrom<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
hyperswitch_domain_models::payment_method_data::Card,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, ccard): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
hyperswitch_domain_models::payment_method_data::Card,
),
) -> Result<Self, Self::Error> {
if item.router_data.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Card 3DS".to_string(),
connector: "BankOfAmerica",
})?
};
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?;
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
let payment_information = PaymentInformation::try_from(&ccard)?;
let processing_information = ProcessingInformation::try_from((item, None, None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information: None,
})
}
}
impl
TryFrom<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
ApplePayWalletData,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, apple_pay_data, apple_pay_wallet_data): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
ApplePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?;
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
let processing_information = ProcessingInformation::try_from((
item,
Some(PaymentSolution::ApplePay),
Some(apple_pay_wallet_data.payment_method.network.clone()),
))?;
let client_reference_information = ClientReferenceInformation::from(item);
let payment_information = PaymentInformation::try_from(&apple_pay_data)?;
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
let ucaf_collection_indicator = match apple_pay_wallet_data
.payment_method
.network
.to_lowercase()
.as_str()
{
"mastercard" => Some("2".to_string()),
_ => None,
};
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information: Some(BankOfAmericaConsumerAuthInformation {
ucaf_collection_indicator,
cavv: None,
ucaf_authentication_data: None,
xid: None,
directory_server_transaction_id: None,
specification_version: None,
}),
})
}
}
impl
TryFrom<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
GooglePayWalletData,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, google_pay_data): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
GooglePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?;
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
let payment_information = PaymentInformation::from(&google_pay_data);
let processing_information =
ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay), None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information: None,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SamsungPayTokenizedCard {
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SamsungPayPaymentInformation {
fluid_data: FluidData,
tokenized_card: SamsungPayTokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SamsungPayFluidDataValue {
public_key_hash: Secret<String>,
version: String,
data: Secret<String>,
}
impl TryFrom<&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>>
for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.connector_mandate_id() {
Some(connector_mandate_id) => Self::try_from((item, connector_mandate_id)),
None => {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)),
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::ApplePay(apple_pay_data) => {
match item.router_data.payment_method_token.clone() {
Some(payment_method_token) => match payment_method_token {
PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
Self::try_from((item, decrypt_data, apple_pay_data))
}
PaymentMethodToken::Token(_) => {
Err(unimplemented_payment_method!(
"Apple Pay",
"Manual",
"Bank Of America"
))?
}
PaymentMethodToken::PazeDecrypt(_) => Err(
unimplemented_payment_method!("Paze", "Bank Of America"),
)?,
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!(
"Google Pay",
"Bank Of America"
))?
}
},
None => {
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(
item.router_data.get_optional_billing(),
email,
)?;
let order_information: OrderInformationWithBill =
OrderInformationWithBill::from((item, Some(bill_to)));
let processing_information =
ProcessingInformation::try_from((
item,
Some(PaymentSolution::ApplePay),
Some(apple_pay_data.payment_method.network.clone()),
))?;
let client_reference_information =
ClientReferenceInformation::from(item);
let payment_information =
PaymentInformation::from(&apple_pay_data);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
let ucaf_collection_indicator = match apple_pay_data
.payment_method
.network
.to_lowercase()
.as_str()
{
"mastercard" => Some("2".to_string()),
_ => None,
};
Ok(Self {
processing_information,
payment_information,
order_information,
merchant_defined_information,
client_reference_information,
consumer_authentication_information: Some(
BankOfAmericaConsumerAuthInformation {
ucaf_collection_indicator,
cavv: None,
ucaf_authentication_data: None,
xid: None,
directory_server_transaction_id: None,
specification_version: None,
},
),
})
}
}
}
WalletData::GooglePay(google_pay_data) => {
Self::try_from((item, google_pay_data))
}
WalletData::SamsungPay(samsung_pay_data) => {
Self::try_from((item, samsung_pay_data))
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::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::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"Bank of America",
),
)
.into()),
},
// If connector_mandate_id is present MandatePayment will be the PMD, the case will be handled in the first `if` clause.
// This is a fallback implementation in the event of catastrophe.
PaymentMethodData::MandatePayment => {
let connector_mandate_id =
item.router_data.request.connector_mandate_id().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
},
)?;
Self::try_from((item, connector_mandate_id))
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"Bank of America",
),
)
.into())
}
}
}
}
}
}
fn get_samsung_pay_fluid_data_value(
samsung_pay_token_data: &hyperswitch_domain_models::payment_method_data::SamsungPayTokenData,
) -> Result<SamsungPayFluidDataValue, error_stack::Report<errors::ConnectorError>> {
let samsung_pay_header =
josekit::jwt::decode_header(samsung_pay_token_data.data.clone().peek())
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to decode samsung pay header")?;
let samsung_pay_kid_optional = samsung_pay_header.claim("kid").and_then(|kid| kid.as_str());
let samsung_pay_fluid_data_value = SamsungPayFluidDataValue {
public_key_hash: Secret::new(
samsung_pay_kid_optional
.get_required_value("samsung pay public_key_hash")
.change_context(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
),
version: samsung_pay_token_data.version.clone(),
data: Secret::new(consts::BASE64_ENGINE.encode(samsung_pay_token_data.data.peek())),
};
Ok(samsung_pay_fluid_data_value)
}
use error_stack::ResultExt;
impl
TryFrom<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Box<SamsungPayWalletData>,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, samsung_pay_data): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Box<SamsungPayWalletData>,
),
) -> Result<Self, Self::Error> {
let email = item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?;
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
let samsung_pay_fluid_data_value =
get_samsung_pay_fluid_data_value(&samsung_pay_data.payment_credential.token_data)?;
let samsung_pay_fluid_data_str = serde_json::to_string(&samsung_pay_fluid_data_value)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to serialize samsung pay fluid data")?;
let payment_information =
PaymentInformation::SamsungPay(Box::new(SamsungPayPaymentInformation {
fluid_data: FluidData {
value: Secret::new(consts::BASE64_ENGINE.encode(samsung_pay_fluid_data_str)),
descriptor: Some(
consts::BASE64_ENGINE.encode(FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY),
),
},
tokenized_card: SamsungPayTokenizedCard {
transaction_type: TransactionType::SamsungPay,
},
}));
let processing_information = ProcessingInformation::try_from((
item,
Some(PaymentSolution::SamsungPay),
Some(samsung_pay_data.payment_credential.card_brand.to_string()),
))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
consumer_authentication_information: None,
merchant_defined_information,
})
}
}
impl
TryFrom<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
String,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, connector_mandate_id): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
String,
),
) -> Result<Self, Self::Error> {
let processing_information = ProcessingInformation::try_from((item, None, None))?;
let payment_instrument = BankOfAmericaPaymentInstrument {
id: connector_mandate_id.into(),
};
let bill_to =
item.router_data.request.get_email().ok().and_then(|email| {
build_bill_to(item.router_data.get_optional_billing(), email).ok()
});
let order_information = OrderInformationWithBill::from((item, bill_to));
let payment_information =
PaymentInformation::MandatePayment(Box::new(MandatePaymentInformation {
payment_instrument,
}));
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information: None,
})
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BankofamericaPaymentStatus {
Authorized,
Succeeded,
Failed,
Voided,
Reversed,
Pending,
Declined,
Rejected,
Challenge,
AuthorizedPendingReview,
AuthorizedRiskDeclined,
Transmitted,
InvalidRequest,
ServerError,
PendingAuthentication,
PendingReview,
Accepted,
Cancelled,
//PartialAuthorized, not being consumed yet.
}
fn map_boa_attempt_status(
(status, auto_capture): (BankofamericaPaymentStatus, bool),
) -> enums::AttemptStatus {
match status {
BankofamericaPaymentStatus::Authorized
| BankofamericaPaymentStatus::AuthorizedPendingReview => {
if auto_capture {
// Because BankOfAmerica will return Payment Status as Authorized even in AutoCapture Payment
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
BankofamericaPaymentStatus::Pending => {
if auto_capture {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Pending
}
}
BankofamericaPaymentStatus::Succeeded | BankofamericaPaymentStatus::Transmitted => {
enums::AttemptStatus::Charged
}
BankofamericaPaymentStatus::Voided
| BankofamericaPaymentStatus::Reversed
| BankofamericaPaymentStatus::Cancelled => enums::AttemptStatus::Voided,
BankofamericaPaymentStatus::Failed
| BankofamericaPaymentStatus::Declined
| BankofamericaPaymentStatus::AuthorizedRiskDeclined
| BankofamericaPaymentStatus::InvalidRequest
| BankofamericaPaymentStatus::Rejected
| BankofamericaPaymentStatus::ServerError => enums::AttemptStatus::Failure,
BankofamericaPaymentStatus::PendingAuthentication => {
enums::AttemptStatus::AuthenticationPending
}
BankofamericaPaymentStatus::PendingReview
| BankofamericaPaymentStatus::Challenge
| BankofamericaPaymentStatus::Accepted => enums::AttemptStatus::Pending,
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BankOfAmericaPaymentsResponse {
ClientReferenceInformation(Box<BankOfAmericaClientReferenceResponse>),
ErrorInformation(Box<BankOfAmericaErrorInformationResponse>),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BankOfAmericaSetupMandatesResponse {
ClientReferenceInformation(Box<BankOfAmericaClientReferenceResponse>),
ErrorInformation(Box<BankOfAmericaErrorInformationResponse>),
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaClientReferenceResponse {
id: String,
status: BankofamericaPaymentStatus,
client_reference_information: ClientReferenceInformation,
processor_information: Option<ClientProcessorInformation>,
processing_information: Option<ProcessingInformationResponse>,
payment_information: Option<PaymentInformationResponse>,
payment_insights_information: Option<PaymentInsightsInformation>,
risk_information: Option<ClientRiskInformation>,
token_information: Option<BankOfAmericaTokenInformation>,
error_information: Option<BankOfAmericaErrorInformation>,
issuer_information: Option<IssuerInformation>,
sender_information: Option<SenderInformation>,
payment_account_information: Option<PaymentAccountInformation>,
reconciliation_id: Option<String>,
consumer_authentication_information: Option<ConsumerAuthenticationInformation>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConsumerAuthenticationInformation {
eci_raw: Option<String>,
eci: Option<String>,
acs_transaction_id: Option<String>,
cavv: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SenderInformation {
payment_information: Option<PaymentInformationResponse>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInsightsInformation {
response_insights: Option<ResponseInsights>,
rule_results: Option<RuleResults>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResponseInsights {
category_code: Option<String>,
category: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RuleResults {
id: Option<String>,
decision: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInformationResponse {
tokenized_card: Option<CardResponseObject>,
customer: Option<CustomerResponseObject>,
card: Option<CardResponseObject>,
scheme: Option<String>,
bin: Option<String>,
account_type: Option<String>,
issuer: Option<String>,
bin_country: Option<enums::CountryAlpha2>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomerResponseObject {
customer_id: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentAccountInformation {
card: Option<PaymentAccountCardInformation>,
features: Option<PaymentAccountFeatureInformation>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentAccountFeatureInformation {
health_card: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentAccountCardInformation {
#[serde(rename = "type")]
card_type: Option<String>,
hashed_number: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingInformationResponse {
payment_solution: Option<String>,
commerce_indicator: Option<String>,
commerce_indicator_label: Option<String>,
authorization_options: Option<AuthorizationOptions>,
ecommerce_indicator: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizationOptions {
auth_type: Option<String>,
initiator: Option<Initiator>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Initiator {
merchant_initiated_transaction: Option<MerchantInitiatedTransactionResponse>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantInitiatedTransactionResponse {
agreement_id: Option<String>,
previous_transaction_id: Option<String>,
original_authorized_amount: Option<String>,
reason: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaTokenInformation {
payment_instrument: Option<BankOfAmericaPaymentInstrument>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IssuerInformation {
country: Option<enums::CountryAlpha2>,
discretionary_data: Option<String>,
country_specific_discretionary_data: Option<String>,
response_code: Option<String>,
pin_request_indicator: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardResponseObject {
suffix: Option<String>,
prefix: Option<String>,
expiration_month: Option<Secret<String>>,
expiration_year: Option<Secret<String>>,
#[serde(rename = "type")]
card_type: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaErrorInformationResponse {
id: String,
error_information: BankOfAmericaErrorInformation,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct BankOfAmericaErrorInformation {
reason: Option<String>,
message: Option<String>,
details: Option<Vec<Details>>,
}
fn map_error_response<F, T>(
error_response: &BankOfAmericaErrorInformationResponse,
item: ResponseRouterData<F, BankOfAmericaPaymentsResponse, T, PaymentsResponseData>,
transaction_status: Option<enums::AttemptStatus>,
) -> RouterData<F, T, PaymentsResponseData> {
let detailed_error_info = error_response
.error_information
.details
.as_ref()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message.clone(),
detailed_error_info,
None,
);
let response = Err(ErrorResponse {
code: error_response
.error_information
.reason
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_response
.error_information
.reason
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
});
match transaction_status {
Some(status) => RouterData {
response,
status,
..item.data
},
None => RouterData {
response,
..item.data
},
}
}
fn get_error_response_if_failure(
(info_response, status, http_code): (
&BankOfAmericaClientReferenceResponse,
enums::AttemptStatus,
u16,
),
) -> Option<ErrorResponse> {
if utils::is_payment_failure(status) {
Some(get_error_response(
&info_response.error_information,
&info_response.risk_information,
Some(status),
http_code,
info_response.id.clone(),
))
} else {
None
}
}
fn get_payment_response(
(info_response, status, http_code): (
&BankOfAmericaClientReferenceResponse,
enums::AttemptStatus,
u16,
),
) -> Result<PaymentsResponseData, Box<ErrorResponse>> {
let error_response = get_error_response_if_failure((info_response, status, http_code));
match error_response {
Some(error) => Err(Box::new(error)),
None => {
let mandate_reference =
info_response
.token_information
.clone()
.map(|token_info| MandateReference {
connector_mandate_id: token_info
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(info_response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
info_response
.client_reference_information
.code
.clone()
.unwrap_or(info_response.id.clone()),
),
incremental_authorization_allowed: None,
charges: None,
})
}
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BankOfAmericaPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BankOfAmericaPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => {
let status = map_boa_attempt_status((
info_response.status.clone(),
item.data.request.is_auto_capture()?,
));
let response = get_payment_response((&info_response, status, item.http_code))
.map_err(|err| *err);
let connector_response = match item.data.payment_method {
common_enums::PaymentMethod::Card => info_response
.processor_information
.as_ref()
.and_then(|processor_information| {
info_response
.consumer_authentication_information
.as_ref()
.map(|consumer_auth_information| {
convert_to_additional_payment_method_connector_response(
processor_information,
consumer_auth_information,
)
})
})
.map(ConnectorResponseData::with_additional_payment_method_data),
common_enums::PaymentMethod::CardRedirect
| common_enums::PaymentMethod::PayLater
| common_enums::PaymentMethod::Wallet
| common_enums::PaymentMethod::BankRedirect
| common_enums::PaymentMethod::BankTransfer
| common_enums::PaymentMethod::Crypto
| common_enums::PaymentMethod::BankDebit
| common_enums::PaymentMethod::Reward
| common_enums::PaymentMethod::RealTimePayment
| common_enums::PaymentMethod::MobilePayment
| common_enums::PaymentMethod::Upi
| common_enums::PaymentMethod::Voucher
| common_enums::PaymentMethod::OpenBanking
| common_enums::PaymentMethod::GiftCard => None,
};
Ok(Self {
status,
response,
connector_response,
..item.data
})
}
BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => {
Ok(map_error_response(
&error_response.clone(),
item,
Some(enums::AttemptStatus::Failure),
))
}
}
}
}
fn convert_to_additional_payment_method_connector_response(
processor_information: &ClientProcessorInformation,
consumer_authentication_information: &ConsumerAuthenticationInformation,
) -> AdditionalPaymentMethodConnectorResponse {
let payment_checks = Some(serde_json::json!({
"avs_response": processor_information.avs,
"card_verification": processor_information.card_verification,
"approval_code": processor_information.approval_code,
"consumer_authentication_response": processor_information.consumer_authentication_response,
"cavv": consumer_authentication_information.cavv,
"eci": consumer_authentication_information.eci,
"eci_raw": consumer_authentication_information.eci_raw,
}));
let authentication_data = Some(serde_json::json!({
"retrieval_reference_number": processor_information.retrieval_reference_number,
"acs_transaction_id": consumer_authentication_information.acs_transaction_id,
"system_trace_audit_number": processor_information.system_trace_audit_number,
}));
AdditionalPaymentMethodConnectorResponse::Card {
authentication_data,
payment_checks,
card_network: None,
domestic_network: None,
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BankOfAmericaPaymentsResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BankOfAmericaPaymentsResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => {
let status = map_boa_attempt_status((info_response.status.clone(), true));
let response = get_payment_response((&info_response, status, item.http_code))
.map_err(|err| *err);
Ok(Self {
status,
response,
..item.data
})
}
BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => {
Ok(map_error_response(&error_response.clone(), item, None))
}
}
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BankOfAmericaPaymentsResponse,
PaymentsCancelData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BankOfAmericaPaymentsResponse,
PaymentsCancelData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => {
let status = map_boa_attempt_status((info_response.status.clone(), false));
let response = get_payment_response((&info_response, status, item.http_code))
.map_err(|err| *err);
Ok(Self {
status,
response,
..item.data
})
}
BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => {
Ok(map_error_response(&error_response.clone(), item, None))
}
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaTransactionResponse {
id: String,
application_information: ApplicationInformation,
client_reference_information: Option<ClientReferenceInformation>,
processor_information: Option<ClientProcessorInformation>,
processing_information: Option<ProcessingInformationResponse>,
payment_information: Option<PaymentInformationResponse>,
payment_insights_information: Option<PaymentInsightsInformation>,
error_information: Option<BankOfAmericaErrorInformation>,
fraud_marking_information: Option<FraudMarkingInformation>,
risk_information: Option<ClientRiskInformation>,
token_information: Option<BankOfAmericaTokenInformation>,
reconciliation_id: Option<String>,
consumer_authentication_information: Option<ConsumerAuthenticationInformation>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FraudMarkingInformation {
reason: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplicationInformation {
status: Option<BankofamericaPaymentStatus>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BankOfAmericaTransactionResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BankOfAmericaTransactionResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.application_information.status {
Some(app_status) => {
let status =
map_boa_attempt_status((app_status, item.data.request.is_auto_capture()?));
let connector_response = match item.data.payment_method {
common_enums::PaymentMethod::Card => item
.response
.processor_information
.as_ref()
.and_then(|processor_information| {
item.response
.consumer_authentication_information
.as_ref()
.map(|consumer_auth_information| {
convert_to_additional_payment_method_connector_response(
processor_information,
consumer_auth_information,
)
})
})
.map(ConnectorResponseData::with_additional_payment_method_data),
common_enums::PaymentMethod::CardRedirect
| common_enums::PaymentMethod::PayLater
| common_enums::PaymentMethod::Wallet
| common_enums::PaymentMethod::BankRedirect
| common_enums::PaymentMethod::BankTransfer
| common_enums::PaymentMethod::Crypto
| common_enums::PaymentMethod::BankDebit
| common_enums::PaymentMethod::Reward
| common_enums::PaymentMethod::RealTimePayment
| common_enums::PaymentMethod::MobilePayment
| common_enums::PaymentMethod::Upi
| common_enums::PaymentMethod::Voucher
| common_enums::PaymentMethod::OpenBanking
| common_enums::PaymentMethod::GiftCard => None,
};
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
Ok(Self {
response: Err(get_error_response(
&item.response.error_information,
&risk_info,
Some(status),
item.http_code,
item.response.id.clone(),
)),
status: enums::AttemptStatus::Failure,
connector_response,
..item.data
})
} else {
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
.response
.client_reference_information
.map(|cref| cref.code)
.unwrap_or(Some(item.response.id)),
incremental_authorization_allowed: None,
charges: None,
}),
connector_response,
..item.data
})
}
}
None => Ok(Self {
status: item.data.status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderInformation {
amount_details: Amount,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaCaptureRequest {
order_information: OrderInformation,
client_reference_information: ClientReferenceInformation,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_defined_information: Option<Vec<MerchantDefinedInformation>>,
}
impl TryFrom<&BankOfAmericaRouterData<&PaymentsCaptureRouterData>> for BankOfAmericaCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: &BankOfAmericaRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let merchant_defined_information = value
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
order_information: OrderInformation {
amount_details: Amount {
total_amount: value.amount.to_owned(),
currency: value.router_data.request.currency,
},
},
client_reference_information: ClientReferenceInformation {
code: Some(value.router_data.connector_request_reference_id.clone()),
},
merchant_defined_information,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaVoidRequest {
client_reference_information: ClientReferenceInformation,
reversal_information: ReversalInformation,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_defined_information: Option<Vec<MerchantDefinedInformation>>,
// The connector documentation does not mention the merchantDefinedInformation field for Void requests. But this has been still added because it works!
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReversalInformation {
amount_details: Amount,
reason: String,
}
impl TryFrom<&BankOfAmericaRouterData<&PaymentsCancelRouterData>> for BankOfAmericaVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: &BankOfAmericaRouterData<&PaymentsCancelRouterData>,
) -> Result<Self, Self::Error> {
let merchant_defined_information = value
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
client_reference_information: ClientReferenceInformation {
code: Some(value.router_data.connector_request_reference_id.clone()),
},
reversal_information: ReversalInformation {
amount_details: Amount {
total_amount: value.amount.to_owned(),
currency: value.router_data.request.currency.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "Currency",
},
)?,
},
reason: value
.router_data
.request
.cancellation_reason
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "Cancellation Reason",
})?,
},
merchant_defined_information,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaRefundRequest {
order_information: OrderInformation,
client_reference_information: ClientReferenceInformation,
}
impl<F> TryFrom<&BankOfAmericaRouterData<&RefundsRouterData<F>>> for BankOfAmericaRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BankOfAmericaRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
order_information: OrderInformation {
amount_details: Amount {
total_amount: item.amount.clone(),
currency: item.router_data.request.currency,
},
},
client_reference_information: ClientReferenceInformation {
code: Some(item.router_data.request.refund_id.clone()),
},
})
}
}
impl From<BankOfAmericaRefundResponse> for enums::RefundStatus {
fn from(item: BankOfAmericaRefundResponse) -> Self {
let error_reason = item
.error_information
.and_then(|error_info| error_info.reason);
match item.status {
BankofamericaRefundStatus::Succeeded | BankofamericaRefundStatus::Transmitted => {
Self::Success
}
BankofamericaRefundStatus::Cancelled
| BankofamericaRefundStatus::Failed
| BankofamericaRefundStatus::Voided => Self::Failure,
BankofamericaRefundStatus::Pending => Self::Pending,
BankofamericaRefundStatus::TwoZeroOne => {
if error_reason == Some("PROCESSOR_DECLINED".to_string()) {
Self::Failure
} else {
Self::Pending
}
}
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaRefundResponse {
id: String,
status: BankofamericaRefundStatus,
error_information: Option<BankOfAmericaErrorInformation>,
}
impl TryFrom<RefundsResponseRouterData<Execute, BankOfAmericaRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, BankOfAmericaRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.clone());
let response = if utils::is_refund_failure(refund_status) {
Err(get_error_response(
&item.response.error_information,
&None,
None,
item.http_code,
item.response.id,
))
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BankofamericaRefundStatus {
Succeeded,
Transmitted,
Failed,
Pending,
Voided,
Cancelled,
#[serde(rename = "201")]
TwoZeroOne,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RsyncApplicationInformation {
status: Option<BankofamericaRefundStatus>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaRsyncResponse {
id: String,
application_information: Option<RsyncApplicationInformation>,
error_information: Option<BankOfAmericaErrorInformation>,
}
impl TryFrom<RefundsResponseRouterData<RSync, BankOfAmericaRsyncResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, BankOfAmericaRsyncResponse>,
) -> Result<Self, Self::Error> {
let response = match item
.response
.application_information
.and_then(|application_information| application_information.status)
{
Some(status) => {
let error_reason = item
.response
.error_information
.clone()
.and_then(|error_info| error_info.reason);
let refund_status = match status {
BankofamericaRefundStatus::Succeeded
| BankofamericaRefundStatus::Transmitted => enums::RefundStatus::Success,
BankofamericaRefundStatus::Cancelled
| BankofamericaRefundStatus::Failed
| BankofamericaRefundStatus::Voided => enums::RefundStatus::Failure,
BankofamericaRefundStatus::Pending => enums::RefundStatus::Pending,
BankofamericaRefundStatus::TwoZeroOne => {
if error_reason == Some("PROCESSOR_DECLINED".to_string()) {
enums::RefundStatus::Failure
} else {
enums::RefundStatus::Pending
}
}
};
if utils::is_refund_failure(refund_status) {
if status == BankofamericaRefundStatus::Voided {
Err(get_error_response(
&Some(BankOfAmericaErrorInformation {
message: Some(constants::REFUND_VOIDED.to_string()),
reason: Some(constants::REFUND_VOIDED.to_string()),
details: None,
}),
&None,
None,
item.http_code,
item.response.id.clone(),
))
} else {
Err(get_error_response(
&item.response.error_information,
&None,
None,
item.http_code,
item.response.id.clone(),
))
}
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
})
}
}
None => Ok(RefundsResponseData {
connector_refund_id: item.response.id.clone(),
refund_status: match item.data.response {
Ok(response) => response.refund_status,
Err(_) => common_enums::RefundStatus::Pending,
},
}),
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaStandardErrorResponse {
pub error_information: Option<ErrorInformation>,
pub status: Option<String>,
pub message: Option<String>,
pub reason: Option<String>,
pub details: Option<Vec<Details>>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaServerErrorResponse {
pub status: Option<String>,
pub message: Option<String>,
pub reason: Option<Reason>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Reason {
SystemError,
ServerTimeout,
ServiceTimeout,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct BankOfAmericaAuthenticationErrorResponse {
pub response: AuthenticationErrorInformation,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BankOfAmericaErrorResponse {
AuthenticationError(BankOfAmericaAuthenticationErrorResponse),
StandardError(BankOfAmericaStandardErrorResponse),
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Details {
pub field: String,
pub reason: String,
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct ErrorInformation {
pub message: String,
pub reason: String,
pub details: Option<Vec<Details>>,
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct AuthenticationErrorInformation {
pub rmsg: String,
}
fn get_error_response(
error_data: &Option<BankOfAmericaErrorInformation>,
risk_information: &Option<ClientRiskInformation>,
attempt_status: Option<enums::AttemptStatus>,
status_code: u16,
transaction_id: String,
) -> ErrorResponse {
let avs_message = risk_information
.clone()
.map(|client_risk_information| {
client_risk_information.rules.map(|rules| {
rules
.iter()
.map(|risk_info| {
risk_info.name.clone().map_or("".to_string(), |name| {
format!(" , {}", name.clone().expose())
})
})
.collect::<Vec<String>>()
.join("")
})
})
.unwrap_or(Some("".to_string()));
let detailed_error_info = error_data.to_owned().and_then(|error_info| {
error_info.details.map(|error_details| {
error_details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
})
});
let reason = get_error_reason(
error_data
.clone()
.and_then(|error_details| error_details.message),
detailed_error_info,
avs_message,
);
let error_message = error_data
.clone()
.and_then(|error_details| error_details.reason);
ErrorResponse {
code: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code,
attempt_status,
connector_transaction_id: Some(transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}
}
impl
TryFrom<(
&SetupMandateRouterData,
hyperswitch_domain_models::payment_method_data::Card,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, ccard): (
&SetupMandateRouterData,
hyperswitch_domain_models::payment_method_data::Card,
),
) -> Result<Self, Self::Error> {
if item.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Card 3DS".to_string(),
connector: "BankOfAmerica",
})?
};
let order_information = OrderInformationWithBill::try_from(item)?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information =
item.request.metadata.clone().map(|metadata| {
convert_metadata_to_merchant_defined_info(metadata.peek().to_owned())
});
let payment_information = PaymentInformation::try_from(&ccard)?;
let processing_information = ProcessingInformation::try_from((None, None))?;
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
consumer_authentication_information: None,
merchant_defined_information,
})
}
}
impl TryFrom<(&SetupMandateRouterData, ApplePayWalletData)> for BankOfAmericaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, apple_pay_data): (&SetupMandateRouterData, ApplePayWalletData),
) -> Result<Self, Self::Error> {
let order_information = OrderInformationWithBill::try_from(item)?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information =
item.request.metadata.clone().map(|metadata| {
convert_metadata_to_merchant_defined_info(metadata.peek().to_owned())
});
let payment_information = match item.payment_method_token.clone() {
Some(payment_method_token) => match payment_method_token {
PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
PaymentInformation::try_from(&decrypt_data)?
}
PaymentMethodToken::Token(_) => Err(unimplemented_payment_method!(
"Apple Pay",
"Manual",
"Bank Of America"
))?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Bank Of America"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => Err(unimplemented_payment_method!(
"Google Pay",
"Bank Of America"
))?,
},
None => PaymentInformation::from(&apple_pay_data),
};
let processing_information = ProcessingInformation::try_from((
Some(PaymentSolution::ApplePay),
Some(apple_pay_data.payment_method.network.clone()),
))?;
let ucaf_collection_indicator = match apple_pay_data
.payment_method
.network
.to_lowercase()
.as_str()
{
"mastercard" => Some("2".to_string()),
_ => None,
};
let consumer_authentication_information = Some(BankOfAmericaConsumerAuthInformation {
ucaf_collection_indicator,
cavv: None,
ucaf_authentication_data: None,
xid: None,
directory_server_transaction_id: None,
specification_version: None,
});
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information,
})
}
}
impl TryFrom<(&SetupMandateRouterData, GooglePayWalletData)> for BankOfAmericaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, google_pay_data): (&SetupMandateRouterData, GooglePayWalletData),
) -> Result<Self, Self::Error> {
let order_information = OrderInformationWithBill::try_from(item)?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information =
item.request.metadata.clone().map(|metadata| {
convert_metadata_to_merchant_defined_info(metadata.peek().to_owned())
});
let payment_information = PaymentInformation::from(&google_pay_data);
let processing_information =
ProcessingInformation::try_from((Some(PaymentSolution::GooglePay), None))?;
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information: None,
})
}
}
// specific for setupMandate flow
impl TryFrom<(Option<PaymentSolution>, Option<String>)> for ProcessingInformation {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(solution, network): (Option<PaymentSolution>, Option<String>),
) -> Result<Self, Self::Error> {
let (action_list, action_token_types, authorization_options) =
get_boa_mandate_action_details();
let commerce_indicator = get_commerce_indicator(network);
Ok(Self {
capture: Some(false),
capture_options: None,
action_list,
action_token_types,
authorization_options,
commerce_indicator,
payment_solution: solution.map(String::from),
})
}
}
impl TryFrom<&SetupMandateRouterData> for OrderInformationWithBill {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
let email = item.request.get_email()?;
let bill_to = build_bill_to(item.get_optional_billing(), email)?;
Ok(Self {
amount_details: Amount {
total_amount: "0".to_string(),
currency: item.request.currency,
},
bill_to: Some(bill_to),
})
}
}
impl TryFrom<&hyperswitch_domain_models::payment_method_data::Card> for PaymentInformation {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
ccard: &hyperswitch_domain_models::payment_method_data::Card,
) -> Result<Self, Self::Error> {
let card_type = match ccard.card_network.clone().and_then(get_boa_card_type) {
Some(card_network) => Some(card_network.to_string()),
None => ccard.get_card_issuer().ok().map(String::from),
};
Ok(Self::Cards(Box::new(CardPaymentInformation {
card: Card {
number: ccard.card_number.clone(),
expiration_month: ccard.card_exp_month.clone(),
expiration_year: ccard.card_exp_year.clone(),
security_code: ccard.card_cvc.clone(),
card_type,
},
})))
}
}
impl TryFrom<&Box<ApplePayPredecryptData>> for PaymentInformation {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(apple_pay_data: &Box<ApplePayPredecryptData>) -> Result<Self, Self::Error> {
let expiration_month = apple_pay_data.get_expiry_month()?;
let expiration_year = apple_pay_data.get_four_digit_expiry_year()?;
Ok(Self::ApplePay(Box::new(ApplePayPaymentInformation {
tokenized_card: TokenizedCard {
number: apple_pay_data.application_primary_account_number.clone(),
cryptogram: apple_pay_data
.payment_data
.online_payment_cryptogram
.clone(),
transaction_type: TransactionType::ApplePay,
expiration_year,
expiration_month,
},
})))
}
}
impl From<&ApplePayWalletData> for PaymentInformation {
fn from(apple_pay_data: &ApplePayWalletData) -> Self {
Self::ApplePayToken(Box::new(ApplePayTokenPaymentInformation {
fluid_data: FluidData {
value: Secret::from(apple_pay_data.payment_data.clone()),
descriptor: None,
},
tokenized_card: ApplePayTokenizedCard {
transaction_type: TransactionType::ApplePay,
},
}))
}
}
impl From<&GooglePayWalletData> for PaymentInformation {
fn from(google_pay_data: &GooglePayWalletData) -> Self {
Self::GooglePay(Box::new(GooglePayPaymentInformation {
fluid_data: FluidData {
value: Secret::from(
consts::BASE64_ENGINE.encode(google_pay_data.tokenization_data.token.clone()),
),
descriptor: None,
},
}))
}
}
fn convert_to_error_response_from_error_info(
error_response: &BankOfAmericaErrorInformationResponse,
status_code: u16,
) -> ErrorResponse {
let detailed_error_info =
error_response
.error_information
.to_owned()
.details
.map(|error_details| {
error_details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message.to_owned(),
detailed_error_info,
None,
);
ErrorResponse {
code: error_response
.error_information
.reason
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_response
.error_information
.reason
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}
}
fn get_boa_mandate_action_details() -> (
Option<Vec<BankOfAmericaActionsList>>,
Option<Vec<BankOfAmericaActionsTokenType>>,
Option<BankOfAmericaAuthorizationOptions>,
) {
(
Some(vec![BankOfAmericaActionsList::TokenCreate]),
Some(vec![
BankOfAmericaActionsTokenType::PaymentInstrument,
BankOfAmericaActionsTokenType::Customer,
]),
Some(BankOfAmericaAuthorizationOptions {
initiator: Some(BankOfAmericaPaymentInitiator {
initiator_type: Some(BankOfAmericaPaymentInitiatorTypes::Customer),
credential_stored_on_file: Some(true),
stored_credential_used: None,
}),
merchant_intitiated_transaction: None,
}),
)
}
fn get_commerce_indicator(network: Option<String>) -> String {
match network {
Some(card_network) => match card_network.to_lowercase().as_str() {
"amex" => "aesk",
"discover" => "dipb",
"mastercard" => "spa",
"visa" => "internet",
_ => "internet",
},
None => "internet",
}
.to_string()
}
pub fn get_error_reason(
error_info: Option<String>,
detailed_error_info: Option<String>,
avs_error_info: Option<String>,
) -> Option<String> {
match (error_info, detailed_error_info, avs_error_info) {
(Some(message), Some(details), Some(avs_message)) => Some(format!(
"{}, detailed_error_information: {}, avs_message: {}",
message, details, avs_message
)),
(Some(message), Some(details), None) => Some(format!(
"{}, detailed_error_information: {}",
message, details
)),
(Some(message), None, Some(avs_message)) => {
Some(format!("{}, avs_message: {}", message, avs_message))
}
(None, Some(details), Some(avs_message)) => {
Some(format!("{}, avs_message: {}", details, avs_message))
}
(Some(message), None, None) => Some(message),
(None, Some(details), None) => Some(details),
(None, None, Some(avs_message)) => Some(avs_message),
(None, None, None) => None,
}
}
| 19,206 | 2,249 |
hyperswitch | crates/common_types/Cargo.toml | .toml | [package]
name = "common_types"
description = "Types shared across the request/response types and database types"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[features]
default = []
v1 = ["common_utils/v1"]
v2 = ["common_utils/v2"]
[dependencies]
diesel = "2.2.3"
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
strum = { version = "0.26", features = ["derive"] }
utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] }
common_enums = { version = "0.1.0", path = "../common_enums" }
common_utils = { version = "0.1.0", path = "../common_utils"}
euclid = { version = "0.1.0", path = "../euclid" }
[lints]
workspace = true
| 229 | 2,250 |
hyperswitch | crates/common_types/src/payments.rs | .rs | //! Payment related types
use std::collections::HashMap;
use common_enums::enums;
use common_utils::{errors, events, impl_to_sql_from_sql_json, types::MinorUnit};
use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow};
use euclid::frontend::{
ast::Program,
dir::{DirKeyKind, EuclidDirFilter},
};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::domain::{AdyenSplitData, XenditSplitSubMerchantData};
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
/// Fee information for Split Payments to be charged on the payment being collected
pub enum SplitPaymentsRequest {
/// StripeSplitPayment
StripeSplitPayment(StripeSplitPaymentRequest),
/// AdyenSplitPayment
AdyenSplitPayment(AdyenSplitData),
/// XenditSplitPayment
XenditSplitPayment(XenditSplitRequest),
}
impl_to_sql_from_sql_json!(SplitPaymentsRequest);
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
/// Fee information for Split Payments to be charged on the payment being collected for Stripe
pub struct StripeSplitPaymentRequest {
/// Stripe's charge type
#[schema(value_type = PaymentChargeType, example = "direct")]
pub charge_type: enums::PaymentChargeType,
/// Platform fees to be collected on the payment
#[schema(value_type = i64, example = 6540)]
pub application_fees: MinorUnit,
/// Identifier for the reseller's account where the funds were transferred
pub transfer_account_id: String,
}
impl_to_sql_from_sql_json!(StripeSplitPaymentRequest);
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
/// Hashmap to store mca_id's with product names
pub struct AuthenticationConnectorAccountMap(
HashMap<enums::AuthenticationProduct, common_utils::id_type::MerchantConnectorAccountId>,
);
impl_to_sql_from_sql_json!(AuthenticationConnectorAccountMap);
impl AuthenticationConnectorAccountMap {
/// fn to get click to pay connector_account_id
pub fn get_click_to_pay_connector_account_id(
&self,
) -> Result<common_utils::id_type::MerchantConnectorAccountId, errors::ValidationError> {
self.0
.get(&enums::AuthenticationProduct::ClickToPay)
.ok_or(errors::ValidationError::MissingRequiredField {
field_name: "authentication_product_id.click_to_pay".to_string(),
})
.cloned()
}
}
#[derive(
Serialize, Default, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
/// ConditionalConfigs
pub struct ConditionalConfigs {
/// Override 3DS
pub override_3ds: Option<common_enums::AuthenticationType>,
}
impl EuclidDirFilter for ConditionalConfigs {
const ALLOWED: &'static [DirKeyKind] = &[
DirKeyKind::PaymentMethod,
DirKeyKind::CardType,
DirKeyKind::CardNetwork,
DirKeyKind::MetaData,
DirKeyKind::PaymentAmount,
DirKeyKind::PaymentCurrency,
DirKeyKind::CaptureMethod,
DirKeyKind::BillingCountry,
DirKeyKind::BusinessCountry,
];
}
impl_to_sql_from_sql_json!(ConditionalConfigs);
#[derive(Serialize, Deserialize, Debug, Clone, FromSqlRow, AsExpression, ToSchema)]
#[diesel(sql_type = Jsonb)]
/// DecisionManagerRecord
pub struct DecisionManagerRecord {
/// Name of the Decision Manager
pub name: String,
/// Program to be executed
pub program: Program<ConditionalConfigs>,
/// Created at timestamp
pub created_at: i64,
}
impl events::ApiEventMetric for DecisionManagerRecord {
fn get_api_event_type(&self) -> Option<events::ApiEventsType> {
Some(events::ApiEventsType::Routing)
}
}
impl_to_sql_from_sql_json!(DecisionManagerRecord);
/// DecisionManagerResponse
pub type DecisionManagerResponse = DecisionManagerRecord;
/// Fee information to be charged on the payment being collected via Stripe
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
pub struct StripeChargeResponseData {
/// Identifier for charge created for the payment
pub charge_id: Option<String>,
/// Type of charge (connector specific)
#[schema(value_type = PaymentChargeType, example = "direct")]
pub charge_type: enums::PaymentChargeType,
/// Platform fees collected on the payment
#[schema(value_type = i64, example = 6540)]
pub application_fees: MinorUnit,
/// Identifier for the reseller's account where the funds were transferred
pub transfer_account_id: String,
}
impl_to_sql_from_sql_json!(StripeChargeResponseData);
/// Charge Information
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum ConnectorChargeResponseData {
/// StripeChargeResponseData
StripeSplitPayment(StripeChargeResponseData),
/// AdyenChargeResponseData
AdyenSplitPayment(AdyenSplitData),
/// XenditChargeResponseData
XenditSplitPayment(XenditChargeResponseData),
}
impl_to_sql_from_sql_json!(ConnectorChargeResponseData);
/// Fee information to be charged on the payment being collected via xendit
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
pub struct XenditSplitRoute {
/// Amount of payments to be split
pub flat_amount: Option<MinorUnit>,
/// Amount of payments to be split, using a percent rate as unit
pub percent_amount: Option<i64>,
/// Currency code
#[schema(value_type = Currency, example = "USD")]
pub currency: enums::Currency,
/// ID of the destination account where the amount will be routed to
pub destination_account_id: String,
/// Reference ID which acts as an identifier of the route itself
pub reference_id: String,
}
impl_to_sql_from_sql_json!(XenditSplitRoute);
/// Fee information to be charged on the payment being collected via xendit
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
pub struct XenditMultipleSplitRequest {
/// Name to identify split rule. Not required to be unique. Typically based on transaction and/or sub-merchant types.
pub name: String,
/// Description to identify fee rule
pub description: String,
/// The sub-account user-id that you want to make this transaction for.
pub for_user_id: Option<String>,
/// Array of objects that define how the platform wants to route the fees and to which accounts.
pub routes: Vec<XenditSplitRoute>,
}
impl_to_sql_from_sql_json!(XenditMultipleSplitRequest);
/// Xendit Charge Request
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum XenditSplitRequest {
/// Split Between Multiple Accounts
MultipleSplits(XenditMultipleSplitRequest),
/// Collect Fee for Single Account
SingleSplit(XenditSplitSubMerchantData),
}
impl_to_sql_from_sql_json!(XenditSplitRequest);
/// Charge Information
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum XenditChargeResponseData {
/// Split Between Multiple Accounts
MultipleSplits(XenditMultipleSplitResponse),
/// Collect Fee for Single Account
SingleSplit(XenditSplitSubMerchantData),
}
impl_to_sql_from_sql_json!(XenditChargeResponseData);
/// Fee information charged on the payment being collected via xendit
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
pub struct XenditMultipleSplitResponse {
/// Identifier for split rule created for the payment
pub split_rule_id: String,
/// The sub-account user-id that you want to make this transaction for.
pub for_user_id: Option<String>,
/// Name to identify split rule. Not required to be unique. Typically based on transaction and/or sub-merchant types.
pub name: String,
/// Description to identify fee rule
pub description: String,
/// Array of objects that define how the platform wants to route the fees and to which accounts.
pub routes: Vec<XenditSplitRoute>,
}
impl_to_sql_from_sql_json!(XenditMultipleSplitResponse);
| 2,103 | 2,251 |
hyperswitch | crates/common_types/src/domain.rs | .rs | //! Common types
use common_enums::enums;
use common_utils::{impl_to_sql_from_sql_json, types::MinorUnit};
use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
/// Fee information for Split Payments to be charged on the payment being collected for Adyen
pub struct AdyenSplitData {
/// The store identifier
pub store: Option<String>,
/// Data for the split items
pub split_items: Vec<AdyenSplitItem>,
}
impl_to_sql_from_sql_json!(AdyenSplitData);
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
/// Data for the split items
pub struct AdyenSplitItem {
/// The amount of the split item
#[schema(value_type = i64, example = 6540)]
pub amount: Option<MinorUnit>,
/// Defines type of split item
#[schema(value_type = AdyenSplitType, example = "BalanceAccount")]
pub split_type: enums::AdyenSplitType,
/// The unique identifier of the account to which the split amount is allocated.
pub account: Option<String>,
/// Unique Identifier for the split item
pub reference: String,
/// Description for the part of the payment that will be allocated to the specified account.
pub description: Option<String>,
}
impl_to_sql_from_sql_json!(AdyenSplitItem);
/// Fee information to be charged on the payment being collected for sub-merchant via xendit
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
pub struct XenditSplitSubMerchantData {
/// The sub-account user-id that you want to make this transaction for.
pub for_user_id: String,
}
impl_to_sql_from_sql_json!(XenditSplitSubMerchantData);
| 491 | 2,252 |
hyperswitch | crates/common_types/src/customers.rs | .rs | //! Customer related types
/// HashMap containing MerchantConnectorAccountId and corresponding customer id
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
#[serde(transparent)]
pub struct ConnectorCustomerMap(
std::collections::HashMap<common_utils::id_type::MerchantConnectorAccountId, String>,
);
#[cfg(feature = "v2")]
common_utils::impl_to_sql_from_sql_json!(ConnectorCustomerMap);
#[cfg(feature = "v2")]
impl std::ops::Deref for ConnectorCustomerMap {
type Target =
std::collections::HashMap<common_utils::id_type::MerchantConnectorAccountId, String>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(feature = "v2")]
impl std::ops::DerefMut for ConnectorCustomerMap {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
| 224 | 2,253 |
hyperswitch | crates/common_types/src/primitive_wrappers.rs | .rs | pub use bool_wrappers::*;
mod bool_wrappers {
use std::ops::Deref;
use serde::{Deserialize, Serialize};
/// Bool that represents if Extended Authorization is Applied or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct ExtendedAuthorizationAppliedBool(bool);
impl Deref for ExtendedAuthorizationAppliedBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<bool> for ExtendedAuthorizationAppliedBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for ExtendedAuthorizationAppliedBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for ExtendedAuthorizationAppliedBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Extended Authorization is Requested or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct RequestExtendedAuthorizationBool(bool);
impl Deref for RequestExtendedAuthorizationBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<bool> for RequestExtendedAuthorizationBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl RequestExtendedAuthorizationBool {
/// returns the inner bool value
pub fn is_true(&self) -> bool {
self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for RequestExtendedAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for RequestExtendedAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Extended Authorization is always Requested or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct AlwaysRequestExtendedAuthorization(bool);
impl Deref for AlwaysRequestExtendedAuthorization {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB>
for AlwaysRequestExtendedAuthorization
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for AlwaysRequestExtendedAuthorization
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Cvv should be collected during payment or not. Default is true
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct ShouldCollectCvvDuringPayment(bool);
impl Deref for ShouldCollectCvvDuringPayment {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for ShouldCollectCvvDuringPayment
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for ShouldCollectCvvDuringPayment
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
impl Default for ShouldCollectCvvDuringPayment {
/// Default for `ShouldCollectCvvDuringPayment` is `true`
fn default() -> Self {
Self(true)
}
}
}
| 1,422 | 2,254 |
hyperswitch | crates/common_types/src/consts.rs | .rs | //! Constants that are used in the domain level.
/// API version
#[cfg(feature = "v1")]
pub const API_VERSION: common_enums::ApiVersion = common_enums::ApiVersion::V1;
/// API version
#[cfg(feature = "v2")]
pub const API_VERSION: common_enums::ApiVersion = common_enums::ApiVersion::V2;
| 78 | 2,255 |
hyperswitch | crates/common_types/src/refunds.rs | .rs | //! Refund related types
use common_utils::impl_to_sql_from_sql_json;
use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::domain::{AdyenSplitData, XenditSplitSubMerchantData};
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
/// Charge specific fields for controlling the revert of funds from either platform or connected account. Check sub-fields for more details.
pub enum SplitRefund {
/// StripeSplitRefundRequest
StripeSplitRefund(StripeSplitRefundRequest),
/// AdyenSplitRefundRequest
AdyenSplitRefund(AdyenSplitData),
/// XenditSplitRefundRequest
XenditSplitRefund(XenditSplitSubMerchantData),
}
impl_to_sql_from_sql_json!(SplitRefund);
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
/// Charge specific fields for controlling the revert of funds from either platform or connected account for Stripe. Check sub-fields for more details.
pub struct StripeSplitRefundRequest {
/// Toggle for reverting the application fee that was collected for the payment.
/// If set to false, the funds are pulled from the destination account.
pub revert_platform_fee: Option<bool>,
/// Toggle for reverting the transfer that was made during the charge.
/// If set to false, the funds are pulled from the main platform's account.
pub revert_transfer: Option<bool>,
}
impl_to_sql_from_sql_json!(StripeSplitRefundRequest);
| 400 | 2,256 |
hyperswitch | crates/common_types/src/lib.rs | .rs | //! Types shared across the request/response types and database types
#![warn(missing_docs, missing_debug_implementations)]
pub mod consts;
pub mod customers;
pub mod domain;
pub mod payment_methods;
pub mod payments;
/// types that are wrappers around primitive types
pub mod primitive_wrappers;
pub mod refunds;
| 64 | 2,257 |
hyperswitch | crates/common_types/src/payment_methods.rs | .rs | //! Common types to be used in payment methods
use diesel::{
backend::Backend,
deserialize,
deserialize::FromSql,
serialize::ToSql,
sql_types::{Json, Jsonb},
AsExpression, Queryable,
};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
/// Details of all the payment methods enabled for the connector for the given merchant account
// sql_type for this can be json instead of jsonb. This is because validation at database is not required since it will always be written by the application.
// This is a performance optimization to avoid json validation at database level.
// jsonb enables faster querying on json columns, but it doesn't justify here since we are not querying on this column.
// https://docs.rs/diesel/latest/diesel/sql_types/struct.Jsonb.html
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, AsExpression)]
#[serde(deny_unknown_fields)]
#[diesel(sql_type = Json)]
pub struct PaymentMethodsEnabled {
/// Type of payment method.
#[schema(value_type = PaymentMethod,example = "card")]
pub payment_method_type: common_enums::PaymentMethod,
/// Payment method configuration, this includes all the filters associated with the payment method
pub payment_method_subtypes: Option<Vec<RequestPaymentMethodTypes>>,
}
// Custom FromSql implmentation to handle deserialization of v1 data format
impl FromSql<Json, diesel::pg::Pg> for PaymentMethodsEnabled {
fn from_sql(bytes: <diesel::pg::Pg as Backend>::RawValue<'_>) -> deserialize::Result<Self> {
let helper: PaymentMethodsEnabledHelper = serde_json::from_slice(bytes.as_bytes())
.map_err(|e| Box::new(diesel::result::Error::DeserializationError(Box::new(e))))?;
Ok(helper.into())
}
}
// In this ToSql implementation, we are directly serializing the PaymentMethodsEnabled struct to JSON
impl ToSql<Json, diesel::pg::Pg> for PaymentMethodsEnabled {
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>,
) -> diesel::serialize::Result {
let value = serde_json::to_value(self)?;
// the function `reborrow` only works in case of `Pg` backend. But, in case of other backends
// please refer to the diesel migration blog:
// https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations
<serde_json::Value as ToSql<Json, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow())
}
}
// Intermediate type to handle deserialization of v1 data format of PaymentMethodsEnabled
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum PaymentMethodsEnabledHelper {
V2 {
payment_method_type: common_enums::PaymentMethod,
payment_method_subtypes: Option<Vec<RequestPaymentMethodTypes>>,
},
V1 {
payment_method: common_enums::PaymentMethod,
payment_method_types: Option<Vec<RequestPaymentMethodTypesV1>>,
},
}
impl From<PaymentMethodsEnabledHelper> for PaymentMethodsEnabled {
fn from(helper: PaymentMethodsEnabledHelper) -> Self {
match helper {
PaymentMethodsEnabledHelper::V2 {
payment_method_type,
payment_method_subtypes,
} => Self {
payment_method_type,
payment_method_subtypes,
},
PaymentMethodsEnabledHelper::V1 {
payment_method,
payment_method_types,
} => Self {
payment_method_type: payment_method,
payment_method_subtypes: payment_method_types.map(|subtypes| {
subtypes
.into_iter()
.map(RequestPaymentMethodTypes::from)
.collect()
}),
},
}
}
}
impl PaymentMethodsEnabled {
/// Get payment_method_type
#[cfg(feature = "v2")]
pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> {
Some(self.payment_method_type)
}
/// Get payment_method_subtypes
#[cfg(feature = "v2")]
pub fn get_payment_method_type(&self) -> Option<&Vec<RequestPaymentMethodTypes>> {
self.payment_method_subtypes.as_ref()
}
}
/// Details of a specific payment method subtype enabled for the connector for the given merchant account
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq, Hash)]
pub struct RequestPaymentMethodTypes {
/// The payment method subtype
#[schema(value_type = PaymentMethodType)]
pub payment_method_subtype: common_enums::PaymentMethodType,
/// The payment experience for the payment method
#[schema(value_type = Option<PaymentExperience>)]
pub payment_experience: Option<common_enums::PaymentExperience>,
/// List of cards networks that are enabled for this payment method, applicable for credit and debit payment method subtypes only
#[schema(value_type = Option<Vec<CardNetwork>>)]
pub card_networks: Option<Vec<common_enums::CardNetwork>>,
/// List of currencies accepted or has the processing capabilities of the processor
#[schema(example = json!(
{
"type": "enable_only",
"list": ["USD", "INR"]
}
), value_type = Option<AcceptedCurrencies>)]
pub accepted_currencies: Option<AcceptedCurrencies>,
/// List of Countries accepted or has the processing capabilities of the processor
#[schema(example = json!(
{
"type": "enable_only",
"list": ["UK", "AU"]
}
), value_type = Option<AcceptedCountries>)]
pub accepted_countries: Option<AcceptedCountries>,
/// Minimum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents)
#[schema(example = 1)]
pub minimum_amount: Option<common_utils::types::MinorUnit>,
/// Maximum amount supported by the processor. To be represented in the lowest denomination of
/// the target currency (For example, for USD it should be in cents)
#[schema(example = 1313)]
pub maximum_amount: Option<common_utils::types::MinorUnit>,
/// Boolean to enable recurring payments / mandates. Default is true.
#[schema(default = true, example = false)]
pub recurring_enabled: bool,
/// Boolean to enable installment / EMI / BNPL payments. Default is true.
#[schema(default = true, example = false)]
pub installment_payment_enabled: bool,
}
impl From<RequestPaymentMethodTypesV1> for RequestPaymentMethodTypes {
fn from(value: RequestPaymentMethodTypesV1) -> Self {
Self {
payment_method_subtype: value.payment_method_type,
payment_experience: value.payment_experience,
card_networks: value.card_networks,
accepted_currencies: value.accepted_currencies,
accepted_countries: value.accepted_countries,
minimum_amount: value.minimum_amount,
maximum_amount: value.maximum_amount,
recurring_enabled: value.recurring_enabled,
installment_payment_enabled: value.installment_payment_enabled,
}
}
}
#[derive(serde::Deserialize)]
struct RequestPaymentMethodTypesV1 {
pub payment_method_type: common_enums::PaymentMethodType,
pub payment_experience: Option<common_enums::PaymentExperience>,
pub card_networks: Option<Vec<common_enums::CardNetwork>>,
pub accepted_currencies: Option<AcceptedCurrencies>,
pub accepted_countries: Option<AcceptedCountries>,
pub minimum_amount: Option<common_utils::types::MinorUnit>,
pub maximum_amount: Option<common_utils::types::MinorUnit>,
pub recurring_enabled: bool,
pub installment_payment_enabled: bool,
}
impl RequestPaymentMethodTypes {
///Get payment_method_subtype
pub fn get_payment_method_type(&self) -> Option<common_enums::PaymentMethodType> {
Some(self.payment_method_subtype)
}
}
#[derive(PartialEq, Eq, Hash, Debug, Clone, serde::Serialize, Deserialize, ToSchema)]
#[serde(
deny_unknown_fields,
tag = "type",
content = "list",
rename_all = "snake_case"
)]
/// Object to filter the countries for which the payment method subtype is enabled
pub enum AcceptedCountries {
/// Only enable the payment method subtype for specific countries
#[schema(value_type = Vec<CountryAlpha2>)]
EnableOnly(Vec<common_enums::CountryAlpha2>),
/// Only disable the payment method subtype for specific countries
#[schema(value_type = Vec<CountryAlpha2>)]
DisableOnly(Vec<common_enums::CountryAlpha2>),
/// Enable the payment method subtype for all countries, in which the processor has the processing capabilities
AllAccepted,
}
#[derive(PartialEq, Eq, Hash, Debug, Clone, serde::Serialize, Deserialize, ToSchema)]
#[serde(
deny_unknown_fields,
tag = "type",
content = "list",
rename_all = "snake_case"
)]
/// Object to filter the countries for which the payment method subtype is enabled
pub enum AcceptedCurrencies {
/// Only enable the payment method subtype for specific currencies
#[schema(value_type = Vec<Currency>)]
EnableOnly(Vec<common_enums::Currency>),
/// Only disable the payment method subtype for specific currencies
#[schema(value_type = Vec<Currency>)]
DisableOnly(Vec<common_enums::Currency>),
/// Enable the payment method subtype for all currencies, in which the processor has the processing capabilities
AllAccepted,
}
impl<DB> Queryable<Jsonb, DB> for PaymentMethodsEnabled
where
DB: Backend,
Self: FromSql<Jsonb, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
/// The network tokenization configuration for creating the payment method session
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct NetworkTokenization {
/// Enable the network tokenization for payment methods that are created using the payment method session
#[schema(value_type = NetworkTokenizationToggle)]
pub enable: common_enums::NetworkTokenizationToggle,
}
/// The Payment Service Provider Configuration for payment methods that are created using the payment method session
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct PspTokenization {
/// The tokenization type to be applied for the payment method
#[schema(value_type = TokenizationType)]
pub tokenization_type: common_enums::TokenizationType,
/// The merchant connector id to be used for tokenization
#[schema(value_type = String)]
pub connector_id: common_utils::id_type::MerchantConnectorAccountId,
}
| 2,319 | 2,258 |
hyperswitch | crates/openapi/Cargo.toml | .toml | [package]
name = "openapi"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[dependencies]
# Third party crates
serde_json = "1.0.115"
utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order", "time"] }
# First party crates
api_models = { version = "0.1.0", path = "../api_models", features = ["frm", "payouts", "openapi"] }
common_utils = { version = "0.1.0", path = "../common_utils", features = ["logs"] }
common_types = { version = "0.1.0", path = "../common_types" }
router_env = { version = "0.1.0", path = "../router_env" }
[features]
v2 = ["api_models/v2", "api_models/customer_v2", "common_utils/v2", "api_models/payment_methods_v2", "common_utils/payment_methods_v2"]
v1 = ["api_models/v1", "common_utils/v1"]
[lints]
workspace = true
| 250 | 2,259 |
hyperswitch | crates/openapi/src/openapi_v2.rs | .rs | use crate::routes;
#[derive(utoipa::OpenApi)]
#[openapi(
info(
title = "Hyperswitch - API Documentation",
contact(
name = "Hyperswitch Support",
url = "https://hyperswitch.io",
email = "hyperswitch@juspay.in"
),
// terms_of_service = "https://www.juspay.io/terms",
description = r#"
## Get started
Hyperswitch provides a collection of APIs that enable you to process and manage payments.
Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes.
You can consume the APIs directly using your favorite HTTP/REST library.
We have a testing environment referred to "sandbox", which you can setup to test API calls without
affecting production data.
Currently, our sandbox environment is live while our production environment is under development
and will be available soon.
You can sign up on our Dashboard to get API keys to access Hyperswitch API.
### Environment
Use the following base URLs when making requests to the APIs:
| Environment | Base URL |
|---------------|------------------------------------|
| Sandbox | <https://sandbox.hyperswitch.io> |
| Production | <https://api.hyperswitch.io> |
## Authentication
When you sign up on our [dashboard](https://app.hyperswitch.io) and create a merchant
account, you are given a secret key (also referred as api-key) and a publishable key.
You may authenticate all API requests with Hyperswitch server by providing the appropriate key in
the request Authorization header.
| Key | Description |
|-----------------|-----------------------------------------------------------------------------------------------|
| api-key | Private key. Used to authenticate all API requests from your merchant server |
| publishable key | Unique identifier for your account. Used to authenticate API requests from your app's client |
Never share your secret api keys. Keep them guarded and secure.
"#,
),
servers(
(url = "https://sandbox.hyperswitch.io", description = "Sandbox Environment")
),
tags(
(name = "Merchant Account", description = "Create and manage merchant accounts"),
(name = "Profile", description = "Create and manage profiles"),
(name = "Merchant Connector Account", description = "Create and manage merchant connector accounts"),
(name = "Payments", description = "Create and manage one-time payments, recurring payments and mandates"),
(name = "Refunds", description = "Create and manage refunds for successful payments"),
(name = "Mandates", description = "Manage mandates"),
(name = "Customers", description = "Create and manage customers"),
(name = "Payment Methods", description = "Create and manage payment methods of customers"),
(name = "Disputes", description = "Manage disputes"),
(name = "API Key", description = "Create and manage API Keys"),
(name = "Payouts", description = "Create and manage payouts"),
(name = "payment link", description = "Create payment link"),
(name = "Routing", description = "Create and manage routing configurations"),
(name = "Event", description = "Manage events"),
),
// The paths will be displayed in the same order as they are registered here
paths(
// Routes for Organization
routes::organization::organization_create,
routes::organization::organization_retrieve,
routes::organization::organization_update,
routes::organization::merchant_account_list,
// Routes for merchant connector account
routes::merchant_connector_account::connector_create,
routes::merchant_connector_account::connector_retrieve,
routes::merchant_connector_account::connector_update,
routes::merchant_connector_account::connector_delete,
// Routes for merchant account
routes::merchant_account::merchant_account_create,
routes::merchant_account::merchant_account_retrieve,
routes::merchant_account::merchant_account_update,
routes::merchant_account::profiles_list,
// Routes for profile
routes::profile::profile_create,
routes::profile::profile_retrieve,
routes::profile::profile_update,
routes::profile::connector_list,
// Routes for routing under profile
routes::profile::routing_link_config,
routes::profile::routing_unlink_config,
routes::profile::routing_update_default_config,
routes::profile::routing_retrieve_default_config,
routes::profile::routing_retrieve_linked_config,
// Routes for routing
routes::routing::routing_create_config,
routes::routing::routing_retrieve_config,
// Routes for api keys
routes::api_keys::api_key_create,
routes::api_keys::api_key_retrieve,
routes::api_keys::api_key_update,
routes::api_keys::api_key_revoke,
routes::api_keys::api_key_list,
//Routes for customers
routes::customers::customers_create,
routes::customers::customers_retrieve,
routes::customers::customers_update,
routes::customers::customers_delete,
routes::customers::customers_list,
//Routes for payments
routes::payments::payments_create_intent,
routes::payments::payments_get_intent,
routes::payments::payments_update_intent,
routes::payments::payments_confirm_intent,
routes::payments::payment_status,
routes::payments::payments_create_and_confirm_intent,
routes::payments::payments_connector_session,
routes::payments::list_payment_methods,
routes::payments::payments_list,
//Routes for payment methods
routes::payment_method::create_payment_method_api,
routes::payment_method::create_payment_method_intent_api,
routes::payment_method::confirm_payment_method_intent_api,
routes::payment_method::payment_method_update_api,
routes::payment_method::payment_method_retrieve_api,
routes::payment_method::payment_method_delete_api,
routes::payment_method::list_customer_payment_method_api,
//Routes for payment method session
routes::payment_method::payment_method_session_create,
routes::payment_method::payment_method_session_retrieve,
routes::payment_method::payment_method_session_list_payment_methods,
routes::payment_method::payment_method_session_update_saved_payment_method,
routes::payment_method::payment_method_session_delete_saved_payment_method,
routes::payment_method::payment_method_session_confirm,
//Routes for refunds
routes::refunds::refunds_create,
// Routes for Revenue Recovery flow under Process Tracker
routes::revenue_recovery::revenue_recovery_pt_retrieve_api
),
components(schemas(
common_utils::types::MinorUnit,
common_utils::types::TimeRange,
common_utils::types::BrowserInformation,
common_utils::link_utils::GenericLinkUiConfig,
common_utils::link_utils::EnabledPaymentMethod,
common_utils::payout_method_utils::AdditionalPayoutMethodData,
common_utils::payout_method_utils::CardAdditionalData,
common_utils::payout_method_utils::BankAdditionalData,
common_utils::payout_method_utils::WalletAdditionalData,
common_utils::payout_method_utils::AchBankTransferAdditionalData,
common_utils::payout_method_utils::BacsBankTransferAdditionalData,
common_utils::payout_method_utils::SepaBankTransferAdditionalData,
common_utils::payout_method_utils::PixBankTransferAdditionalData,
common_utils::payout_method_utils::PaypalAdditionalData,
common_utils::payout_method_utils::VenmoAdditionalData,
common_types::payments::SplitPaymentsRequest,
common_types::payments::StripeSplitPaymentRequest,
common_types::domain::AdyenSplitData,
common_types::payments::XenditSplitRequest,
common_types::payments::XenditSplitRoute,
common_types::payments::XenditChargeResponseData,
common_types::payments::XenditMultipleSplitResponse,
common_types::payments::XenditMultipleSplitRequest,
common_types::domain::XenditSplitSubMerchantData,
common_types::domain::AdyenSplitItem,
common_types::refunds::StripeSplitRefundRequest,
common_utils::types::ChargeRefunds,
common_types::payment_methods::PaymentMethodsEnabled,
common_types::payment_methods::PspTokenization,
common_types::payment_methods::NetworkTokenization,
common_types::refunds::SplitRefund,
common_types::payments::ConnectorChargeResponseData,
common_types::payments::StripeChargeResponseData,
api_models::refunds::RefundRequest,
api_models::refunds::RefundsCreateRequest,
api_models::refunds::RefundErrorDetails,
api_models::refunds::RefundType,
api_models::refunds::RefundResponse,
api_models::refunds::RefundStatus,
api_models::refunds::RefundUpdateRequest,
api_models::organization::OrganizationCreateRequest,
api_models::organization::OrganizationUpdateRequest,
api_models::organization::OrganizationResponse,
api_models::admin::MerchantAccountCreateWithoutOrgId,
api_models::admin::MerchantAccountUpdate,
api_models::admin::MerchantAccountDeleteResponse,
api_models::admin::MerchantConnectorDeleteResponse,
api_models::admin::MerchantConnectorResponse,
api_models::admin::MerchantConnectorListResponse,
api_models::admin::AuthenticationConnectorDetails,
api_models::admin::ExtendedCardInfoConfig,
api_models::admin::BusinessGenericLinkConfig,
api_models::admin::BusinessCollectLinkConfig,
api_models::admin::BusinessPayoutLinkConfig,
api_models::admin::MerchantConnectorAccountFeatureMetadata,
api_models::admin::RevenueRecoveryMetadata,
api_models::customers::CustomerRequest,
api_models::customers::CustomerUpdateRequest,
api_models::customers::CustomerDeleteResponse,
api_models::ephemeral_key::ResourceId,
api_models::payment_methods::PaymentMethodCreate,
api_models::payment_methods::PaymentMethodIntentCreate,
api_models::payment_methods::PaymentMethodIntentConfirm,
api_models::payment_methods::AuthenticationDetails,
api_models::payment_methods::PaymentMethodResponse,
api_models::payment_methods::PaymentMethodResponseData,
api_models::payment_methods::CustomerPaymentMethod,
api_models::payment_methods::PaymentMethodListRequest,
api_models::payment_methods::PaymentMethodListResponse,
api_models::payment_methods::ResponsePaymentMethodsEnabled,
api_models::payment_methods::PaymentMethodSubtypeSpecificData,
api_models::payment_methods::ResponsePaymentMethodTypes,
api_models::payment_methods::PaymentExperienceTypes,
api_models::payment_methods::CardNetworkTypes,
api_models::payment_methods::BankDebitTypes,
api_models::payment_methods::BankTransferTypes,
api_models::payment_methods::CustomerPaymentMethodsListResponse,
api_models::payment_methods::PaymentMethodDeleteResponse,
api_models::payment_methods::PaymentMethodUpdate,
api_models::payment_methods::PaymentMethodUpdateData,
api_models::payment_methods::CardDetailFromLocker,
api_models::payment_methods::PaymentMethodCreateData,
api_models::payment_methods::CardDetail,
api_models::payment_methods::CardDetailUpdate,
api_models::payment_methods::CardType,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::payment_methods::CardType,
api_models::payment_methods::PaymentMethodListData,
api_models::poll::PollResponse,
api_models::poll::PollStatus,
api_models::customers::CustomerResponse,
api_models::admin::AcceptedCountries,
api_models::admin::AcceptedCurrencies,
api_models::enums::AdyenSplitType,
api_models::enums::ProductType,
api_models::enums::PaymentType,
api_models::enums::ScaExemptionType,
api_models::enums::PaymentMethod,
api_models::enums::PaymentMethodType,
api_models::enums::ConnectorType,
api_models::enums::PayoutConnectors,
api_models::enums::AuthenticationConnectors,
api_models::enums::Currency,
api_models::enums::IntentStatus,
api_models::enums::CaptureMethod,
api_models::enums::FutureUsage,
api_models::enums::AuthenticationType,
api_models::enums::Connector,
api_models::enums::PaymentMethod,
api_models::enums::PaymentMethodIssuerCode,
api_models::enums::MandateStatus,
api_models::enums::MerchantProductType,
api_models::enums::PaymentExperience,
api_models::enums::BankNames,
api_models::enums::BankType,
api_models::enums::BankHolderType,
api_models::enums::CardNetwork,
api_models::enums::DisputeStage,
api_models::enums::DisputeStatus,
api_models::enums::CountryAlpha2,
api_models::enums::CountryAlpha3,
api_models::enums::FieldType,
api_models::enums::FrmAction,
api_models::enums::FrmPreferredFlowTypes,
api_models::enums::RetryAction,
api_models::enums::AttemptStatus,
api_models::enums::CaptureStatus,
api_models::enums::ReconStatus,
api_models::enums::ConnectorStatus,
api_models::enums::AuthorizationStatus,
api_models::enums::ElementPosition,
api_models::enums::ElementSize,
api_models::enums::SizeVariants,
api_models::enums::MerchantProductType,
api_models::enums::PaymentLinkDetailsLayout,
api_models::enums::PaymentMethodStatus,
api_models::enums::PaymentConnectorCategory,
api_models::enums::FeatureStatus,
api_models::enums::OrderFulfillmentTimeOrigin,
api_models::enums::UIWidgetFormLayout,
api_models::enums::MerchantProductType,
api_models::enums::CtpServiceProvider,
api_models::admin::MerchantConnectorCreate,
api_models::admin::AdditionalMerchantData,
api_models::admin::CardTestingGuardConfig,
api_models::admin::CardTestingGuardStatus,
api_models::admin::ConnectorWalletDetails,
api_models::admin::MerchantRecipientData,
api_models::admin::MerchantAccountData,
api_models::admin::MerchantConnectorUpdate,
api_models::admin::PrimaryBusinessDetails,
api_models::admin::FrmConfigs,
api_models::admin::FrmPaymentMethod,
api_models::admin::FrmPaymentMethodType,
api_models::admin::MerchantConnectorDetailsWrap,
api_models::admin::MerchantConnectorDetails,
api_models::admin::MerchantConnectorWebhookDetails,
api_models::admin::ProfileCreate,
api_models::admin::ProfileResponse,
api_models::admin::BusinessPaymentLinkConfig,
api_models::admin::PaymentLinkBackgroundImageConfig,
api_models::admin::PaymentLinkConfigRequest,
api_models::admin::PaymentLinkConfig,
api_models::admin::PaymentLinkTransactionDetails,
api_models::admin::TransactionDetailsUiConfiguration,
api_models::disputes::DisputeResponse,
api_models::disputes::DisputeResponsePaymentsRetrieve,
api_models::gsm::GsmCreateRequest,
api_models::gsm::GsmRetrieveRequest,
api_models::gsm::GsmUpdateRequest,
api_models::gsm::GsmDeleteRequest,
api_models::gsm::GsmDeleteResponse,
api_models::gsm::GsmResponse,
api_models::gsm::GsmDecision,
api_models::payments::AddressDetails,
api_models::payments::BankDebitData,
api_models::payments::AliPayQr,
api_models::payments::PaymentAttemptFeatureMetadata,
api_models::payments::PaymentAttemptRevenueRecoveryData,
api_models::payments::AliPayRedirection,
api_models::payments::MomoRedirection,
api_models::payments::TouchNGoRedirection,
api_models::payments::GcashRedirection,
api_models::payments::KakaoPayRedirection,
api_models::payments::AliPayHkRedirection,
api_models::payments::GoPayRedirection,
api_models::payments::MbWayRedirection,
api_models::payments::MobilePayRedirection,
api_models::payments::WeChatPayRedirection,
api_models::payments::WeChatPayQr,
api_models::payments::BankDebitBilling,
api_models::payments::CryptoData,
api_models::payments::RewardData,
api_models::payments::UpiData,
api_models::payments::UpiCollectData,
api_models::payments::UpiIntentData,
api_models::payments::VoucherData,
api_models::payments::BoletoVoucherData,
api_models::payments::AlfamartVoucherData,
api_models::payments::IndomaretVoucherData,
api_models::payments::Address,
api_models::payments::VoucherData,
api_models::payments::JCSVoucherData,
api_models::payments::AlfamartVoucherData,
api_models::payments::IndomaretVoucherData,
api_models::payments::BankRedirectData,
api_models::payments::RealTimePaymentData,
api_models::payments::BankRedirectBilling,
api_models::payments::BankRedirectBilling,
api_models::payments::ConnectorMetadata,
api_models::payments::FeatureMetadata,
api_models::payments::SdkType,
api_models::payments::ApplepayConnectorMetadataRequest,
api_models::payments::SessionTokenInfo,
api_models::payments::PaymentProcessingDetailsAt,
api_models::payments::ApplepayInitiative,
api_models::payments::PaymentProcessingDetails,
api_models::payments::PaymentMethodDataResponseWithBilling,
api_models::payments::PaymentMethodDataResponse,
api_models::payments::CardResponse,
api_models::payments::PaylaterResponse,
api_models::payments::KlarnaSdkPaymentMethodResponse,
api_models::payments::SwishQrData,
api_models::payments::AirwallexData,
api_models::payments::BraintreeData,
api_models::payments::NoonData,
api_models::payments::OrderDetailsWithAmount,
api_models::payments::NextActionType,
api_models::payments::WalletData,
api_models::payments::NextActionData,
api_models::payments::PayLaterData,
api_models::payments::MandateData,
api_models::payments::PhoneDetails,
api_models::payments::PaymentMethodData,
api_models::payments::PaymentMethodDataRequest,
api_models::payments::MandateType,
api_models::payments::AcceptanceType,
api_models::payments::MandateAmountData,
api_models::payments::OnlineMandate,
api_models::payments::Card,
api_models::payments::CardRedirectData,
api_models::payments::CardToken,
api_models::payments::CustomerAcceptance,
api_models::payments::ConnectorTokenDetails,
api_models::payments::PaymentsRequest,
api_models::payments::PaymentsResponse,
api_models::payments::PaymentsListResponseItem,
api_models::payments::PaymentRetrieveBody,
api_models::payments::PaymentsRetrieveRequest,
api_models::payments::PaymentsCaptureRequest,
api_models::payments::PaymentsSessionRequest,
api_models::payments::PaymentsSessionResponse,
api_models::payments::PaymentsCreateIntentRequest,
api_models::payments::PaymentsUpdateIntentRequest,
api_models::payments::PaymentsIntentResponse,
api_models::payments::PazeWalletData,
api_models::payments::AmountDetails,
api_models::payments::AmountDetailsUpdate,
api_models::payments::SessionToken,
api_models::payments::ApplePaySessionResponse,
api_models::payments::ThirdPartySdkSessionResponse,
api_models::payments::NoThirdPartySdkSessionResponse,
api_models::payments::SecretInfoToInitiateSdk,
api_models::payments::ApplePayPaymentRequest,
api_models::payments::ApplePayBillingContactFields,
api_models::payments::ApplePayShippingContactFields,
api_models::payments::ApplePayAddressParameters,
api_models::payments::ApplePayRecurringPaymentRequest,
api_models::payments::ApplePayRegularBillingRequest,
api_models::payments::ApplePayPaymentTiming,
api_models::payments::RecurringPaymentIntervalUnit,
api_models::payments::ApplePayRecurringDetails,
api_models::payments::ApplePayRegularBillingDetails,
api_models::payments::AmountInfo,
api_models::payments::GooglePayWalletData,
api_models::payments::PayPalWalletData,
api_models::payments::PaypalRedirection,
api_models::payments::GpayMerchantInfo,
api_models::payments::GpayAllowedPaymentMethods,
api_models::payments::GpayAllowedMethodsParameters,
api_models::payments::GpayTokenizationSpecification,
api_models::payments::GpayTokenParameters,
api_models::payments::GpayTransactionInfo,
api_models::payments::GpaySessionTokenResponse,
api_models::payments::GooglePayThirdPartySdkData,
api_models::payments::KlarnaSessionTokenResponse,
api_models::payments::PaypalSessionTokenResponse,
api_models::payments::ApplepaySessionTokenResponse,
api_models::payments::SdkNextAction,
api_models::payments::NextActionCall,
api_models::payments::SdkNextActionData,
api_models::payments::SamsungPayWalletData,
api_models::payments::WeChatPay,
api_models::payments::GpayTokenizationData,
api_models::payments::GooglePayPaymentMethodInfo,
api_models::payments::ApplePayWalletData,
api_models::payments::ApplepayPaymentMethod,
api_models::payments::PazeSessionTokenResponse,
api_models::payments::SamsungPaySessionTokenResponse,
api_models::payments::SamsungPayMerchantPaymentInformation,
api_models::payments::SamsungPayAmountDetails,
api_models::payments::SamsungPayAmountFormat,
api_models::payments::SamsungPayProtocolType,
api_models::payments::SamsungPayWalletCredentials,
api_models::payments::SamsungPayWebWalletData,
api_models::payments::SamsungPayAppWalletData,
api_models::payments::SamsungPayCardBrand,
api_models::payments::SamsungPayTokenData,
api_models::payments::PaymentsCancelRequest,
api_models::payments::PaymentListResponse,
api_models::payments::CashappQr,
api_models::payments::BankTransferData,
api_models::payments::BankTransferNextStepsData,
api_models::payments::SepaAndBacsBillingDetails,
api_models::payments::AchBillingDetails,
api_models::payments::MultibancoBillingDetails,
api_models::payments::DokuBillingDetails,
api_models::payments::BankTransferInstructions,
api_models::payments::MobilePaymentNextStepData,
api_models::payments::MobilePaymentConsent,
api_models::payments::IframeData,
api_models::payments::ReceiverDetails,
api_models::payments::AchTransfer,
api_models::payments::MultibancoTransferInstructions,
api_models::payments::DokuBankTransferInstructions,
api_models::payments::AmazonPayRedirectData,
api_models::payments::ApplePayRedirectData,
api_models::payments::ApplePayThirdPartySdkData,
api_models::payments::GooglePayRedirectData,
api_models::payments::GooglePayThirdPartySdk,
api_models::mandates::NetworkTransactionIdAndCardDetails,
api_models::payments::GooglePaySessionResponse,
api_models::payments::GpayShippingAddressParameters,
api_models::payments::GpayBillingAddressParameters,
api_models::payments::GpayBillingAddressFormat,
api_models::payments::SepaBankTransferInstructions,
api_models::payments::BacsBankTransferInstructions,
api_models::payments::RedirectResponse,
api_models::payments::RequestSurchargeDetails,
api_models::payments::PaymentRevenueRecoveryMetadata,
api_models::payments::BillingConnectorPaymentDetails,
api_models::enums::PaymentConnectorTransmission,
api_models::enums::TriggeredBy,
api_models::payments::PaymentAttemptResponse,
api_models::payments::PaymentAttemptAmountDetails,
api_models::payments::CaptureResponse,
api_models::payments::PaymentsIncrementalAuthorizationRequest,
api_models::payments::IncrementalAuthorizationResponse,
api_models::payments::PaymentsCompleteAuthorizeRequest,
api_models::payments::PaymentsExternalAuthenticationRequest,
api_models::payments::PaymentsExternalAuthenticationResponse,
api_models::payments::SdkInformation,
api_models::payments::DeviceChannel,
api_models::payments::ThreeDsCompletionIndicator,
api_models::payments::MifinityData,
api_models::payments::ClickToPaySessionResponse,
api_models::enums::TransactionStatus,
api_models::payments::PaymentCreatePaymentLinkConfig,
api_models::payments::ThreeDsData,
api_models::payments::ThreeDsMethodData,
api_models::payments::PollConfigResponse,
api_models::payments::ExternalAuthenticationDetailsResponse,
api_models::payments::ExtendedCardInfo,
api_models::payments::PaymentsConfirmIntentRequest,
api_models::payments::AmountDetailsResponse,
api_models::payments::BankCodeResponse,
api_models::payments::Order,
api_models::payments::SortOn,
api_models::payments::SortBy,
api_models::payments::PaymentMethodListResponseForPayments,
api_models::payments::ResponsePaymentMethodTypesForPayments,
api_models::payment_methods::CardNetworkTokenizeRequest,
api_models::payment_methods::CardNetworkTokenizeResponse,
api_models::payment_methods::CardType,
api_models::payment_methods::RequiredFieldInfo,
api_models::payment_methods::MaskedBankDetails,
api_models::payment_methods::SurchargeDetailsResponse,
api_models::payment_methods::SurchargeResponse,
api_models::payment_methods::SurchargePercentage,
api_models::payment_methods::PaymentMethodCollectLinkRequest,
api_models::payment_methods::PaymentMethodCollectLinkResponse,
api_models::payment_methods::PaymentMethodSubtypeSpecificData,
api_models::payment_methods::PaymentMethodSessionRequest,
api_models::payment_methods::PaymentMethodSessionResponse,
api_models::payment_methods::PaymentMethodsSessionUpdateRequest,
api_models::payment_methods::NetworkTokenResponse,
api_models::payment_methods::NetworkTokenDetailsPaymentMethod,
api_models::payment_methods::TokenizeCardRequest,
api_models::payment_methods::TokenizeDataRequest,
api_models::payment_methods::TokenizePaymentMethodRequest,
api_models::refunds::RefundListRequest,
api_models::refunds::RefundListResponse,
api_models::payments::AmountFilter,
api_models::mandates::MandateRevokedResponse,
api_models::mandates::MandateResponse,
api_models::mandates::MandateCardDetails,
api_models::mandates::RecurringDetails,
api_models::mandates::ProcessorPaymentToken,
api_models::ephemeral_key::ClientSecretResponse,
api_models::payments::CustomerDetails,
api_models::payments::GiftCardData,
api_models::payments::GiftCardDetails,
api_models::payments::MobilePaymentData,
api_models::payments::MobilePaymentResponse,
api_models::payments::Address,
api_models::payouts::CardPayout,
api_models::payouts::Wallet,
api_models::payouts::Paypal,
api_models::payouts::Venmo,
api_models::payouts::AchBankTransfer,
api_models::payouts::BacsBankTransfer,
api_models::payouts::SepaBankTransfer,
api_models::payouts::PixBankTransfer,
api_models::payouts::PayoutRequest,
api_models::payouts::PayoutAttemptResponse,
api_models::payouts::PayoutActionRequest,
api_models::payouts::PayoutCreateRequest,
api_models::payouts::PayoutCreateResponse,
api_models::payouts::PayoutListConstraints,
api_models::payouts::PayoutListFilterConstraints,
api_models::payouts::PayoutListResponse,
api_models::payouts::PayoutRetrieveBody,
api_models::payouts::PayoutRetrieveRequest,
api_models::payouts::PayoutMethodData,
api_models::payouts::PayoutMethodDataResponse,
api_models::payouts::PayoutLinkResponse,
api_models::payouts::Bank,
api_models::payouts::PayoutCreatePayoutLinkConfig,
api_models::enums::PayoutEntityType,
api_models::enums::PayoutSendPriority,
api_models::enums::PayoutStatus,
api_models::enums::PayoutType,
api_models::enums::TransactionType,
api_models::enums::PresenceOfCustomerDuringPayment,
api_models::enums::MitExemptionRequest,
api_models::enums::EnablePaymentLinkRequest,
api_models::enums::RequestIncrementalAuthorization,
api_models::enums::External3dsAuthenticationRequest,
api_models::enums::TaxCalculationOverride,
api_models::enums::SurchargeCalculationOverride,
api_models::payments::FrmMessage,
api_models::webhooks::OutgoingWebhook,
api_models::webhooks::OutgoingWebhookContent,
api_models::enums::EventClass,
api_models::enums::EventType,
api_models::enums::DecoupledAuthenticationType,
api_models::enums::AuthenticationStatus,
api_models::enums::UpdateActiveAttempt,
api_models::admin::MerchantAccountResponse,
api_models::admin::MerchantConnectorId,
api_models::admin::MerchantDetails,
api_models::admin::ToggleKVRequest,
api_models::admin::ToggleKVResponse,
api_models::admin::WebhookDetails,
api_models::api_keys::ApiKeyExpiration,
api_models::api_keys::CreateApiKeyRequest,
api_models::api_keys::CreateApiKeyResponse,
api_models::api_keys::RetrieveApiKeyResponse,
api_models::api_keys::RevokeApiKeyResponse,
api_models::api_keys::UpdateApiKeyRequest,
api_models::payments::RetrievePaymentLinkRequest,
api_models::payments::PaymentLinkResponse,
api_models::payments::RetrievePaymentLinkResponse,
api_models::payments::PaymentLinkInitiateRequest,
api_models::payouts::PayoutLinkInitiateRequest,
api_models::payments::ExtendedCardInfoResponse,
api_models::payments::GooglePayAssuranceDetails,
api_models::routing::RoutingConfigRequest,
api_models::routing::RoutingDictionaryRecord,
api_models::routing::RoutingKind,
api_models::routing::RoutableConnectorChoice,
api_models::routing::LinkedRoutingConfigRetrieveResponse,
api_models::routing::RoutingRetrieveResponse,
api_models::routing::ProfileDefaultRoutingConfig,
api_models::routing::MerchantRoutingAlgorithm,
api_models::routing::RoutingAlgorithmKind,
api_models::routing::RoutingDictionary,
api_models::routing::RoutingAlgorithm,
api_models::routing::StraightThroughAlgorithm,
api_models::routing::ConnectorVolumeSplit,
api_models::routing::ConnectorSelection,
api_models::routing::ast::RoutableChoiceKind,
api_models::enums::RoutableConnectors,
api_models::routing::ast::ProgramConnectorSelection,
api_models::routing::ast::RuleConnectorSelection,
api_models::routing::ast::IfStatement,
api_models::routing::ast::Comparison,
api_models::routing::ast::ComparisonType,
api_models::routing::ast::ValueType,
api_models::routing::ast::MetadataValue,
api_models::routing::ast::NumberComparison,
api_models::routing::RoutingAlgorithmId,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::payments::PaymentLinkStatus,
api_models::blocklist::BlocklistRequest,
api_models::blocklist::BlocklistResponse,
api_models::blocklist::ToggleBlocklistResponse,
api_models::blocklist::ListBlocklistQuery,
api_models::enums::BlocklistDataKind,
api_models::enums::ErrorCategory,
api_models::webhook_events::EventListItemResponse,
api_models::webhook_events::EventRetrieveResponse,
api_models::webhook_events::OutgoingWebhookRequestContent,
api_models::webhook_events::OutgoingWebhookResponseContent,
api_models::enums::WebhookDeliveryAttempt,
api_models::enums::PaymentChargeType,
api_models::enums::StripeChargeType,
api_models::payments::CustomerDetailsResponse,
api_models::payments::OpenBankingData,
api_models::payments::OpenBankingSessionToken,
api_models::payments::BankDebitResponse,
api_models::payments::BankRedirectResponse,
api_models::payments::BankTransferResponse,
api_models::payments::CardRedirectResponse,
api_models::payments::CardTokenResponse,
api_models::payments::CryptoResponse,
api_models::payments::GiftCardResponse,
api_models::payments::OpenBankingResponse,
api_models::payments::RealTimePaymentDataResponse,
api_models::payments::UpiResponse,
api_models::payments::VoucherResponse,
api_models::payments::additional_info::CardTokenAdditionalData,
api_models::payments::additional_info::BankDebitAdditionalData,
api_models::payments::additional_info::AchBankDebitAdditionalData,
api_models::payments::additional_info::BacsBankDebitAdditionalData,
api_models::payments::additional_info::BecsBankDebitAdditionalData,
api_models::payments::additional_info::SepaBankDebitAdditionalData,
api_models::payments::additional_info::BankRedirectDetails,
api_models::payments::additional_info::BancontactBankRedirectAdditionalData,
api_models::payments::additional_info::BlikBankRedirectAdditionalData,
api_models::payments::additional_info::GiropayBankRedirectAdditionalData,
api_models::payments::additional_info::BankTransferAdditionalData,
api_models::payments::additional_info::PixBankTransferAdditionalData,
api_models::payments::additional_info::LocalBankTransferAdditionalData,
api_models::payments::additional_info::GiftCardAdditionalData,
api_models::payments::additional_info::GivexGiftCardAdditionalData,
api_models::payments::additional_info::UpiAdditionalData,
api_models::payments::additional_info::UpiCollectAdditionalData,
api_models::payments::additional_info::WalletAdditionalDataForCard,
api_models::payments::WalletResponse,
api_models::payments::WalletResponseData,
api_models::payments::PaymentsDynamicTaxCalculationRequest,
api_models::payments::PaymentsDynamicTaxCalculationResponse,
api_models::payments::DisplayAmountOnSdk,
api_models::payments::ErrorDetails,
api_models::payments::CtpServiceDetails,
api_models::feature_matrix::FeatureMatrixListResponse,
api_models::feature_matrix::FeatureMatrixRequest,
api_models::feature_matrix::ConnectorFeatureMatrixResponse,
api_models::feature_matrix::PaymentMethodSpecificFeatures,
api_models::feature_matrix::CardSpecificFeatures,
api_models::feature_matrix::SupportedPaymentMethod,
api_models::payment_methods::PaymentMethodSessionUpdateSavedPaymentMethod,
api_models::payment_methods::PaymentMethodSessionDeleteSavedPaymentMethod,
common_utils::types::BrowserInformation,
api_models::enums::TokenizationType,
api_models::enums::NetworkTokenizationToggle,
api_models::payments::PaymentAmountDetailsResponse,
api_models::payment_methods::PaymentMethodSessionConfirmRequest,
api_models::payment_methods::PaymentMethodSessionResponse,
api_models::payment_methods::AuthenticationDetails,
api_models::process_tracker::revenue_recovery::RevenueRecoveryResponse,
api_models::enums::ProcessTrackerStatus,
routes::payments::ForceSync,
)),
modifiers(&SecurityAddon)
)]
// Bypass clippy lint for not being constructed
#[allow(dead_code)]
pub(crate) struct ApiDoc;
struct SecurityAddon;
impl utoipa::Modify for SecurityAddon {
fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) {
use utoipa::openapi::security::{ApiKey, ApiKeyValue, SecurityScheme};
if let Some(components) = openapi.components.as_mut() {
components.add_security_schemes_from_iter([
(
"api_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Use the API key created under your merchant account from the HyperSwitch dashboard. API key is used to authenticate API requests from your merchant server only. Don't expose this key on a website or embed it in a mobile application."
))),
),
(
"admin_api_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Admin API keys allow you to perform some privileged actions such as \
creating a merchant account and Connector account."
))),
),
(
"publishable_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Publishable keys are a type of keys that can be public and have limited \
scope of usage."
))),
),
(
"ephemeral_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Ephemeral keys provide temporary access to singular data, such as access \
to a single customer object for a short period of time."
))),
),
]);
}
}
}
| 8,051 | 2,260 |
hyperswitch | crates/openapi/src/openapi.rs | .rs | use crate::routes;
#[derive(utoipa::OpenApi)]
#[openapi(
info(
title = "Hyperswitch - API Documentation",
contact(
name = "Hyperswitch Support",
url = "https://hyperswitch.io",
email = "hyperswitch@juspay.in"
),
// terms_of_service = "https://www.juspay.io/terms",
description = r#"
## Get started
Hyperswitch provides a collection of APIs that enable you to process and manage payments.
Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes.
You can consume the APIs directly using your favorite HTTP/REST library.
We have a testing environment referred to "sandbox", which you can setup to test API calls without
affecting production data.
Currently, our sandbox environment is live while our production environment is under development
and will be available soon.
You can sign up on our Dashboard to get API keys to access Hyperswitch API.
### Environment
Use the following base URLs when making requests to the APIs:
| Environment | Base URL |
|---------------|------------------------------------|
| Sandbox | <https://sandbox.hyperswitch.io> |
| Production | <https://api.hyperswitch.io> |
## Authentication
When you sign up on our [dashboard](https://app.hyperswitch.io) and create a merchant
account, you are given a secret key (also referred as api-key) and a publishable key.
You may authenticate all API requests with Hyperswitch server by providing the appropriate key in
the request Authorization header.
| Key | Description |
|-----------------|-----------------------------------------------------------------------------------------------|
| api-key | Private key. Used to authenticate all API requests from your merchant server |
| publishable key | Unique identifier for your account. Used to authenticate API requests from your app's client |
Never share your secret api keys. Keep them guarded and secure.
"#,
),
servers(
(url = "https://sandbox.hyperswitch.io", description = "Sandbox Environment")
),
tags(
(name = "Merchant Account", description = "Create and manage merchant accounts"),
(name = "Profile", description = "Create and manage profiles"),
(name = "Merchant Connector Account", description = "Create and manage merchant connector accounts"),
(name = "Payments", description = "Create and manage one-time payments, recurring payments and mandates"),
(name = "Refunds", description = "Create and manage refunds for successful payments"),
(name = "Mandates", description = "Manage mandates"),
(name = "Customers", description = "Create and manage customers"),
(name = "Payment Methods", description = "Create and manage payment methods of customers"),
(name = "Disputes", description = "Manage disputes"),
(name = "API Key", description = "Create and manage API Keys"),
(name = "Payouts", description = "Create and manage payouts"),
(name = "payment link", description = "Create payment link"),
(name = "Routing", description = "Create and manage routing configurations"),
(name = "Event", description = "Manage events"),
),
// The paths will be displayed in the same order as they are registered here
paths(
// Routes for payments
routes::payments::payments_create,
routes::payments::payments_update,
routes::payments::payments_confirm,
routes::payments::payments_retrieve,
routes::payments::payments_capture,
routes::payments::payments_connector_session,
routes::payments::payments_cancel,
routes::payments::payments_list,
routes::payments::payments_incremental_authorization,
routes::payment_link::payment_link_retrieve,
routes::payments::payments_external_authentication,
routes::payments::payments_complete_authorize,
routes::payments::payments_post_session_tokens,
// Routes for relay
routes::relay::relay,
routes::relay::relay_retrieve,
// Routes for refunds
routes::refunds::refunds_create,
routes::refunds::refunds_retrieve,
routes::refunds::refunds_update,
routes::refunds::refunds_list,
// Routes for Organization
routes::organization::organization_create,
routes::organization::organization_retrieve,
routes::organization::organization_update,
// Routes for merchant account
routes::merchant_account::merchant_account_create,
routes::merchant_account::retrieve_merchant_account,
routes::merchant_account::update_merchant_account,
routes::merchant_account::delete_merchant_account,
routes::merchant_account::merchant_account_kv_status,
// Routes for merchant connector account
routes::merchant_connector_account::connector_create,
routes::merchant_connector_account::connector_retrieve,
routes::merchant_connector_account::connector_list,
routes::merchant_connector_account::connector_update,
routes::merchant_connector_account::connector_delete,
//Routes for gsm
routes::gsm::create_gsm_rule,
routes::gsm::get_gsm_rule,
routes::gsm::update_gsm_rule,
routes::gsm::delete_gsm_rule,
// Routes for mandates
routes::mandates::get_mandate,
routes::mandates::revoke_mandate,
routes::mandates::customers_mandates_list,
//Routes for customers
routes::customers::customers_create,
routes::customers::customers_retrieve,
routes::customers::customers_list,
routes::customers::customers_update,
routes::customers::customers_delete,
//Routes for payment methods
routes::payment_method::create_payment_method_api,
routes::payment_method::list_payment_method_api,
routes::payment_method::list_customer_payment_method_api,
routes::payment_method::list_customer_payment_method_api_client,
routes::payment_method::default_payment_method_set_api,
routes::payment_method::payment_method_retrieve_api,
routes::payment_method::payment_method_update_api,
routes::payment_method::payment_method_delete_api,
// Routes for Profile
routes::profile::profile_create,
routes::profile::profile_list,
routes::profile::profile_retrieve,
routes::profile::profile_update,
routes::profile::profile_delete,
// Routes for disputes
routes::disputes::retrieve_dispute,
routes::disputes::retrieve_disputes_list,
// Routes for routing
routes::routing::routing_create_config,
routes::routing::routing_link_config,
routes::routing::routing_retrieve_config,
routes::routing::list_routing_configs,
routes::routing::routing_unlink_config,
routes::routing::routing_update_default_config,
routes::routing::routing_retrieve_default_config,
routes::routing::routing_retrieve_linked_config,
routes::routing::routing_retrieve_default_config_for_profiles,
routes::routing::routing_update_default_config_for_profile,
routes::routing::success_based_routing_update_configs,
routes::routing::toggle_success_based_routing,
routes::routing::toggle_elimination_routing,
routes::routing::contract_based_routing_setup_config,
routes::routing::contract_based_routing_update_configs,
// Routes for blocklist
routes::blocklist::remove_entry_from_blocklist,
routes::blocklist::list_blocked_payment_methods,
routes::blocklist::add_entry_to_blocklist,
routes::blocklist::toggle_blocklist_guard,
// Routes for payouts
routes::payouts::payouts_create,
routes::payouts::payouts_retrieve,
routes::payouts::payouts_update,
routes::payouts::payouts_cancel,
routes::payouts::payouts_fulfill,
routes::payouts::payouts_list,
routes::payouts::payouts_confirm,
routes::payouts::payouts_list_filters,
routes::payouts::payouts_list_by_filter,
// Routes for api keys
routes::api_keys::api_key_create,
routes::api_keys::api_key_retrieve,
routes::api_keys::api_key_update,
routes::api_keys::api_key_revoke,
routes::api_keys::api_key_list,
// Routes for events
routes::webhook_events::list_initial_webhook_delivery_attempts,
routes::webhook_events::list_initial_webhook_delivery_attempts_with_jwtauth,
routes::webhook_events::list_webhook_delivery_attempts,
routes::webhook_events::retry_webhook_delivery_attempt,
// Routes for poll apis
routes::poll::retrieve_poll_status,
),
components(schemas(
common_utils::types::MinorUnit,
common_utils::types::TimeRange,
common_utils::link_utils::GenericLinkUiConfig,
common_utils::link_utils::EnabledPaymentMethod,
common_utils::payout_method_utils::AdditionalPayoutMethodData,
common_utils::payout_method_utils::CardAdditionalData,
common_utils::payout_method_utils::BankAdditionalData,
common_utils::payout_method_utils::WalletAdditionalData,
common_utils::payout_method_utils::AchBankTransferAdditionalData,
common_utils::payout_method_utils::BacsBankTransferAdditionalData,
common_utils::payout_method_utils::SepaBankTransferAdditionalData,
common_utils::payout_method_utils::PixBankTransferAdditionalData,
common_utils::payout_method_utils::PaypalAdditionalData,
common_utils::payout_method_utils::VenmoAdditionalData,
common_types::payments::SplitPaymentsRequest,
common_types::payments::StripeSplitPaymentRequest,
common_types::domain::AdyenSplitData,
common_types::domain::AdyenSplitItem,
common_types::payments::XenditSplitRequest,
common_types::payments::XenditSplitRoute,
common_types::payments::XenditChargeResponseData,
common_types::payments::XenditMultipleSplitResponse,
common_types::payments::XenditMultipleSplitRequest,
common_types::domain::XenditSplitSubMerchantData,
common_utils::types::ChargeRefunds,
common_types::refunds::SplitRefund,
common_types::refunds::StripeSplitRefundRequest,
common_types::payments::ConnectorChargeResponseData,
common_types::payments::StripeChargeResponseData,
api_models::refunds::RefundRequest,
api_models::refunds::RefundType,
api_models::refunds::RefundResponse,
api_models::refunds::RefundStatus,
api_models::refunds::RefundUpdateRequest,
api_models::organization::OrganizationCreateRequest,
api_models::organization::OrganizationUpdateRequest,
api_models::organization::OrganizationResponse,
api_models::admin::MerchantAccountCreate,
api_models::admin::MerchantAccountUpdate,
api_models::admin::MerchantAccountDeleteResponse,
api_models::admin::MerchantConnectorDeleteResponse,
api_models::admin::MerchantConnectorResponse,
api_models::admin::MerchantConnectorListResponse,
api_models::admin::AuthenticationConnectorDetails,
api_models::admin::ExtendedCardInfoConfig,
api_models::admin::BusinessGenericLinkConfig,
api_models::admin::BusinessCollectLinkConfig,
api_models::admin::BusinessPayoutLinkConfig,
api_models::admin::CardTestingGuardConfig,
api_models::admin::CardTestingGuardStatus,
api_models::customers::CustomerRequest,
api_models::customers::CustomerUpdateRequest,
api_models::customers::CustomerDeleteResponse,
api_models::payment_methods::PaymentMethodCreate,
api_models::payment_methods::PaymentMethodResponse,
api_models::payment_methods::CustomerPaymentMethod,
api_models::payment_methods::PaymentMethodListResponse,
api_models::payment_methods::ResponsePaymentMethodsEnabled,
api_models::payment_methods::ResponsePaymentMethodTypes,
api_models::payment_methods::PaymentExperienceTypes,
api_models::payment_methods::CardNetworkTypes,
api_models::payment_methods::BankDebitTypes,
api_models::payment_methods::BankTransferTypes,
api_models::payment_methods::CustomerPaymentMethodsListResponse,
api_models::payment_methods::PaymentMethodDeleteResponse,
api_models::payment_methods::PaymentMethodUpdate,
api_models::payment_methods::CustomerDefaultPaymentMethodResponse,
api_models::payment_methods::CardDetailFromLocker,
api_models::payment_methods::PaymentMethodCreateData,
api_models::payment_methods::CardDetail,
api_models::payment_methods::CardDetailUpdate,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::poll::PollResponse,
api_models::poll::PollStatus,
api_models::customers::CustomerResponse,
api_models::admin::AcceptedCountries,
api_models::admin::AcceptedCurrencies,
api_models::enums::AdyenSplitType,
api_models::enums::PaymentType,
api_models::enums::ScaExemptionType,
api_models::enums::PaymentMethod,
api_models::enums::TriggeredBy,
api_models::enums::PaymentMethodType,
api_models::enums::ConnectorType,
api_models::enums::PayoutConnectors,
api_models::enums::AuthenticationConnectors,
api_models::enums::Currency,
api_models::enums::IntentStatus,
api_models::enums::CaptureMethod,
api_models::enums::FutureUsage,
api_models::enums::AuthenticationType,
api_models::enums::Connector,
api_models::enums::PaymentMethod,
api_models::enums::PaymentMethodIssuerCode,
api_models::enums::MandateStatus,
api_models::enums::PaymentExperience,
api_models::enums::BankNames,
api_models::enums::BankType,
api_models::enums::BankHolderType,
api_models::enums::CardNetwork,
api_models::enums::DisputeStage,
api_models::enums::DisputeStatus,
api_models::enums::CountryAlpha2,
api_models::enums::CountryAlpha3,
api_models::enums::FieldType,
api_models::enums::FrmAction,
api_models::enums::FrmPreferredFlowTypes,
api_models::enums::RetryAction,
api_models::enums::AttemptStatus,
api_models::enums::CaptureStatus,
api_models::enums::ReconStatus,
api_models::enums::ConnectorStatus,
api_models::enums::AuthorizationStatus,
api_models::enums::ElementPosition,
api_models::enums::ElementSize,
api_models::enums::SizeVariants,
api_models::enums::MerchantProductType,
api_models::enums::PaymentLinkDetailsLayout,
api_models::enums::PaymentMethodStatus,
api_models::enums::UIWidgetFormLayout,
api_models::enums::MerchantProductType,
api_models::enums::PaymentConnectorCategory,
api_models::enums::CardDiscovery,
api_models::enums::FeatureStatus,
api_models::enums::MerchantProductType,
api_models::enums::CtpServiceProvider,
api_models::admin::MerchantConnectorCreate,
api_models::admin::AdditionalMerchantData,
api_models::admin::ConnectorWalletDetails,
api_models::admin::MerchantRecipientData,
api_models::admin::MerchantAccountData,
api_models::admin::MerchantConnectorUpdate,
api_models::admin::PrimaryBusinessDetails,
api_models::admin::FrmConfigs,
api_models::admin::FrmPaymentMethod,
api_models::admin::FrmPaymentMethodType,
api_models::admin::PaymentMethodsEnabled,
api_models::admin::MerchantConnectorDetailsWrap,
api_models::admin::MerchantConnectorDetails,
api_models::admin::MerchantConnectorWebhookDetails,
api_models::admin::ProfileCreate,
api_models::admin::ProfileResponse,
api_models::admin::BusinessPaymentLinkConfig,
api_models::admin::PaymentLinkBackgroundImageConfig,
api_models::admin::PaymentLinkConfigRequest,
api_models::admin::PaymentLinkConfig,
api_models::admin::PaymentLinkTransactionDetails,
api_models::admin::TransactionDetailsUiConfiguration,
api_models::disputes::DisputeResponse,
api_models::disputes::DisputeResponsePaymentsRetrieve,
api_models::gsm::GsmCreateRequest,
api_models::gsm::GsmRetrieveRequest,
api_models::gsm::GsmUpdateRequest,
api_models::gsm::GsmDeleteRequest,
api_models::gsm::GsmDeleteResponse,
api_models::gsm::GsmResponse,
api_models::gsm::GsmDecision,
api_models::payments::AddressDetails,
api_models::payments::BankDebitData,
api_models::payments::AliPayQr,
api_models::payments::AliPayRedirection,
api_models::payments::MomoRedirection,
api_models::payments::TouchNGoRedirection,
api_models::payments::GcashRedirection,
api_models::payments::KakaoPayRedirection,
api_models::payments::AliPayHkRedirection,
api_models::payments::GoPayRedirection,
api_models::payments::MbWayRedirection,
api_models::payments::MobilePayRedirection,
api_models::payments::WeChatPayRedirection,
api_models::payments::WeChatPayQr,
api_models::payments::BankDebitBilling,
api_models::payments::CryptoData,
api_models::payments::RewardData,
api_models::payments::UpiData,
api_models::payments::UpiCollectData,
api_models::payments::UpiIntentData,
api_models::payments::VoucherData,
api_models::payments::BoletoVoucherData,
api_models::payments::AlfamartVoucherData,
api_models::payments::IndomaretVoucherData,
api_models::payments::Address,
api_models::payments::VoucherData,
api_models::payments::JCSVoucherData,
api_models::payments::AlfamartVoucherData,
api_models::payments::IndomaretVoucherData,
api_models::payments::BankRedirectData,
api_models::payments::RealTimePaymentData,
api_models::payments::BankRedirectBilling,
api_models::payments::BankRedirectBilling,
api_models::payments::ConnectorMetadata,
api_models::payments::FeatureMetadata,
api_models::payments::ApplepayConnectorMetadataRequest,
api_models::payments::SessionTokenInfo,
api_models::payments::PaymentProcessingDetailsAt,
api_models::payments::ApplepayInitiative,
api_models::payments::PaymentProcessingDetails,
api_models::payments::PaymentMethodDataResponseWithBilling,
api_models::payments::PaymentMethodDataResponse,
api_models::payments::CardResponse,
api_models::payments::PaylaterResponse,
api_models::payments::KlarnaSdkPaymentMethodResponse,
api_models::payments::SwishQrData,
api_models::payments::AirwallexData,
api_models::payments::BraintreeData,
api_models::payments::NoonData,
api_models::payments::OrderDetailsWithAmount,
api_models::payments::NextActionType,
api_models::payments::WalletData,
api_models::payments::NextActionData,
api_models::payments::PayLaterData,
api_models::payments::MandateData,
api_models::payments::PhoneDetails,
api_models::payments::PaymentMethodData,
api_models::payments::PaymentMethodDataRequest,
api_models::payments::MandateType,
api_models::payments::AcceptanceType,
api_models::payments::MandateAmountData,
api_models::payments::OnlineMandate,
api_models::payments::Card,
api_models::payments::CardRedirectData,
api_models::payments::CardToken,
api_models::payments::CustomerAcceptance,
api_models::payments::PaymentsRequest,
api_models::payments::PaymentsCreateRequest,
api_models::payments::PaymentsUpdateRequest,
api_models::payments::PaymentsConfirmRequest,
api_models::payments::PaymentsResponse,
api_models::payments::PaymentsCreateResponseOpenApi,
api_models::payments::PaymentRetrieveBody,
api_models::payments::PaymentsRetrieveRequest,
api_models::payments::PaymentsCaptureRequest,
api_models::payments::PaymentsSessionRequest,
api_models::payments::PaymentsSessionResponse,
api_models::payments::PazeWalletData,
api_models::payments::SessionToken,
api_models::payments::ApplePaySessionResponse,
api_models::payments::ThirdPartySdkSessionResponse,
api_models::payments::NoThirdPartySdkSessionResponse,
api_models::payments::SecretInfoToInitiateSdk,
api_models::payments::ApplePayPaymentRequest,
api_models::payments::ApplePayBillingContactFields,
api_models::payments::ApplePayShippingContactFields,
api_models::payments::ApplePayRecurringPaymentRequest,
api_models::payments::ApplePayRegularBillingRequest,
api_models::payments::ApplePayPaymentTiming,
api_models::payments::RecurringPaymentIntervalUnit,
api_models::payments::ApplePayRecurringDetails,
api_models::payments::ApplePayRegularBillingDetails,
api_models::payments::ApplePayAddressParameters,
api_models::payments::AmountInfo,
api_models::payments::ClickToPaySessionResponse,
api_models::enums::ProductType,
api_models::payments::GooglePayWalletData,
api_models::payments::PayPalWalletData,
api_models::payments::PaypalRedirection,
api_models::payments::GpayMerchantInfo,
api_models::payments::GpayAllowedPaymentMethods,
api_models::payments::GpayAllowedMethodsParameters,
api_models::payments::GpayTokenizationSpecification,
api_models::payments::GpayTokenParameters,
api_models::payments::GpayTransactionInfo,
api_models::payments::GpaySessionTokenResponse,
api_models::payments::GooglePayThirdPartySdkData,
api_models::payments::KlarnaSessionTokenResponse,
api_models::payments::PaypalSessionTokenResponse,
api_models::payments::ApplepaySessionTokenResponse,
api_models::payments::SdkNextAction,
api_models::payments::NextActionCall,
api_models::payments::SdkNextActionData,
api_models::payments::SamsungPayWalletData,
api_models::payments::WeChatPay,
api_models::payments::GpayTokenizationData,
api_models::payments::GooglePayPaymentMethodInfo,
api_models::payments::ApplePayWalletData,
api_models::payments::SamsungPayWalletCredentials,
api_models::payments::SamsungPayWebWalletData,
api_models::payments::SamsungPayAppWalletData,
api_models::payments::SamsungPayCardBrand,
api_models::payments::SamsungPayTokenData,
api_models::payments::ApplepayPaymentMethod,
api_models::payments::PaymentsCancelRequest,
api_models::payments::PaymentListConstraints,
api_models::payments::PaymentListResponse,
api_models::payments::CashappQr,
api_models::payments::BankTransferData,
api_models::payments::BankTransferNextStepsData,
api_models::payments::SepaAndBacsBillingDetails,
api_models::payments::AchBillingDetails,
api_models::payments::MultibancoBillingDetails,
api_models::payments::DokuBillingDetails,
api_models::payments::BankTransferInstructions,
api_models::payments::MobilePaymentNextStepData,
api_models::payments::MobilePaymentConsent,
api_models::payments::IframeData,
api_models::payments::ReceiverDetails,
api_models::payments::AchTransfer,
api_models::payments::MultibancoTransferInstructions,
api_models::payments::DokuBankTransferInstructions,
api_models::payments::AmazonPayRedirectData,
api_models::payments::ApplePayRedirectData,
api_models::payments::ApplePayThirdPartySdkData,
api_models::payments::GooglePayRedirectData,
api_models::payments::GooglePayThirdPartySdk,
api_models::payments::GooglePaySessionResponse,
api_models::payments::PazeSessionTokenResponse,
api_models::payments::SamsungPaySessionTokenResponse,
api_models::payments::SamsungPayMerchantPaymentInformation,
api_models::payments::SamsungPayAmountDetails,
api_models::payments::SamsungPayAmountFormat,
api_models::payments::SamsungPayProtocolType,
api_models::payments::GpayShippingAddressParameters,
api_models::payments::GpayBillingAddressParameters,
api_models::payments::GpayBillingAddressFormat,
api_models::payments::SepaBankTransferInstructions,
api_models::payments::BacsBankTransferInstructions,
api_models::payments::RedirectResponse,
api_models::payments::RequestSurchargeDetails,
api_models::payments::PaymentAttemptResponse,
api_models::payments::CaptureResponse,
api_models::payments::PaymentsIncrementalAuthorizationRequest,
api_models::payments::IncrementalAuthorizationResponse,
api_models::payments::PaymentsCompleteAuthorizeRequest,
api_models::payments::PaymentsExternalAuthenticationRequest,
api_models::payments::PaymentsExternalAuthenticationResponse,
api_models::payments::SdkInformation,
api_models::payments::DeviceChannel,
api_models::payments::ThreeDsCompletionIndicator,
api_models::payments::MifinityData,
api_models::enums::TransactionStatus,
api_models::payments::BrowserInformation,
api_models::payments::PaymentCreatePaymentLinkConfig,
api_models::payments::ThreeDsData,
api_models::payments::ThreeDsMethodData,
api_models::payments::PollConfigResponse,
api_models::payments::ExternalAuthenticationDetailsResponse,
api_models::payments::ExtendedCardInfo,
api_models::payment_methods::RequiredFieldInfo,
api_models::payment_methods::DefaultPaymentMethod,
api_models::payment_methods::MaskedBankDetails,
api_models::payment_methods::SurchargeDetailsResponse,
api_models::payment_methods::SurchargeResponse,
api_models::payment_methods::SurchargePercentage,
api_models::payment_methods::PaymentMethodCollectLinkRequest,
api_models::payment_methods::PaymentMethodCollectLinkResponse,
api_models::payment_methods::CardType,
api_models::payment_methods::CardNetworkTokenizeRequest,
api_models::payment_methods::CardNetworkTokenizeResponse,
api_models::payment_methods::TokenizeDataRequest,
api_models::payment_methods::TokenizeCardRequest,
api_models::payment_methods::TokenizePaymentMethodRequest,
api_models::refunds::RefundListRequest,
api_models::refunds::RefundListResponse,
api_models::relay::RelayRequest,
api_models::relay::RelayResponse,
api_models::enums::RelayType,
api_models::relay::RelayData,
api_models::relay::RelayRefundRequestData,
api_models::enums::RelayStatus,
api_models::relay::RelayError,
api_models::payments::AmountFilter,
api_models::mandates::MandateRevokedResponse,
api_models::mandates::MandateResponse,
api_models::mandates::MandateCardDetails,
api_models::mandates::RecurringDetails,
api_models::mandates::NetworkTransactionIdAndCardDetails,
api_models::mandates::ProcessorPaymentToken,
api_models::ephemeral_key::EphemeralKeyCreateResponse,
api_models::payments::CustomerDetails,
api_models::payments::GiftCardData,
api_models::payments::GiftCardDetails,
api_models::payments::MobilePaymentData,
api_models::payments::MobilePaymentResponse,
api_models::payments::Address,
api_models::payments::BankCodeResponse,
api_models::payouts::CardPayout,
api_models::payouts::Wallet,
api_models::payouts::Paypal,
api_models::payouts::Venmo,
api_models::payouts::AchBankTransfer,
api_models::payouts::BacsBankTransfer,
api_models::payouts::SepaBankTransfer,
api_models::payouts::PixBankTransfer,
api_models::payouts::PayoutsCreateRequest,
api_models::payouts::PayoutUpdateRequest,
api_models::payouts::PayoutConfirmRequest,
api_models::payouts::PayoutCancelRequest,
api_models::payouts::PayoutFulfillRequest,
api_models::payouts::PayoutRetrieveRequest,
api_models::payouts::PayoutAttemptResponse,
api_models::payouts::PayoutCreateResponse,
api_models::payouts::PayoutListConstraints,
api_models::payouts::PayoutListFilters,
api_models::payouts::PayoutListFilterConstraints,
api_models::payouts::PayoutListResponse,
api_models::payouts::PayoutRetrieveBody,
api_models::payouts::PayoutMethodData,
api_models::payouts::PayoutMethodDataResponse,
api_models::payouts::PayoutLinkResponse,
api_models::payouts::Bank,
api_models::payouts::PayoutCreatePayoutLinkConfig,
api_models::enums::PayoutEntityType,
api_models::enums::PayoutSendPriority,
api_models::enums::PayoutStatus,
api_models::enums::PayoutType,
api_models::enums::TransactionType,
api_models::payments::FrmMessage,
api_models::webhooks::OutgoingWebhook,
api_models::webhooks::OutgoingWebhookContent,
api_models::enums::EventClass,
api_models::enums::EventType,
api_models::enums::DecoupledAuthenticationType,
api_models::enums::AuthenticationStatus,
api_models::admin::MerchantAccountResponse,
api_models::admin::MerchantConnectorId,
api_models::admin::MerchantDetails,
api_models::admin::ToggleKVRequest,
api_models::admin::ToggleKVResponse,
api_models::admin::WebhookDetails,
api_models::api_keys::ApiKeyExpiration,
api_models::api_keys::CreateApiKeyRequest,
api_models::api_keys::CreateApiKeyResponse,
api_models::api_keys::RetrieveApiKeyResponse,
api_models::api_keys::RevokeApiKeyResponse,
api_models::api_keys::UpdateApiKeyRequest,
api_models::payments::RetrievePaymentLinkRequest,
api_models::payments::PaymentLinkResponse,
api_models::payments::RetrievePaymentLinkResponse,
api_models::payments::PaymentLinkInitiateRequest,
api_models::payouts::PayoutLinkInitiateRequest,
api_models::payments::ExtendedCardInfoResponse,
api_models::payments::GooglePayAssuranceDetails,
api_models::routing::RoutingConfigRequest,
api_models::routing::RoutingDictionaryRecord,
api_models::routing::RoutingKind,
api_models::routing::RoutableConnectorChoice,
api_models::routing::DynamicRoutingFeatures,
api_models::routing::SuccessBasedRoutingConfig,
api_models::routing::DynamicRoutingConfigParams,
api_models::routing::CurrentBlockThreshold,
api_models::routing::SuccessBasedRoutingConfigBody,
api_models::routing::ContractBasedRoutingConfig,
api_models::routing::ContractBasedRoutingConfigBody,
api_models::routing::LabelInformation,
api_models::routing::ContractBasedTimeScale,
api_models::routing::LinkedRoutingConfigRetrieveResponse,
api_models::routing::RoutingRetrieveResponse,
api_models::routing::ProfileDefaultRoutingConfig,
api_models::routing::MerchantRoutingAlgorithm,
api_models::routing::RoutingAlgorithmKind,
api_models::routing::RoutingDictionary,
api_models::routing::RoutingAlgorithm,
api_models::routing::StraightThroughAlgorithm,
api_models::routing::ConnectorVolumeSplit,
api_models::routing::ConnectorSelection,
api_models::routing::SuccessRateSpecificityLevel,
api_models::routing::ToggleDynamicRoutingQuery,
api_models::routing::ToggleDynamicRoutingPath,
api_models::routing::ast::RoutableChoiceKind,
api_models::enums::RoutableConnectors,
api_models::routing::ast::ProgramConnectorSelection,
api_models::routing::ast::RuleConnectorSelection,
api_models::routing::ast::IfStatement,
api_models::routing::ast::Comparison,
api_models::routing::ast::ComparisonType,
api_models::routing::ast::ValueType,
api_models::routing::ast::MetadataValue,
api_models::routing::ast::NumberComparison,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::payments::PaymentLinkStatus,
api_models::blocklist::BlocklistRequest,
api_models::blocklist::BlocklistResponse,
api_models::blocklist::ToggleBlocklistResponse,
api_models::blocklist::ListBlocklistQuery,
api_models::enums::BlocklistDataKind,
api_models::enums::ErrorCategory,
api_models::webhook_events::EventListItemResponse,
api_models::webhook_events::EventRetrieveResponse,
api_models::webhook_events::OutgoingWebhookRequestContent,
api_models::webhook_events::OutgoingWebhookResponseContent,
api_models::webhook_events::TotalEventsResponse,
api_models::enums::WebhookDeliveryAttempt,
api_models::enums::PaymentChargeType,
api_models::enums::StripeChargeType,
api_models::payments::CustomerDetailsResponse,
api_models::payments::SdkType,
api_models::payments::OpenBankingData,
api_models::payments::OpenBankingSessionToken,
api_models::payments::BankDebitResponse,
api_models::payments::BankRedirectResponse,
api_models::payments::BankTransferResponse,
api_models::payments::CardRedirectResponse,
api_models::payments::CardTokenResponse,
api_models::payments::CryptoResponse,
api_models::payments::GiftCardResponse,
api_models::payments::OpenBankingResponse,
api_models::payments::RealTimePaymentDataResponse,
api_models::payments::UpiResponse,
api_models::payments::VoucherResponse,
api_models::payments::additional_info::CardTokenAdditionalData,
api_models::payments::additional_info::BankDebitAdditionalData,
api_models::payments::additional_info::AchBankDebitAdditionalData,
api_models::payments::additional_info::BacsBankDebitAdditionalData,
api_models::payments::additional_info::BecsBankDebitAdditionalData,
api_models::payments::additional_info::SepaBankDebitAdditionalData,
api_models::payments::additional_info::BankRedirectDetails,
api_models::payments::additional_info::BancontactBankRedirectAdditionalData,
api_models::payments::additional_info::BlikBankRedirectAdditionalData,
api_models::payments::additional_info::GiropayBankRedirectAdditionalData,
api_models::payments::additional_info::BankTransferAdditionalData,
api_models::payments::additional_info::PixBankTransferAdditionalData,
api_models::payments::additional_info::LocalBankTransferAdditionalData,
api_models::payments::additional_info::GiftCardAdditionalData,
api_models::payments::additional_info::GivexGiftCardAdditionalData,
api_models::payments::additional_info::UpiAdditionalData,
api_models::payments::additional_info::UpiCollectAdditionalData,
api_models::payments::additional_info::WalletAdditionalDataForCard,
api_models::payments::PaymentsDynamicTaxCalculationRequest,
api_models::payments::WalletResponse,
api_models::payments::WalletResponseData,
api_models::payments::PaymentsDynamicTaxCalculationResponse,
api_models::payments::DisplayAmountOnSdk,
api_models::payments::PaymentsPostSessionTokensRequest,
api_models::payments::PaymentsPostSessionTokensResponse,
api_models::payments::CtpServiceDetails,
api_models::feature_matrix::FeatureMatrixListResponse,
api_models::feature_matrix::FeatureMatrixRequest,
api_models::feature_matrix::ConnectorFeatureMatrixResponse,
api_models::feature_matrix::PaymentMethodSpecificFeatures,
api_models::feature_matrix::CardSpecificFeatures,
api_models::feature_matrix::SupportedPaymentMethod,
)),
modifiers(&SecurityAddon)
)]
// Bypass clippy lint for not being constructed
#[allow(dead_code)]
pub(crate) struct ApiDoc;
struct SecurityAddon;
impl utoipa::Modify for SecurityAddon {
fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) {
use utoipa::openapi::security::{ApiKey, ApiKeyValue, SecurityScheme};
if let Some(components) = openapi.components.as_mut() {
components.add_security_schemes_from_iter([
(
"api_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Use the API key created under your merchant account from the HyperSwitch dashboard. API key is used to authenticate API requests from your merchant server only. Don't expose this key on a website or embed it in a mobile application."
))),
),
(
"admin_api_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Admin API keys allow you to perform some privileged actions such as \
creating a merchant account and Merchant Connector account."
))),
),
(
"publishable_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Publishable keys are a type of keys that can be public and have limited \
scope of usage."
))),
),
(
"ephemeral_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Ephemeral keys provide temporary access to singular data, such as access \
to a single customer object for a short period of time."
))),
),
]);
}
}
}
| 8,140 | 2,261 |
hyperswitch | crates/openapi/src/main.rs | .rs | #[cfg(feature = "v1")]
mod openapi;
#[cfg(feature = "v2")]
mod openapi_v2;
mod routes;
#[allow(clippy::print_stdout)] // Using a logger is not necessary here
fn main() {
#[cfg(all(feature = "v1", feature = "v2"))]
compile_error!("features v1 and v2 are mutually exclusive, please enable only one of them");
#[cfg(feature = "v1")]
let relative_file_path = "api-reference/openapi_spec.json";
#[cfg(feature = "v2")]
let relative_file_path = "api-reference-v2/openapi_spec.json";
#[cfg(any(feature = "v1", feature = "v2"))]
let mut file_path = router_env::workspace_path();
#[cfg(any(feature = "v1", feature = "v2"))]
file_path.push(relative_file_path);
#[cfg(feature = "v1")]
let openapi = <openapi::ApiDoc as utoipa::OpenApi>::openapi();
#[cfg(feature = "v2")]
let openapi = <openapi_v2::ApiDoc as utoipa::OpenApi>::openapi();
#[allow(clippy::expect_used)]
#[cfg(any(feature = "v1", feature = "v2"))]
std::fs::write(
file_path,
openapi
.to_pretty_json()
.expect("Failed to serialize OpenAPI specification as JSON"),
)
.expect("Failed to write OpenAPI specification to file");
#[cfg(any(feature = "v1", feature = "v2"))]
println!("Successfully saved OpenAPI specification file at '{relative_file_path}'");
#[cfg(not(any(feature = "v1", feature = "v2")))]
println!("No feature enabled to generate OpenAPI specification, please enable either 'v1' or 'v2' feature");
}
| 408 | 2,262 |
hyperswitch | crates/openapi/src/lib.rs | .rs | pub mod routes;
| 4 | 2,263 |
hyperswitch | crates/openapi/src/routes.rs | .rs | #![allow(unused)]
pub mod api_keys;
pub mod blocklist;
pub mod customers;
pub mod disputes;
pub mod gsm;
pub mod mandates;
pub mod merchant_account;
pub mod merchant_connector_account;
pub mod organization;
pub mod payment_link;
pub mod payment_method;
pub mod payments;
pub mod payouts;
pub mod poll;
pub mod profile;
pub mod refunds;
pub mod relay;
pub mod revenue_recovery;
pub mod routing;
pub mod webhook_events;
| 95 | 2,264 |
hyperswitch | crates/openapi/src/routes/payment_link.rs | .rs | /// Payments Link - Retrieve
///
/// To retrieve the properties of a Payment Link. This may be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/payment_link/{payment_link_id}",
params(
("payment_link_id" = String, Path, description = "The identifier for payment link")
),
request_body=RetrievePaymentLinkRequest,
responses(
(status = 200, description = "Gets details regarding payment link", body = RetrievePaymentLinkResponse),
(status = 404, description = "No payment link found")
),
tag = "Payments",
operation_id = "Retrieve a Payment Link",
security(("api_key" = []), ("publishable_key" = []))
)]
pub async fn payment_link_retrieve() {}
| 182 | 2,265 |
hyperswitch | crates/openapi/src/routes/merchant_account.rs | .rs | #[cfg(feature = "v1")]
/// Merchant Account - Create
///
/// Create a new account for a *merchant* and the *merchant* could be a seller or retailer or client who likes to receive and send payments.
#[utoipa::path(
post,
path = "/accounts",
request_body(
content = MerchantAccountCreate,
examples(
(
"Create a merchant account with minimal fields" = (
value = json!({"merchant_id": "merchant_abc"})
)
),
(
"Create a merchant account with webhook url" = (
value = json!({
"merchant_id": "merchant_abc",
"webhook_details" : {
"webhook_url": "https://webhook.site/a5c54f75-1f7e-4545-b781-af525b7e37a0"
}
})
)
),
(
"Create a merchant account with return url" = (
value = json!({"merchant_id": "merchant_abc",
"return_url": "https://example.com"})
)
)
)
),
responses(
(status = 200, description = "Merchant Account Created", body = MerchantAccountResponse),
(status = 400, description = "Invalid data")
),
tag = "Merchant Account",
operation_id = "Create a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_create() {}
#[cfg(feature = "v2")]
/// Merchant Account - Create
///
/// Create a new account for a *merchant* and the *merchant* could be a seller or retailer or client who likes to receive and send payments.
///
/// Before creating the merchant account, it is mandatory to create an organization.
#[utoipa::path(
post,
path = "/v2/merchant-accounts",
params(
(
"X-Organization-Id" = String, Header,
description = "Organization ID for which the merchant account has to be created.",
example = json!({"X-Organization-Id": "org_abcdefghijklmnop"})
),
),
request_body(
content = MerchantAccountCreate,
examples(
(
"Create a merchant account with minimal fields" = (
value = json!({
"merchant_name": "Cloth Store",
})
)
),
(
"Create a merchant account with merchant details" = (
value = json!({
"merchant_name": "Cloth Store",
"merchant_details": {
"primary_contact_person": "John Doe",
"primary_email": "example@company.com"
}
})
)
),
(
"Create a merchant account with metadata" = (
value = json!({
"merchant_name": "Cloth Store",
"metadata": {
"key_1": "John Doe",
"key_2": "Trends"
}
})
)
),
)
),
responses(
(status = 200, description = "Merchant Account Created", body = MerchantAccountResponse),
(status = 400, description = "Invalid data")
),
tag = "Merchant Account",
operation_id = "Create a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_create() {}
#[cfg(feature = "v1")]
/// Merchant Account - Retrieve
///
/// Retrieve a *merchant* account details.
#[utoipa::path(
get,
path = "/accounts/{account_id}",
params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Retrieved", body = MerchantAccountResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Retrieve a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn retrieve_merchant_account() {}
#[cfg(feature = "v2")]
/// Merchant Account - Retrieve
///
/// Retrieve a *merchant* account details.
#[utoipa::path(
get,
path = "/v2/merchant-accounts/{id}",
params (("id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Retrieved", body = MerchantAccountResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Retrieve a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_retrieve() {}
#[cfg(feature = "v1")]
/// Merchant Account - Update
///
/// Updates details of an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc
#[utoipa::path(
post,
path = "/accounts/{account_id}",
request_body (
content = MerchantAccountUpdate,
examples(
(
"Update merchant name" = (
value = json!({
"merchant_id": "merchant_abc",
"merchant_name": "merchant_name"
})
)
),
("Update webhook url" = (
value = json!({
"merchant_id": "merchant_abc",
"webhook_details": {
"webhook_url": "https://webhook.site/a5c54f75-1f7e-4545-b781-af525b7e37a0"
}
})
)
),
("Update return url" = (
value = json!({
"merchant_id": "merchant_abc",
"return_url": "https://example.com"
})
)))),
params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Updated", body = MerchantAccountResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Update a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn update_merchant_account() {}
#[cfg(feature = "v2")]
/// Merchant Account - Update
///
/// Updates details of an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc
#[utoipa::path(
put,
path = "/v2/merchant-accounts/{id}",
request_body (
content = MerchantAccountUpdate,
examples(
(
"Update merchant name" = (
value = json!({
"merchant_id": "merchant_abc",
"merchant_name": "merchant_name"
})
)
),
("Update Merchant Details" = (
value = json!({
"merchant_details": {
"primary_contact_person": "John Doe",
"primary_email": "example@company.com"
}
})
)
),
)),
params (("id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Updated", body = MerchantAccountResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Update a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_update() {}
#[cfg(feature = "v1")]
/// Merchant Account - Delete
///
/// Delete a *merchant* account
#[utoipa::path(
delete,
path = "/accounts/{account_id}",
params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Deleted", body = MerchantAccountDeleteResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Delete a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn delete_merchant_account() {}
#[cfg(feature = "v1")]
/// Merchant Account - KV Status
///
/// Toggle KV mode for the Merchant Account
#[utoipa::path(
post,
path = "/accounts/{account_id}/kv",
request_body (
content = ToggleKVRequest,
examples (
("Enable KV for Merchant" = (
value = json!({
"kv_enabled": "true"
})
)),
("Disable KV for Merchant" = (
value = json!({
"kv_enabled": "false"
})
)))
),
params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "KV mode is enabled/disabled for Merchant Account", body = ToggleKVResponse),
(status = 400, description = "Invalid data"),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Enable/Disable KV for a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_kv_status() {}
/// Merchant Connector - List
///
/// List Merchant Connector Details for the merchant
#[utoipa::path(
get,
path = "/accounts/{account_id}/profile/connectors",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
),
responses(
(status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnectorResponse>),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "List all Merchant Connectors for The given Profile",
security(("admin_api_key" = []))
)]
pub async fn payment_connector_list_profile() {}
#[cfg(feature = "v2")]
/// Merchant Account - Profile List
///
/// List profiles for an Merchant
#[utoipa::path(
get,
path = "/v2/merchant-accounts/{id}/profiles",
params (("id" = String, Path, description = "The unique identifier for the Merchant")),
responses(
(status = 200, description = "profile list retrieved successfully", body = Vec<ProfileResponse>),
(status = 400, description = "Invalid data")
),
tag = "Merchant Account",
operation_id = "List Profiles",
security(("admin_api_key" = []))
)]
pub async fn profiles_list() {}
| 2,347 | 2,266 |
hyperswitch | crates/openapi/src/routes/organization.rs | .rs | #[cfg(feature = "v1")]
/// Organization - Create
///
/// Create a new organization
#[utoipa::path(
post,
path = "/organization",
request_body(
content = OrganizationCreateRequest,
examples(
(
"Create an organization with organization_name" = (
value = json!({"organization_name": "organization_abc"})
)
),
)
),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Create an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_create() {}
#[cfg(feature = "v1")]
/// Organization - Retrieve
///
/// Retrieve an existing organization
#[utoipa::path(
get,
path = "/organization/{id}",
params (("id" = String, Path, description = "The unique identifier for the Organization")),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Retrieve an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_retrieve() {}
#[cfg(feature = "v1")]
/// Organization - Update
///
/// Create a new organization for .
#[utoipa::path(
put,
path = "/organization/{id}",
request_body(
content = OrganizationUpdateRequest,
examples(
(
"Update organization_name of the organization" = (
value = json!({"organization_name": "organization_abcd"})
)
),
)
),
params (("id" = String, Path, description = "The unique identifier for the Organization")),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Update an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_update() {}
#[cfg(feature = "v2")]
/// Organization - Create
///
/// Create a new organization
#[utoipa::path(
post,
path = "/v2/organization",
request_body(
content = OrganizationCreateRequest,
examples(
(
"Create an organization with organization_name" = (
value = json!({"organization_name": "organization_abc"})
)
),
)
),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Create an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_create() {}
#[cfg(feature = "v2")]
/// Organization - Retrieve
///
/// Retrieve an existing organization
#[utoipa::path(
get,
path = "/v2/organization/{id}",
params (("id" = String, Path, description = "The unique identifier for the Organization")),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Retrieve an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_retrieve() {}
#[cfg(feature = "v2")]
/// Organization - Update
///
/// Create a new organization for .
#[utoipa::path(
put,
path = "/v2/organization/{id}",
request_body(
content = OrganizationUpdateRequest,
examples(
(
"Update organization_name of the organization" = (
value = json!({"organization_name": "organization_abcd"})
)
),
)
),
params (("id" = String, Path, description = "The unique identifier for the Organization")),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Update an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_update() {}
#[cfg(feature = "v2")]
/// Organization - Merchant Account - List
///
/// List merchant accounts for an Organization
#[utoipa::path(
get,
path = "/v2/organization/{id}/merchant-accounts",
params (("id" = String, Path, description = "The unique identifier for the Organization")),
responses(
(status = 200, description = "Merchant Account list retrieved successfully", body = Vec<MerchantAccountResponse>),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "List Merchant Accounts",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_list() {}
| 1,095 | 2,267 |
hyperswitch | crates/openapi/src/routes/disputes.rs | .rs | /// Disputes - Retrieve Dispute
/// Retrieves a dispute
#[utoipa::path(
get,
path = "/disputes/{dispute_id}",
params(
("dispute_id" = String, Path, description = "The identifier for dispute")
),
responses(
(status = 200, description = "The dispute was retrieved successfully", body = DisputeResponse),
(status = 404, description = "Dispute does not exist in our records")
),
tag = "Disputes",
operation_id = "Retrieve a Dispute",
security(("api_key" = []))
)]
pub async fn retrieve_dispute() {}
/// Disputes - List Disputes
/// Lists all the Disputes for a merchant
#[utoipa::path(
get,
path = "/disputes/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of Dispute Objects to include in the response"),
("dispute_status" = Option<DisputeStatus>, Query, description = "The status of dispute"),
("dispute_stage" = Option<DisputeStage>, Query, description = "The stage of dispute"),
("reason" = Option<String>, Query, description = "The reason for dispute"),
("connector" = Option<String>, Query, description = "The connector linked to dispute"),
("received_time" = Option<PrimitiveDateTime>, Query, description = "The time at which dispute is received"),
("received_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the dispute received time"),
("received_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the dispute received time"),
("received_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the dispute received time"),
("received_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the dispute received time"),
),
responses(
(status = 200, description = "The dispute list was retrieved successfully", body = Vec<DisputeResponse>),
(status = 401, description = "Unauthorized request")
),
tag = "Disputes",
operation_id = "List Disputes",
security(("api_key" = []))
)]
pub async fn retrieve_disputes_list() {}
/// Disputes - List Disputes for The Given Profiles
/// Lists all the Disputes for a merchant
#[utoipa::path(
get,
path = "/disputes/profile/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of Dispute Objects to include in the response"),
("dispute_status" = Option<DisputeStatus>, Query, description = "The status of dispute"),
("dispute_stage" = Option<DisputeStage>, Query, description = "The stage of dispute"),
("reason" = Option<String>, Query, description = "The reason for dispute"),
("connector" = Option<String>, Query, description = "The connector linked to dispute"),
("received_time" = Option<PrimitiveDateTime>, Query, description = "The time at which dispute is received"),
("received_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the dispute received time"),
("received_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the dispute received time"),
("received_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the dispute received time"),
("received_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the dispute received time"),
),
responses(
(status = 200, description = "The dispute list was retrieved successfully", body = Vec<DisputeResponse>),
(status = 401, description = "Unauthorized request")
),
tag = "Disputes",
operation_id = "List Disputes for The given Profiles",
security(("api_key" = []))
)]
pub async fn retrieve_disputes_list_profile() {}
| 901 | 2,268 |
hyperswitch | crates/openapi/src/routes/api_keys.rs | .rs | #[cfg(feature = "v1")]
/// API Key - Create
///
/// Create a new API Key for accessing our APIs from your servers. The plaintext API Key will be
/// displayed only once on creation, so ensure you store it securely.
#[utoipa::path(
post,
path = "/api_keys/{merchant_id}",
params(("merchant_id" = String, Path, description = "The unique identifier for the merchant account")),
request_body= CreateApiKeyRequest,
responses(
(status = 200, description = "API Key created", body = CreateApiKeyResponse),
(status = 400, description = "Invalid data")
),
tag = "API Key",
operation_id = "Create an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_create() {}
#[cfg(feature = "v2")]
/// API Key - Create
///
/// Create a new API Key for accessing our APIs from your servers. The plaintext API Key will be
/// displayed only once on creation, so ensure you store it securely.
#[utoipa::path(
post,
path = "/v2/api-keys",
request_body= CreateApiKeyRequest,
responses(
(status = 200, description = "API Key created", body = CreateApiKeyResponse),
(status = 400, description = "Invalid data")
),
tag = "API Key",
operation_id = "Create an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_create() {}
#[cfg(feature = "v1")]
/// API Key - Retrieve
///
/// Retrieve information about the specified API Key.
#[utoipa::path(
get,
path = "/api_keys/{merchant_id}/{key_id}",
params (
("merchant_id" = String, Path, description = "The unique identifier for the merchant account"),
("key_id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key retrieved", body = RetrieveApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Retrieve an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_retrieve() {}
#[cfg(feature = "v2")]
/// API Key - Retrieve
///
/// Retrieve information about the specified API Key.
#[utoipa::path(
get,
path = "/v2/api-keys/{id}",
params (
("id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key retrieved", body = RetrieveApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Retrieve an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_retrieve() {}
#[cfg(feature = "v1")]
/// API Key - Update
///
/// Update information for the specified API Key.
#[utoipa::path(
post,
path = "/api_keys/{merchant_id}/{key_id}",
request_body = UpdateApiKeyRequest,
params (
("merchant_id" = String, Path, description = "The unique identifier for the merchant account"),
("key_id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key updated", body = RetrieveApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Update an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_update() {}
#[cfg(feature = "v2")]
/// API Key - Update
///
/// Update information for the specified API Key.
#[utoipa::path(
put,
path = "/v2/api-keys/{id}",
request_body = UpdateApiKeyRequest,
params (
("id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key updated", body = RetrieveApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Update an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_update() {}
#[cfg(feature = "v1")]
/// API Key - Revoke
///
/// Revoke the specified API Key. Once revoked, the API Key can no longer be used for
/// authenticating with our APIs.
#[utoipa::path(
delete,
path = "/api_keys/{merchant_id}/{key_id}",
params (
("merchant_id" = String, Path, description = "The unique identifier for the merchant account"),
("key_id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key revoked", body = RevokeApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Revoke an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_revoke() {}
#[cfg(feature = "v2")]
/// API Key - Revoke
///
/// Revoke the specified API Key. Once revoked, the API Key can no longer be used for
/// authenticating with our APIs.
#[utoipa::path(
delete,
path = "/v2/api-keys/{id}",
params (
("id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key revoked", body = RevokeApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Revoke an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_revoke() {}
#[cfg(feature = "v1")]
/// API Key - List
///
/// List all the API Keys associated to a merchant account.
#[utoipa::path(
get,
path = "/api_keys/{merchant_id}/list",
params(
("merchant_id" = String, Path, description = "The unique identifier for the merchant account"),
("limit" = Option<i64>, Query, description = "The maximum number of API Keys to include in the response"),
("skip" = Option<i64>, Query, description = "The number of API Keys to skip when retrieving the list of API keys."),
),
responses(
(status = 200, description = "List of API Keys retrieved successfully", body = Vec<RetrieveApiKeyResponse>),
),
tag = "API Key",
operation_id = "List all API Keys associated with a merchant account",
security(("admin_api_key" = []))
)]
pub async fn api_key_list() {}
#[cfg(feature = "v2")]
/// API Key - List
///
/// List all the API Keys associated to a merchant account.
#[utoipa::path(
get,
path = "/v2/api-keys/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of API Keys to include in the response"),
("skip" = Option<i64>, Query, description = "The number of API Keys to skip when retrieving the list of API keys."),
),
responses(
(status = 200, description = "List of API Keys retrieved successfully", body = Vec<RetrieveApiKeyResponse>),
),
tag = "API Key",
operation_id = "List all API Keys associated with a merchant account",
security(("admin_api_key" = []))
)]
pub async fn api_key_list() {}
| 1,748 | 2,269 |
hyperswitch | crates/openapi/src/routes/relay.rs | .rs | /// Relay - Create
///
/// Creates a relay request.
#[utoipa::path(
post,
path = "/relay",
request_body(
content = RelayRequest,
examples((
"Create a relay request" = (
value = json!({
"connector_resource_id": "7256228702616471803954",
"connector_id": "mca_5apGeP94tMts6rg3U3kR",
"type": "refund",
"data": {
"refund": {
"amount": 6540,
"currency": "USD"
}
}
})
)
))
),
responses(
(status = 200, description = "Relay request", body = RelayResponse),
(status = 400, description = "Invalid data")
),
params(
("X-Profile-Id" = String, Header, description = "Profile ID for authentication"),
("X-Idempotency-Key" = String, Header, description = "Idempotency Key for relay request")
),
tag = "Relay",
operation_id = "Relay Request",
security(("api_key" = []))
)]
pub async fn relay() {}
/// Relay - Retrieve
///
/// Retrieves a relay details.
#[utoipa::path(
get,
path = "/relay/{relay_id}",
params (("id" = String, Path, description = "The unique identifier for the Relay")),
responses(
(status = 200, description = "Relay Retrieved", body = RelayResponse),
(status = 404, description = "Relay details was not found")
),
params(
("X-Profile-Id" = String, Header, description = "Profile ID for authentication")
),
tag = "Relay",
operation_id = "Retrieve a Relay details",
security(("api_key" = []), ("ephemeral_key" = []))
)]
pub async fn relay_retrieve() {}
| 448 | 2,270 |
hyperswitch | crates/openapi/src/routes/payments.rs | .rs | /// Payments - Create
///
/// **Creates a payment object when amount and currency are passed.**
///
/// This API is also used to create a mandate by passing the `mandate_object`.
///
/// Depending on the user journey you wish to achieve, you may opt to complete all the steps in a single request **by attaching a payment method, setting `confirm=true` and `capture_method = automatic`** in the *Payments/Create API* request.
///
/// Otherwise, To completely process a payment you will have to **create a payment, attach a payment method, confirm and capture funds**. For that you could use the following sequence of API requests -
///
/// 1. Payments - Create
///
/// 2. Payments - Update
///
/// 3. Payments - Confirm
///
/// 4. Payments - Capture.
///
/// You will require the 'API - Key' from the Hyperswitch dashboard to make the first call, and use the 'client secret' returned in this API along with your 'publishable key' to make subsequent API calls from your client.
///
/// This page lists the various combinations in which the Payments - Create API can be used and the details about the various fields in the requests and responses.
#[utoipa::path(
post,
path = "/payments",
request_body(
content = PaymentsCreateRequest,
examples(
(
"Create a payment with minimal fields" = (
value = json!({"amount": 6540,"currency": "USD"})
)
),
(
"Create a payment with customer details and metadata" = (
value = json!({
"amount": 6540,
"currency": "USD",
"payment_id": "abcdefghijklmnopqrstuvwxyz",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"phone": "9123456789",
"email": "john@example.com"
},
"description": "Its my first payment request",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "some-value",
"udf2": "some-value"
}
})
)
),
(
"Create a 3DS payment" = (
value = json!({
"amount": 6540,
"currency": "USD",
"authentication_type": "three_ds"
})
)
),
(
"Create a manual capture payment" = (
value = json!({
"amount": 6540,
"currency": "USD",
"capture_method": "manual"
})
)
),
(
"Create a setup mandate payment" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer123",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"setup_future_usage": "off_session",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"single_use": {
"amount": 6540,
"currency": "USD"
}
}
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
}
})
)
),
(
"Create a recurring payment with mandate_id" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer",
"authentication_type": "no_three_ds",
"mandate_id": "{{mandate_id}}",
"off_session": true
})
)
),
(
"Create a payment and save the card" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer123",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"setup_future_usage": "off_session"
})
)
),
(
"Create a payment using an already saved card's token" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"client_secret": "{{client_secret}}",
"payment_method": "card",
"payment_token": "{{payment_token}}",
"card_cvc": "123"
})
)
),
(
"Create a manual capture payment" = (
value = json!({
"amount": 6540,
"currency": "USD",
"customer": {
"id": "cus_abcdefgh"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+91"
}
}
})
)
)
),
),
responses(
(status = 200, description = "Payment created", body = PaymentsCreateResponseOpenApi),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payments",
operation_id = "Create a Payment",
security(("api_key" = [])),
)]
pub fn payments_create() {}
/// Payments - Retrieve
///
/// Retrieves a Payment. This API can also be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/payments/{payment_id}",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body=PaymentRetrieveBody,
responses(
(status = 200, description = "Gets the payment with final status", body = PaymentsResponse),
(status = 404, description = "No payment found")
),
tag = "Payments",
operation_id = "Retrieve a Payment",
security(("api_key" = []), ("publishable_key" = []))
)]
pub fn payments_retrieve() {}
/// Payments - Update
///
/// To update the properties of a *PaymentIntent* object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created
#[utoipa::path(
post,
path = "/payments/{payment_id}",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body(
content = PaymentsUpdateRequest,
examples(
(
"Update the payment amount" = (
value = json!({
"amount": 7654,
}
)
)
),
(
"Update the shipping address" = (
value = json!(
{
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+91"
}
},
}
)
)
)
)
),
responses(
(status = 200, description = "Payment updated", body = PaymentsCreateResponseOpenApi),
(status = 400, description = "Missing mandatory fields")
),
tag = "Payments",
operation_id = "Update a Payment",
security(("api_key" = []), ("publishable_key" = []))
)]
pub fn payments_update() {}
/// Payments - Confirm
///
/// **Use this API to confirm the payment and forward the payment to the payment processor.**
///
/// Alternatively you can confirm the payment within the *Payments/Create* API by setting `confirm=true`. After confirmation, the payment could either:
///
/// 1. fail with `failed` status or
///
/// 2. transition to a `requires_customer_action` status with a `next_action` block or
///
/// 3. succeed with either `succeeded` in case of automatic capture or `requires_capture` in case of manual capture
#[utoipa::path(
post,
path = "/payments/{payment_id}/confirm",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body(
content = PaymentsConfirmRequest,
examples(
(
"Confirm a payment with payment method data" = (
value = json!({
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
}
}
)
)
)
)
),
responses(
(status = 200, description = "Payment confirmed", body = PaymentsCreateResponseOpenApi),
(status = 400, description = "Missing mandatory fields")
),
tag = "Payments",
operation_id = "Confirm a Payment",
security(("api_key" = []), ("publishable_key" = []))
)]
pub fn payments_confirm() {}
/// Payments - Capture
///
/// To capture the funds for an uncaptured payment
#[utoipa::path(
post,
path = "/payments/{payment_id}/capture",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body (
content = PaymentsCaptureRequest,
examples(
(
"Capture the full amount" = (
value = json!({})
)
),
(
"Capture partial amount" = (
value = json!({"amount_to_capture": 654})
)
),
)
),
responses(
(status = 200, description = "Payment captured", body = PaymentsResponse),
(status = 400, description = "Missing mandatory fields")
),
tag = "Payments",
operation_id = "Capture a Payment",
security(("api_key" = []))
)]
pub fn payments_capture() {}
#[cfg(feature = "v1")]
/// Payments - Session token
///
/// Creates a session object or a session token for wallets like Apple Pay, Google Pay, etc. These tokens are used by Hyperswitch's SDK to initiate these wallets' SDK.
#[utoipa::path(
post,
path = "/payments/session_tokens",
request_body=PaymentsSessionRequest,
responses(
(status = 200, description = "Payment session object created or session token was retrieved from wallets", body = PaymentsSessionResponse),
(status = 400, description = "Missing mandatory fields")
),
tag = "Payments",
operation_id = "Create Session tokens for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_connector_session() {}
#[cfg(feature = "v2")]
/// Payments - Session token
///
/// Creates a session object or a session token for wallets like Apple Pay, Google Pay, etc. These tokens are used by Hyperswitch's SDK to initiate these wallets' SDK.
#[utoipa::path(
post,
path = "/v2/payments/{payment_id}/create-external-sdk-tokens",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body=PaymentsSessionRequest,
responses(
(status = 200, description = "Payment session object created or session token was retrieved from wallets", body = PaymentsSessionResponse),
(status = 400, description = "Missing mandatory fields")
),
tag = "Payments",
operation_id = "Create Session tokens for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_connector_session() {}
/// Payments - Cancel
///
/// A Payment could can be cancelled when it is in one of these statuses: `requires_payment_method`, `requires_capture`, `requires_confirmation`, `requires_customer_action`.
#[utoipa::path(
post,
path = "/payments/{payment_id}/cancel",
request_body (
content = PaymentsCancelRequest,
examples(
(
"Cancel the payment with minimal fields" = (
value = json!({})
)
),
(
"Cancel the payment with cancellation reason" = (
value = json!({"cancellation_reason": "requested_by_customer"})
)
),
)
),
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Payment canceled"),
(status = 400, description = "Missing mandatory fields")
),
tag = "Payments",
operation_id = "Cancel a Payment",
security(("api_key" = []))
)]
pub fn payments_cancel() {}
/// Payments - List
///
/// To list the *payments*
#[cfg(feature = "v1")]
#[utoipa::path(
get,
path = "/payments/list",
params(
("customer_id" = String, Query, description = "The identifier for the customer"),
("starting_after" = String, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
("ending_before" = String, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
("limit" = i64, Query, description = "Limit on the number of objects to return"),
("created" = PrimitiveDateTime, Query, description = "The time at which payment is created"),
("created_lt" = PrimitiveDateTime, Query, description = "Time less than the payment created time"),
("created_gt" = PrimitiveDateTime, Query, description = "Time greater than the payment created time"),
("created_lte" = PrimitiveDateTime, Query, description = "Time less than or equals to the payment created time"),
("created_gte" = PrimitiveDateTime, Query, description = "Time greater than or equals to the payment created time")
),
responses(
(status = 200, description = "Successfully retrieved a payment list", body = Vec<PaymentListResponse>),
(status = 404, description = "No payments found")
),
tag = "Payments",
operation_id = "List all Payments",
security(("api_key" = []))
)]
pub fn payments_list() {}
/// Profile level Payments - List
///
/// To list the payments
#[utoipa::path(
get,
path = "/payments/list",
params(
("customer_id" = String, Query, description = "The identifier for the customer"),
("starting_after" = String, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
("ending_before" = String, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
("limit" = i64, Query, description = "Limit on the number of objects to return"),
("created" = PrimitiveDateTime, Query, description = "The time at which payment is created"),
("created_lt" = PrimitiveDateTime, Query, description = "Time less than the payment created time"),
("created_gt" = PrimitiveDateTime, Query, description = "Time greater than the payment created time"),
("created_lte" = PrimitiveDateTime, Query, description = "Time less than or equals to the payment created time"),
("created_gte" = PrimitiveDateTime, Query, description = "Time greater than or equals to the payment created time")
),
responses(
(status = 200, description = "Received payment list"),
(status = 404, description = "No payments found")
),
tag = "Payments",
operation_id = "List all Payments for the Profile",
security(("api_key" = []))
)]
pub async fn profile_payments_list() {}
/// Payments - Incremental Authorization
///
/// Authorized amount for a payment can be incremented if it is in status: requires_capture
#[utoipa::path(
post,
path = "/payments/{payment_id}/incremental_authorization",
request_body=PaymentsIncrementalAuthorizationRequest,
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Payment authorized amount incremented", body = PaymentsResponse),
(status = 400, description = "Missing mandatory fields")
),
tag = "Payments",
operation_id = "Increment authorized amount for a Payment",
security(("api_key" = []))
)]
pub fn payments_incremental_authorization() {}
/// Payments - External 3DS Authentication
///
/// External 3DS Authentication is performed and returns the AuthenticationResponse
#[utoipa::path(
post,
path = "/payments/{payment_id}/3ds/authentication",
request_body=PaymentsExternalAuthenticationRequest,
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Authentication created", body = PaymentsExternalAuthenticationResponse),
(status = 400, description = "Missing mandatory fields")
),
tag = "Payments",
operation_id = "Initiate external authentication for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_external_authentication() {}
/// Payments - Complete Authorize
#[utoipa::path(
post,
path = "/{payment_id}/complete_authorize",
request_body=PaymentsCompleteAuthorizeRequest,
params(
("payment_id" =String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Payments Complete Authorize Success", body = PaymentsResponse),
(status = 400, description = "Missing mandatory fields")
),
tag = "Payments",
operation_id = "Complete Authorize a Payment",
security(("publishable_key" = []))
)]
pub fn payments_complete_authorize() {}
/// Dynamic Tax Calculation
#[utoipa::path(
post,
path = "/payments/{payment_id}/calculate_tax",
request_body=PaymentsDynamicTaxCalculationRequest,
responses(
(status = 200, description = "Tax Calculation is done", body = PaymentsDynamicTaxCalculationResponse),
(status = 400, description = "Missing mandatory fields")
),
tag = "Payments",
operation_id = "Create Tax Calculation for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_dynamic_tax_calculation() {}
/// Payments - Post Session Tokens
#[utoipa::path(
post,
path = "/payments/{payment_id}/post_session_tokens",
request_body=PaymentsPostSessionTokensRequest,
responses(
(status = 200, description = "Post Session Token is done", body = PaymentsPostSessionTokensResponse),
(status = 400, description = "Missing mandatory fields")
),
tag = "Payments",
operation_id = "Create Post Session Tokens for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_post_session_tokens() {}
/// Payments - Create Intent
///
/// **Creates a payment intent object when amount_details are passed.**
///
/// You will require the 'API - Key' from the Hyperswitch dashboard to make the first call, and use the 'client secret' returned in this API along with your 'publishable key' to make subsequent API calls from your client.
#[utoipa::path(
post,
path = "/v2/payments/create-intent",
request_body(
content = PaymentsCreateIntentRequest,
examples(
(
"Create a payment intent with minimal fields" = (
value = json!({"amount_details": {"order_amount": 6540, "currency": "USD"}})
)
),
),
),
responses(
(status = 200, description = "Payment created", body = PaymentsIntentResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payments",
operation_id = "Create a Payment Intent",
security(("api_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payments_create_intent() {}
/// Payments - Get Intent
///
/// **Get a payment intent object when id is passed in path**
///
/// You will require the 'API - Key' from the Hyperswitch dashboard to make the call.
#[utoipa::path(
get,
path = "/v2/payments/{id}/get-intent",
params (("id" = String, Path, description = "The unique identifier for the Payment Intent")),
responses(
(status = 200, description = "Payment Intent", body = PaymentsIntentResponse),
(status = 404, description = "Payment Intent not found")
),
tag = "Payments",
operation_id = "Get the Payment Intent details",
security(("api_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payments_get_intent() {}
/// Payments - Update Intent
///
/// **Update a payment intent object**
///
/// You will require the 'API - Key' from the Hyperswitch dashboard to make the call.
#[utoipa::path(
put,
path = "/v2/payments/{id}/update-intent",
params (("id" = String, Path, description = "The unique identifier for the Payment Intent"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
),
),
request_body(
content = PaymentsUpdateIntentRequest,
examples(
(
"Update a payment intent with minimal fields" = (
value = json!({"amount_details": {"order_amount": 6540, "currency": "USD"}})
)
),
),
),
responses(
(status = 200, description = "Payment Intent Updated", body = PaymentsIntentResponse),
(status = 404, description = "Payment Intent Not Found")
),
tag = "Payments",
operation_id = "Update a Payment Intent",
security(("api_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payments_update_intent() {}
/// Payments - Confirm Intent
///
/// **Confirms a payment intent object with the payment method data**
///
/// .
#[utoipa::path(
post,
path = "/v2/payments/{id}/confirm-intent",
params (("id" = String, Path, description = "The unique identifier for the Payment Intent"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
),
(
"X-Client-Secret" = String, Header,
description = "Client Secret Associated with the payment intent",
example = json!({"X-Client-Secret": "12345_pay_0193e41106e07e518940f8b51b9c8121_secret_0193e41107027a928d61d292e6a5dba9"})
),
),
request_body(
content = PaymentsConfirmIntentRequest,
examples(
(
"Confirm the payment intent with card details" = (
value = json!({
"payment_method_type": "card",
"payment_method_subtype": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
})
)
),
),
),
responses(
(status = 200, description = "Payment created", body = PaymentsResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payments",
operation_id = "Confirm Payment Intent",
security(("publishable_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payments_confirm_intent() {}
/// Payments - Get
///
/// Retrieves a Payment. This API can also be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/v2/payments/{id}",
params(
("id" = String, Path, description = "The global payment id"),
("force_sync" = ForceSync, Query, description = "A boolean to indicate whether to force sync the payment status. Value can be true or false")
),
responses(
(status = 200, description = "Gets the payment with final status", body = PaymentsResponse),
(status = 404, description = "No payment found with the given id")
),
tag = "Payments",
operation_id = "Retrieve a Payment",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub fn payment_status() {}
/// Payments - Create and Confirm Intent
///
/// **Creates and confirms a payment intent object when the amount and payment method information are passed.**
///
/// You will require the 'API - Key' from the Hyperswitch dashboard to make the call.
#[utoipa::path(
post,
path = "/v2/payments",
params (
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
)
),
request_body(
content = PaymentsRequest,
examples(
(
"Create and confirm the payment intent with amount and card details" = (
value = json!({
"amount_details": {
"order_amount": 6540,
"currency": "USD"
},
"payment_method_type": "card",
"payment_method_subtype": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
})
)
),
),
),
responses(
(status = 200, description = "Payment created", body = PaymentsResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payments",
operation_id = "Create and Confirm Payment Intent",
security(("api_key" = [])),
)]
pub fn payments_create_and_confirm_intent() {}
#[derive(utoipa::ToSchema)]
#[schema(rename_all = "lowercase")]
pub(crate) enum ForceSync {
/// Force sync with the connector / processor to update the status
True,
/// Do not force sync with the connector / processor. Get the status which is available in the database
False,
}
/// Payments - Payment Methods List
///
/// List the payment methods eligible for a payment. This endpoint also returns the saved payment methods for the customer when the customer_id is passed when creating the payment
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payments/{id}/payment-methods",
params(
("id" = String, Path, description = "The global payment id"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
),
(
"X-Client-Secret" = String, Header,
description = "Client Secret Associated with the payment intent",
example = json!({"X-Client-Secret": "12345_pay_0193e41106e07e518940f8b51b9c8121_secret_0193e41107027a928d61d292e6a5dba9"})
),
),
responses(
(status = 200, description = "Get the payment methods", body = PaymentMethodListResponseForPayments),
(status = 404, description = "No payment found with the given id")
),
tag = "Payments",
operation_id = "Retrieve Payment methods for a Payment",
security(("publishable_key" = []))
)]
pub fn list_payment_methods() {}
/// Payments - List
///
/// To list the *payments*
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payments/list",
params(api_models::payments::PaymentListConstraints),
responses(
(status = 200, description = "Successfully retrieved a payment list", body = PaymentListResponse),
(status = 404, description = "No payments found")
),
tag = "Payments",
operation_id = "List all Payments",
security(("api_key" = []), ("jwt_key" = []))
)]
pub fn payments_list() {}
| 7,042 | 2,271 |
hyperswitch | crates/openapi/src/routes/mandates.rs | .rs | /// Mandates - Retrieve Mandate
///
/// Retrieves a mandate created using the Payments/Create API
#[utoipa::path(
get,
path = "/mandates/{mandate_id}",
params(
("mandate_id" = String, Path, description = "The identifier for mandate")
),
responses(
(status = 200, description = "The mandate was retrieved successfully", body = MandateResponse),
(status = 404, description = "Mandate does not exist in our records")
),
tag = "Mandates",
operation_id = "Retrieve a Mandate",
security(("api_key" = []))
)]
pub async fn get_mandate() {}
/// Mandates - Revoke Mandate
///
/// Revokes a mandate created using the Payments/Create API
#[utoipa::path(
post,
path = "/mandates/revoke/{mandate_id}",
params(
("mandate_id" = String, Path, description = "The identifier for a mandate")
),
responses(
(status = 200, description = "The mandate was revoked successfully", body = MandateRevokedResponse),
(status = 400, description = "Mandate does not exist in our records")
),
tag = "Mandates",
operation_id = "Revoke a Mandate",
security(("api_key" = []))
)]
pub async fn revoke_mandate() {}
/// Mandates - List Mandates
#[utoipa::path(
get,
path = "/mandates/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of Mandate Objects to include in the response"),
("mandate_status" = Option<MandateStatus>, Query, description = "The status of mandate"),
("connector" = Option<String>, Query, description = "The connector linked to mandate"),
("created_time" = Option<PrimitiveDateTime>, Query, description = "The time at which mandate is created"),
("created_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the mandate created time"),
("created_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the mandate created time"),
("created_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the mandate created time"),
("created_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the mandate created time"),
),
responses(
(status = 200, description = "The mandate list was retrieved successfully", body = Vec<MandateResponse>),
(status = 401, description = "Unauthorized request")
),
tag = "Mandates",
operation_id = "List Mandates",
security(("api_key" = []))
)]
pub async fn retrieve_mandates_list() {}
/// Mandates - Customer Mandates List
///
/// Lists all the mandates for a particular customer id.
#[utoipa::path(
post,
path = "/customers/{customer_id}/mandates",
responses(
(status = 200, description = "List of retrieved mandates for a customer", body = Vec<MandateResponse>),
(status = 400, description = "Invalid Data"),
),
tag = "Mandates",
operation_id = "List Mandates for a Customer",
security(("api_key" = []))
)]
pub async fn customers_mandates_list() {}
| 760 | 2,272 |
hyperswitch | crates/openapi/src/routes/routing.rs | .rs | #[cfg(feature = "v1")]
/// Routing - Create
///
/// Create a routing config
#[utoipa::path(
post,
path = "/routing",
request_body = RoutingConfigRequest,
responses(
(status = 200, description = "Routing config created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Create a routing config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_create_config() {}
#[cfg(feature = "v2")]
/// Routing - Create
///
/// Create a routing algorithm
#[utoipa::path(
post,
path = "/v2/routing-algorithm",
request_body = RoutingConfigRequest,
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Create a routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_create_config() {}
#[cfg(feature = "v1")]
/// Routing - Activate config
///
/// Activate a routing config
#[utoipa::path(
post,
path = "/routing/{routing_algorithm_id}/activate",
params(
("routing_algorithm_id" = String, Path, description = "The unique identifier for a config"),
),
responses(
(status = 200, description = "Routing config activated", body = RoutingDictionaryRecord),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 400, description = "Bad request")
),
tag = "Routing",
operation_id = "Activate a routing config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_link_config() {}
#[cfg(feature = "v1")]
/// Routing - Retrieve
///
/// Retrieve a routing algorithm
#[utoipa::path(
get,
path = "/routing/{routing_algorithm_id}",
params(
("routing_algorithm_id" = String, Path, description = "The unique identifier for a config"),
),
responses(
(status = 200, description = "Successfully fetched routing config", body = MerchantRoutingAlgorithm),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 403, description = "Forbidden")
),
tag = "Routing",
operation_id = "Retrieve a routing config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_config() {}
#[cfg(feature = "v2")]
/// Routing - Retrieve
///
/// Retrieve a routing algorithm with its algorithm id
#[utoipa::path(
get,
path = "/v2/routing-algorithm/{id}",
params(
("id" = String, Path, description = "The unique identifier for a routing algorithm"),
),
responses(
(status = 200, description = "Successfully fetched routing algorithm", body = MerchantRoutingAlgorithm),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 403, description = "Forbidden")
),
tag = "Routing",
operation_id = "Retrieve a routing algorithm with its algorithm id",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_config() {}
#[cfg(feature = "v1")]
/// Routing - List
///
/// List all routing configs
#[utoipa::path(
get,
path = "/routing",
params(
("limit" = Option<u16>, Query, description = "The number of records to be returned"),
("offset" = Option<u8>, Query, description = "The record offset from which to start gathering of results"),
("profile_id" = Option<String>, Query, description = "The unique identifier for a merchant profile"),
),
responses(
(status = 200, description = "Successfully fetched routing configs", body = RoutingKind),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing")
),
tag = "Routing",
operation_id = "List routing configs",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn list_routing_configs() {}
#[cfg(feature = "v1")]
/// Routing - Deactivate
///
/// Deactivates a routing config
#[utoipa::path(
post,
path = "/routing/deactivate",
request_body = RoutingConfigRequest,
responses(
(status = 200, description = "Successfully deactivated routing config", body = RoutingDictionaryRecord),
(status = 500, description = "Internal server error"),
(status = 400, description = "Malformed request"),
(status = 403, description = "Malformed request"),
(status = 422, description = "Unprocessable request")
),
tag = "Routing",
operation_id = "Deactivate a routing config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_unlink_config() {}
#[cfg(feature = "v1")]
/// Routing - Update Default Config
///
/// Update default fallback config
#[utoipa::path(
post,
path = "/routing/default",
request_body = Vec<RoutableConnectorChoice>,
responses(
(status = 200, description = "Successfully updated default config", body = Vec<RoutableConnectorChoice>),
(status = 500, description = "Internal server error"),
(status = 400, description = "Malformed request"),
(status = 422, description = "Unprocessable request")
),
tag = "Routing",
operation_id = "Update default fallback config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_update_default_config() {}
#[cfg(feature = "v1")]
/// Routing - Retrieve Default Config
///
/// Retrieve default fallback config
#[utoipa::path(
get,
path = "/routing/default",
responses(
(status = 200, description = "Successfully retrieved default config", body = Vec<RoutableConnectorChoice>),
(status = 500, description = "Internal server error")
),
tag = "Routing",
operation_id = "Retrieve default fallback config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_default_config() {}
#[cfg(feature = "v1")]
/// Routing - Retrieve Config
///
/// Retrieve active config
#[utoipa::path(
get,
path = "/routing/active",
params(
("profile_id" = Option<String>, Query, description = "The unique identifier for a merchant profile"),
),
responses(
(status = 200, description = "Successfully retrieved active config", body = LinkedRoutingConfigRetrieveResponse),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 403, description = "Forbidden")
),
tag = "Routing",
operation_id = "Retrieve active config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_linked_config() {}
#[cfg(feature = "v1")]
/// Routing - Retrieve Default For Profile
///
/// Retrieve default config for profiles
#[utoipa::path(
get,
path = "/routing/default/profile",
responses(
(status = 200, description = "Successfully retrieved default config", body = ProfileDefaultRoutingConfig),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing")
),
tag = "Routing",
operation_id = "Retrieve default configs for all profiles",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_default_config_for_profiles() {}
#[cfg(feature = "v1")]
/// Routing - Update Default For Profile
///
/// Update default config for profiles
#[utoipa::path(
post,
path = "/routing/default/profile/{profile_id}",
request_body = Vec<RoutableConnectorChoice>,
params(
("profile_id" = String, Path, description = "The unique identifier for a profile"),
),
responses(
(status = 200, description = "Successfully updated default config for profile", body = ProfileDefaultRoutingConfig),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 400, description = "Malformed request"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Update default configs for all profiles",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_update_default_config_for_profile() {}
#[cfg(feature = "v1")]
/// Routing - Toggle success based dynamic routing for profile
///
/// Create a success based dynamic routing algorithm
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/success_based/toggle",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for success based routing"),
),
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Toggle success based dynamic routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn toggle_success_based_routing() {}
#[cfg(feature = "v1")]
/// Routing - Update success based dynamic routing config for profile
///
/// Update success based dynamic routing algorithm
#[utoipa::path(
patch,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/success_based/config/{algorithm_id}",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("algorithm_id" = String, Path, description = "Success based routing algorithm id which was last activated to update the config"),
),
request_body = SuccessBasedRoutingConfig,
responses(
(status = 200, description = "Routing Algorithm updated", body = RoutingDictionaryRecord),
(status = 400, description = "Update body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Update success based dynamic routing configs",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn success_based_routing_update_configs() {}
#[cfg(feature = "v1")]
/// Routing - Toggle elimination routing for profile
///
/// Create a elimination based dynamic routing algorithm
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/elimination/toggle",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for elimination based routing"),
),
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Toggle elimination routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn toggle_elimination_routing() {}
#[cfg(feature = "v1")]
/// Routing - Toggle Contract routing for profile
///
/// Create a Contract based dynamic routing algorithm
#[utoipa::path(
post,
path = "/account/:account_id/business_profile/:profile_id/dynamic_routing/contracts/toggle",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for contract based routing"),
),
request_body = ContractBasedRoutingConfig,
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Toggle contract routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn contract_based_routing_setup_config() {}
#[cfg(feature = "v1")]
/// Routing - Update contract based dynamic routing config for profile
///
/// Update contract based dynamic routing algorithm
#[utoipa::path(
patch,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/contracts/config/{algorithm_id}",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("algorithm_id" = String, Path, description = "Contract based routing algorithm id which was last activated to update the config"),
),
request_body = ContractBasedRoutingConfig,
responses(
(status = 200, description = "Routing Algorithm updated", body = RoutingDictionaryRecord),
(status = 400, description = "Update body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Update contract based dynamic routing configs",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn contract_based_routing_update_configs() {}
| 3,612 | 2,273 |
hyperswitch | crates/openapi/src/routes/revenue_recovery.rs | .rs | #[cfg(feature = "v2")]
/// Revenue Recovery - Retrieve
///
/// Retrieve the Revenue Recovery Payment Info
#[utoipa::path(
get,
path = "/v2/process_tracker/revenue_recovery_workflow/{revenue_recovery_id}",
params(
("recovery_recovery_id" = String, Path, description = "The payment intent id"),
),
responses(
(status = 200, description = "Revenue Recovery Info Retrieved Successfully", body = RevenueRecoveryResponse),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Revenue Recovery",
operation_id = "Retrieve Revenue Recovery Info",
security(("jwt_key" = []))
)]
pub async fn revenue_recovery_pt_retrieve_api() {}
| 204 | 2,274 |
hyperswitch | crates/openapi/src/routes/customers.rs | .rs | /// Customers - Create
///
/// Creates a customer object and stores the customer details to be reused for future payments.
/// Incase the customer already exists in the system, this API will respond with the customer details.
#[utoipa::path(
post,
path = "/customers",
request_body (
content = CustomerRequest,
examples (( "Update name and email of a customer" =(
value =json!( {
"email": "guest@example.com",
"name": "John Doe"
})
)))
),
responses(
(status = 200, description = "Customer Created", body = CustomerResponse),
(status = 400, description = "Invalid data")
),
tag = "Customers",
operation_id = "Create a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn customers_create() {}
/// Customers - Retrieve
///
/// Retrieves a customer's details.
#[utoipa::path(
get,
path = "/customers/{customer_id}",
params (("customer_id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer Retrieved", body = CustomerResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Retrieve a Customer",
security(("api_key" = []), ("ephemeral_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn customers_retrieve() {}
/// Customers - Update
///
/// Updates the customer's details in a customer object.
#[utoipa::path(
post,
path = "/customers/{customer_id}",
request_body (
content = CustomerUpdateRequest,
examples (( "Update name and email of a customer" =(
value =json!( {
"email": "guest@example.com",
"name": "John Doe"
})
)))
),
params (("customer_id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer was Updated", body = CustomerResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Update a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn customers_update() {}
/// Customers - Delete
///
/// Delete a customer record.
#[utoipa::path(
delete,
path = "/customers/{customer_id}",
params (("customer_id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer was Deleted", body = CustomerDeleteResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Delete a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn customers_delete() {}
/// Customers - List
///
/// Lists all the customers for a particular merchant id.
#[utoipa::path(
get,
path = "/customers/list",
responses(
(status = 200, description = "Customers retrieved", body = Vec<CustomerResponse>),
(status = 400, description = "Invalid Data"),
),
tag = "Customers",
operation_id = "List all Customers for a Merchant",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn customers_list() {}
/// Customers - Create
///
/// Creates a customer object and stores the customer details to be reused for future payments.
/// Incase the customer already exists in the system, this API will respond with the customer details.
#[utoipa::path(
post,
path = "/v2/customers",
request_body (
content = CustomerRequest,
examples (( "Create a customer with name and email" =(
value =json!( {
"email": "guest@example.com",
"name": "John Doe"
})
)))
),
responses(
(status = 200, description = "Customer Created", body = CustomerResponse),
(status = 400, description = "Invalid data")
),
tag = "Customers",
operation_id = "Create a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn customers_create() {}
/// Customers - Retrieve
///
/// Retrieves a customer's details.
#[utoipa::path(
get,
path = "/v2/customers/{id}",
params (("id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer Retrieved", body = CustomerResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Retrieve a Customer",
security(("api_key" = []), ("ephemeral_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn customers_retrieve() {}
/// Customers - Update
///
/// Updates the customer's details in a customer object.
#[utoipa::path(
post,
path = "/v2/customers/{id}",
request_body (
content = CustomerUpdateRequest,
examples (( "Update name and email of a customer" =(
value =json!( {
"email": "guest@example.com",
"name": "John Doe"
})
)))
),
params (("id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer was Updated", body = CustomerResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Update a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn customers_update() {}
/// Customers - Delete
///
/// Delete a customer record.
#[utoipa::path(
delete,
path = "/v2/customers/{id}",
params (("id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer was Deleted", body = CustomerDeleteResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Delete a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn customers_delete() {}
/// Customers - List
///
/// Lists all the customers for a particular merchant id.
#[utoipa::path(
get,
path = "/v2/customers/list",
responses(
(status = 200, description = "Customers retrieved", body = Vec<CustomerResponse>),
(status = 400, description = "Invalid Data"),
),
tag = "Customers",
operation_id = "List all Customers for a Merchant",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn customers_list() {}
| 1,581 | 2,275 |
hyperswitch | crates/openapi/src/routes/payment_method.rs | .rs | /// PaymentMethods - Create
///
/// Creates and stores a payment method against a customer.
/// In case of cards, this API should be used only by PCI compliant merchants.
#[utoipa::path(
post,
path = "/payment_methods",
request_body (
content = PaymentMethodCreate,
examples (( "Save a card" =(
value =json!( {
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "4242424242424242",
"card_exp_month": "11",
"card_exp_year": "25",
"card_holder_name": "John Doe"
},
"customer_id": "{{customer_id}}"
})
)))
),
responses(
(status = 200, description = "Payment Method Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data")
),
tag = "Payment Methods",
operation_id = "Create a Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn create_payment_method_api() {}
/// List payment methods for a Merchant
///
/// Lists the applicable payment methods for a particular Merchant ID.
/// Use the client secret and publishable key authorization to list all relevant payment methods of the merchant for the payment corresponding to the client secret.
#[utoipa::path(
get,
path = "/account/payment_methods",
params (
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("accepted_country" = Vec<String>, Query, description = "The two-letter ISO currency code"),
("accepted_currency" = Vec<Currency>, Path, description = "The three-letter ISO currency code"),
("minimum_amount" = i64, Query, description = "The minimum amount accepted for processing by the particular payment method."),
("maximum_amount" = i64, Query, description = "The maximum amount accepted for processing by the particular payment method."),
("recurring_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for installment payments"),
),
responses(
(status = 200, description = "Payment Methods retrieved", body = PaymentMethodListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List all Payment Methods for a Merchant",
security(("api_key" = []), ("publishable_key" = []))
)]
pub async fn list_payment_method_api() {}
/// List payment methods for a Customer
///
/// Lists all the applicable payment methods for a particular Customer ID.
#[utoipa::path(
get,
path = "/customers/{customer_id}/payment_methods",
params (
("customer_id" = String, Path, description = "The unique identifier for the customer account"),
("accepted_country" = Vec<String>, Query, description = "The two-letter ISO currency code"),
("accepted_currency" = Vec<Currency>, Path, description = "The three-letter ISO currency code"),
("minimum_amount" = i64, Query, description = "The minimum amount accepted for processing by the particular payment method."),
("maximum_amount" = i64, Query, description = "The maximum amount accepted for processing by the particular payment method."),
("recurring_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for installment payments"),
),
responses(
(status = 200, description = "Payment Methods retrieved", body = CustomerPaymentMethodsListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List all Payment Methods for a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn list_customer_payment_method_api() {}
/// List customer saved payment methods for a Payment
///
/// Lists all the applicable payment methods for a particular payment tied to the `client_secret`.
#[utoipa::path(
get,
path = "/customers/payment_methods",
params (
("client-secret" = String, Path, description = "A secret known only to your client and the authorization server. Used for client side authentication"),
("customer_id" = String, Path, description = "The unique identifier for the customer account"),
("accepted_country" = Vec<String>, Query, description = "The two-letter ISO currency code"),
("accepted_currency" = Vec<Currency>, Path, description = "The three-letter ISO currency code"),
("minimum_amount" = i64, Query, description = "The minimum amount accepted for processing by the particular payment method."),
("maximum_amount" = i64, Query, description = "The maximum amount accepted for processing by the particular payment method."),
("recurring_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for installment payments"),
),
responses(
(status = 200, description = "Payment Methods retrieved for customer tied to its respective client-secret passed in the param", body = CustomerPaymentMethodsListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List all Payment Methods for a Customer",
security(("publishable_key" = []))
)]
pub async fn list_customer_payment_method_api_client() {}
/// Payment Method - Retrieve
///
/// Retrieves a payment method of a customer.
#[utoipa::path(
get,
path = "/payment_methods/{method_id}",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method retrieved", body = PaymentMethodResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Retrieve a Payment method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_retrieve_api() {}
/// Payment Method - Update
///
/// Update an existing payment method of a customer.
/// This API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments.
#[utoipa::path(
post,
path = "/payment_methods/{method_id}/update",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
request_body = PaymentMethodUpdate,
responses(
(status = 200, description = "Payment Method updated", body = PaymentMethodResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Update a Payment method",
security(("api_key" = []), ("publishable_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_update_api() {}
/// Payment Method - Delete
///
/// Deletes a payment method of a customer.
#[utoipa::path(
delete,
path = "/payment_methods/{method_id}",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method deleted", body = PaymentMethodDeleteResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Delete a Payment method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_delete_api() {}
/// Payment Method - Set Default Payment Method for Customer
///
/// Set the Payment Method as Default for the Customer.
#[utoipa::path(
get,
path = "/{customer_id}/payment_methods/{payment_method_id}/default",
params (
("customer_id" = String,Path, description ="The unique identifier for the Customer"),
("payment_method_id" = String,Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method has been set as default", body =CustomerDefaultPaymentMethodResponse ),
(status = 400, description = "Payment Method has already been set as default for that customer"),
(status = 404, description = "Payment Method not found for the customer")
),
tag = "Payment Methods",
operation_id = "Set the Payment Method as Default",
security(("ephemeral_key" = []))
)]
pub async fn default_payment_method_set_api() {}
/// Payment Method - Create Intent
///
/// Creates a payment method for customer with billing information and other metadata.
#[utoipa::path(
post,
path = "/v2/payment-methods/create-intent",
request_body(
content = PaymentMethodIntentCreate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Intent Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Create Payment Method Intent",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn create_payment_method_intent_api() {}
/// Payment Method - Confirm Intent
///
/// Update a payment method with customer's payment method related information.
#[utoipa::path(
post,
path = "/v2/payment-methods/{id}/confirm-intent",
request_body(
content = PaymentMethodIntentConfirm,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Intent Confirmed", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Confirm Payment Method Intent",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn confirm_payment_method_intent_api() {}
/// Payment Method - Create
///
/// Creates and stores a payment method against a customer. In case of cards, this API should be used only by PCI compliant merchants.
#[utoipa::path(
post,
path = "/v2/payment-methods",
request_body(
content = PaymentMethodCreate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Create Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn create_payment_method_api() {}
/// Payment Method - Retrieve
///
/// Retrieves a payment method of a customer.
#[utoipa::path(
get,
path = "/v2/payment-methods/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Retrieved", body = PaymentMethodResponse),
(status = 404, description = "Payment Method Not Found"),
),
tag = "Payment Methods",
operation_id = "Retrieve Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_retrieve_api() {}
/// Payment Method - Update
///
/// Update an existing payment method of a customer.
#[utoipa::path(
patch,
path = "/v2/payment-methods/{id}/update-saved-payment-method",
request_body(
content = PaymentMethodUpdate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Update", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Update Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_update_api() {}
/// Payment Method - Delete
///
/// Deletes a payment method of a customer.
#[utoipa::path(
delete,
path = "/v2/payment-methods/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Retrieved", body = PaymentMethodDeleteResponse),
(status = 404, description = "Payment Method Not Found"),
),
tag = "Payment Methods",
operation_id = "Delete Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_delete_api() {}
/// Payment Method - List Customer Saved Payment Methods
///
/// List the payment methods saved for a customer
#[utoipa::path(
get,
path = "/v2/customers/{id}/saved-payment-methods",
params (
("id" = String, Path, description = "The unique identifier for the customer"),
),
responses(
(status = 200, description = "Payment Methods Retrieved", body = CustomerPaymentMethodsListResponse),
(status = 404, description = "Customer Not Found"),
),
tag = "Payment Methods",
operation_id = "List Customer Saved Payment Methods",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn list_customer_payment_method_api() {}
/// Payment Method Session - Create
///
/// Create a payment method session for a customer
/// This is used to list the saved payment methods for the customer
/// The customer can also add a new payment method using this session
#[cfg(feature = "v2")]
#[utoipa::path(
post,
path = "/v2/payment-method-session",
request_body(
content = PaymentMethodSessionRequest,
examples (( "Create a payment method session with customer_id" = (
value =json!( {
"customer_id": "12345_cus_abcdefghijklmnopqrstuvwxyz"
})
)))
),
responses(
(status = 200, description = "Create the payment method session", body = PaymentMethodSessionResponse),
(status = 400, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Create a payment method session",
security(("api_key" = []))
)]
pub fn payment_method_session_create() {}
/// Payment Method Session - Retrieve
///
/// Retrieve the payment method session
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payment-method-session/:id",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
responses(
(status = 200, description = "The payment method session is retrieved successfully", body = PaymentMethodSessionResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Retrieve the payment method session",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_retrieve() {}
/// Payment Method Session - List Payment Methods
///
/// List payment methods for the given payment method session.
/// This endpoint lists the enabled payment methods for the profile and the saved payment methods of the customer.
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payment-method-session/:id/list-payment-methods",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
responses(
(status = 200, description = "The payment method session is retrieved successfully", body = PaymentMethodListResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "List Payment methods for a Payment Method Session",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_list_payment_methods() {}
/// Payment Method Session - Update a saved payment method
///
/// Update a saved payment method from the given payment method session.
#[cfg(feature = "v2")]
#[utoipa::path(
put,
path = "/v2/payment-method-session/:id/update-saved-payment-method",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
request_body(
content = PaymentMethodSessionUpdateSavedPaymentMethod,
examples(( "Update the card holder name" = (
value =json!( {
"payment_method_id": "12345_pm_0194b1ecabc172e28aeb71f70a4daba3",
"payment_method_data": {
"card": {
"card_holder_name": "Narayan Bhat"
}
}
}
)
)))
),
responses(
(status = 200, description = "The payment method has been updated successfully", body = PaymentMethodResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Update a saved payment method",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_update_saved_payment_method() {}
/// Payment Method Session - Delete a saved payment method
///
/// Delete a saved payment method from the given payment method session.
#[cfg(feature = "v2")]
#[utoipa::path(
delete,
path = "/v2/payment-method-session/:id",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
request_body(
content = PaymentMethodSessionDeleteSavedPaymentMethod,
examples(( "Update the card holder name" = (
value =json!( {
"payment_method_id": "12345_pm_0194b1ecabc172e28aeb71f70a4daba3",
}
)
)))
),
responses(
(status = 200, description = "The payment method has been updated successfully", body = PaymentMethodDeleteResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Delete a saved payment method",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_delete_saved_payment_method() {}
/// Card network tokenization - Create using raw card data
///
/// Create a card network token for a customer and store it as a payment method.
/// This API expects raw card details for creating a network token with the card networks.
#[utoipa::path(
post,
path = "/payment_methods/tokenize-card",
request_body = CardNetworkTokenizeRequest,
responses(
(status = 200, description = "Payment Method Created", body = CardNetworkTokenizeResponse),
(status = 404, description = "Customer not found"),
),
tag = "Payment Methods",
operation_id = "Create card network token",
security(("admin_api_key" = []))
)]
pub async fn tokenize_card_api() {}
/// Card network tokenization - Create using existing payment method
///
/// Create a card network token for a customer for an existing payment method.
/// This API expects an existing payment method ID for a card.
#[utoipa::path(
post,
path = "/payment_methods/{id}/tokenize-card",
request_body = CardNetworkTokenizeRequest,
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Updated", body = CardNetworkTokenizeResponse),
(status = 404, description = "Customer not found"),
),
tag = "Payment Methods",
operation_id = "Create card network token",
security(("admin_api_key" = []))
)]
pub async fn tokenize_card_using_pm_api() {}
/// Payment Method Session - Confirm a payment method session
///
/// **Confirms a payment method session object with the payment method data**
#[utoipa::path(
post,
path = "/v2/payment-method-session/:id/confirm",
params (("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
)
),
request_body(
content = PaymentMethodSessionConfirmRequest,
examples(
(
"Confirm the payment method session with card details" = (
value = json!({
"payment_method_type": "card",
"payment_method_subtype": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_cvc": "123"
}
},
})
)
),
),
),
responses(
(status = 200, description = "Payment Method created", body = PaymentMethodResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payment Method Session",
operation_id = "Confirm the payment method session",
security(("publishable_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payment_method_session_confirm() {}
| 4,898 | 2,276 |
hyperswitch | crates/openapi/src/routes/refunds.rs | .rs | /// Refunds - Create
///
/// Creates a refund against an already processed payment. In case of some processors, you can even opt to refund only a partial amount multiple times until the original charge amount has been refunded
#[utoipa::path(
post,
path = "/refunds",
request_body(
content = RefundRequest,
examples(
(
"Create an instant refund to refund the whole amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"refund_type": "instant"
})
)
),
(
"Create an instant refund to refund partial amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"refund_type": "instant",
"amount": 654
})
)
),
(
"Create an instant refund with reason" = (
value = json!({
"payment_id": "{{payment_id}}",
"refund_type": "instant",
"amount": 6540,
"reason": "Customer returned product"
})
)
),
)
),
responses(
(status = 200, description = "Refund created", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Refunds",
operation_id = "Create a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn refunds_create() {}
/// Refunds - Retrieve
///
/// Retrieves a Refund. This may be used to get the status of a previously initiated refund
#[utoipa::path(
get,
path = "/refunds/{refund_id}",
params(
("refund_id" = String, Path, description = "The identifier for refund")
),
responses(
(status = 200, description = "Refund retrieved", body = RefundResponse),
(status = 404, description = "Refund does not exist in our records")
),
tag = "Refunds",
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
pub async fn refunds_retrieve() {}
/// Refunds - Retrieve (POST)
///
/// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/refunds/sync",
responses(
(status = 200, description = "Refund retrieved", body = RefundResponse),
(status = 404, description = "Refund does not exist in our records")
),
tag = "Refunds",
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
pub async fn refunds_retrieve_with_body() {}
/// Refunds - Update
///
/// Updates the properties of a Refund object. This API can be used to attach a reason for the refund or metadata fields
#[utoipa::path(
post,
path = "/refunds/{refund_id}",
params(
("refund_id" = String, Path, description = "The identifier for refund")
),
request_body(
content = RefundUpdateRequest,
examples(
(
"Update refund reason" = (
value = json!({
"reason": "Paid by mistake"
})
)
),
)
),
responses(
(status = 200, description = "Refund updated", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Refunds",
operation_id = "Update a Refund",
security(("api_key" = []))
)]
pub async fn refunds_update() {}
/// Refunds - List
///
/// Lists all the refunds associated with the merchant, or for a specific payment if payment_id is provided
#[utoipa::path(
post,
path = "/refunds/list",
request_body=RefundListRequest,
responses(
(status = 200, description = "List of refunds", body = RefundListResponse),
),
tag = "Refunds",
operation_id = "List all Refunds",
security(("api_key" = []))
)]
pub fn refunds_list() {}
/// Refunds - List For the Given profiles
///
/// Lists all the refunds associated with the merchant or a payment_id if payment_id is not provided
#[utoipa::path(
post,
path = "/refunds/profile/list",
request_body=RefundListRequest,
responses(
(status = 200, description = "List of refunds", body = RefundListResponse),
),
tag = "Refunds",
operation_id = "List all Refunds for the given Profiles",
security(("api_key" = []))
)]
pub fn refunds_list_profile() {}
/// Refunds - Filter
///
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
#[utoipa::path(
post,
path = "/refunds/filter",
request_body=TimeRange,
responses(
(status = 200, description = "List of filters", body = RefundListMetaData),
),
tag = "Refunds",
operation_id = "List all filters for Refunds",
security(("api_key" = []))
)]
pub async fn refunds_filter_list() {}
/// Refunds - Create
///
/// Creates a refund against an already processed payment. In case of some processors, you can even opt to refund only a partial amount multiple times until the original charge amount has been refunded
#[utoipa::path(
post,
path = "/v2/refunds",
request_body(
content = RefundsCreateRequest,
examples(
(
"Create an instant refund to refund the whole amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"merchant_reference_id": "ref_123",
"refund_type": "instant"
})
)
),
(
"Create an instant refund to refund partial amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"merchant_reference_id": "ref_123",
"refund_type": "instant",
"amount": 654
})
)
),
(
"Create an instant refund with reason" = (
value = json!({
"payment_id": "{{payment_id}}",
"merchant_reference_id": "ref_123",
"refund_type": "instant",
"amount": 6540,
"reason": "Customer returned product"
})
)
),
)
),
responses(
(status = 200, description = "Refund created", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Refunds",
operation_id = "Create a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn refunds_create() {}
| 1,541 | 2,277 |
hyperswitch | crates/openapi/src/routes/gsm.rs | .rs | /// Gsm - Create
///
/// Creates a GSM (Global Status Mapping) Rule. A GSM rule is used to map a connector's error message/error code combination during a particular payments flow/sub-flow to Hyperswitch's unified status/error code/error message combination. It is also used to decide the next action in the flow - retry/requeue/do_default
#[utoipa::path(
post,
path = "/gsm",
request_body(
content = GsmCreateRequest,
),
responses(
(status = 200, description = "Gsm created", body = GsmResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Gsm",
operation_id = "Create Gsm Rule",
security(("admin_api_key" = [])),
)]
pub async fn create_gsm_rule() {}
/// Gsm - Get
///
/// Retrieves a Gsm Rule
#[utoipa::path(
post,
path = "/gsm/get",
request_body(
content = GsmRetrieveRequest,
),
responses(
(status = 200, description = "Gsm retrieved", body = GsmResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Gsm",
operation_id = "Retrieve Gsm Rule",
security(("admin_api_key" = [])),
)]
pub async fn get_gsm_rule() {}
/// Gsm - Update
///
/// Updates a Gsm Rule
#[utoipa::path(
post,
path = "/gsm/update",
request_body(
content = GsmUpdateRequest,
),
responses(
(status = 200, description = "Gsm updated", body = GsmResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Gsm",
operation_id = "Update Gsm Rule",
security(("admin_api_key" = [])),
)]
pub async fn update_gsm_rule() {}
/// Gsm - Delete
///
/// Deletes a Gsm Rule
#[utoipa::path(
post,
path = "/gsm/delete",
request_body(
content = GsmDeleteRequest,
),
responses(
(status = 200, description = "Gsm deleted", body = GsmDeleteResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Gsm",
operation_id = "Delete Gsm Rule",
security(("admin_api_key" = [])),
)]
pub async fn delete_gsm_rule() {}
| 558 | 2,278 |
hyperswitch | crates/openapi/src/routes/payouts.rs | .rs | /// Payouts - Create
#[utoipa::path(
post,
path = "/payouts/create",
request_body=PayoutsCreateRequest,
responses(
(status = 200, description = "Payout created", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payouts",
operation_id = "Create a Payout",
security(("api_key" = []))
)]
pub async fn payouts_create() {}
/// Payouts - Retrieve
#[utoipa::path(
get,
path = "/payouts/{payout_id}",
params(
("payout_id" = String, Path, description = "The identifier for payout"),
("force_sync" = Option<bool>, Query, description = "Sync with the connector to get the payout details (defaults to false)")
),
responses(
(status = 200, description = "Payout retrieved", body = PayoutCreateResponse),
(status = 404, description = "Payout does not exist in our records")
),
tag = "Payouts",
operation_id = "Retrieve a Payout",
security(("api_key" = []))
)]
pub async fn payouts_retrieve() {}
/// Payouts - Update
#[utoipa::path(
post,
path = "/payouts/{payout_id}",
params(
("payout_id" = String, Path, description = "The identifier for payout")
),
request_body=PayoutUpdateRequest,
responses(
(status = 200, description = "Payout updated", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payouts",
operation_id = "Update a Payout",
security(("api_key" = []))
)]
pub async fn payouts_update() {}
/// Payouts - Cancel
#[utoipa::path(
post,
path = "/payouts/{payout_id}/cancel",
params(
("payout_id" = String, Path, description = "The identifier for payout")
),
request_body=PayoutCancelRequest,
responses(
(status = 200, description = "Payout cancelled", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payouts",
operation_id = "Cancel a Payout",
security(("api_key" = []))
)]
pub async fn payouts_cancel() {}
/// Payouts - Fulfill
#[utoipa::path(
post,
path = "/payouts/{payout_id}/fulfill",
params(
("payout_id" = String, Path, description = "The identifier for payout")
),
request_body=PayoutFulfillRequest,
responses(
(status = 200, description = "Payout fulfilled", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payouts",
operation_id = "Fulfill a Payout",
security(("api_key" = []))
)]
pub async fn payouts_fulfill() {}
/// Payouts - List
#[utoipa::path(
get,
path = "/payouts/list",
params(
("customer_id" = String, Query, description = "The identifier for customer"),
("starting_after" = String, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
("ending_before" = String, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
("limit" = String, Query, description = "limit on the number of objects to return"),
("created" = String, Query, description = "The time at which payout is created"),
("time_range" = String, Query, description = "The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).")
),
responses(
(status = 200, description = "Payouts listed", body = PayoutListResponse),
(status = 404, description = "Payout not found")
),
tag = "Payouts",
operation_id = "List payouts using generic constraints",
security(("api_key" = []))
)]
pub async fn payouts_list() {}
/// Payouts - List for the Given Profiles
#[utoipa::path(
get,
path = "/payouts/profile/list",
params(
("customer_id" = String, Query, description = "The identifier for customer"),
("starting_after" = String, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
("ending_before" = String, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
("limit" = String, Query, description = "limit on the number of objects to return"),
("created" = String, Query, description = "The time at which payout is created"),
("time_range" = String, Query, description = "The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).")
),
responses(
(status = 200, description = "Payouts listed", body = PayoutListResponse),
(status = 404, description = "Payout not found")
),
tag = "Payouts",
operation_id = "List payouts using generic constraints for the given Profiles",
security(("api_key" = []))
)]
pub async fn payouts_list_profile() {}
/// Payouts - List available filters
#[utoipa::path(
post,
path = "/payouts/filter",
request_body=TimeRange,
responses(
(status = 200, description = "Filters listed", body = PayoutListFilters)
),
tag = "Payouts",
operation_id = "List available payout filters",
security(("api_key" = []))
)]
pub async fn payouts_list_filters() {}
/// Payouts - List using filters
#[utoipa::path(
post,
path = "/payouts/list",
request_body=PayoutListFilterConstraints,
responses(
(status = 200, description = "Payouts filtered", body = PayoutListResponse),
(status = 404, description = "Payout not found")
),
tag = "Payouts",
operation_id = "Filter payouts using specific constraints",
security(("api_key" = []))
)]
pub async fn payouts_list_by_filter() {}
/// Payouts - List using filters for the given Profiles
#[utoipa::path(
post,
path = "/payouts/list",
request_body=PayoutListFilterConstraints,
responses(
(status = 200, description = "Payouts filtered", body = PayoutListResponse),
(status = 404, description = "Payout not found")
),
tag = "Payouts",
operation_id = "Filter payouts using specific constraints for the given Profiles",
security(("api_key" = []))
)]
pub async fn payouts_list_by_filter_profile() {}
/// Payouts - Confirm
#[utoipa::path(
post,
path = "/payouts/{payout_id}/confirm",
params(
("payout_id" = String, Path, description = "The identifier for payout")
),
request_body=PayoutConfirmRequest,
responses(
(status = 200, description = "Payout updated", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payouts",
operation_id = "Confirm a Payout",
security(("api_key" = []))
)]
pub async fn payouts_confirm() {}
| 1,765 | 2,279 |
hyperswitch | crates/openapi/src/routes/merchant_connector_account.rs | .rs | /// Merchant Connector - Create
///
/// Creates a new Merchant Connector for the merchant account. The connector could be a payment processor/facilitator/acquirer or a provider of specialized services like Fraud/Accounting etc.
#[cfg(feature = "v1")]
#[utoipa::path(
post,
path = "/accounts/{account_id}/connectors",
request_body(
content = MerchantConnectorCreate,
examples(
(
"Create a merchant connector account with minimal fields" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
}
})
)
),
(
"Create a merchant connector account under a specific profile" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
},
"profile_id": "{{profile_id}}"
})
)
),
(
"Create a merchant account with custom connector label" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_label": "EU_adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
}
})
)
),
)
),
responses(
(status = 200, description = "Merchant Connector Created", body = MerchantConnectorResponse),
(status = 400, description = "Missing Mandatory fields"),
),
tag = "Merchant Connector Account",
operation_id = "Create a Merchant Connector",
security(("api_key" = []))
)]
pub async fn connector_create() {}
/// Connector Account - Create
///
/// Creates a new Connector Account for the merchant account. The connector could be a payment processor/facilitator/acquirer or a provider of specialized services like Fraud/Accounting etc.
#[cfg(feature = "v2")]
#[utoipa::path(
post,
path = "/v2/connector-accounts",
request_body(
content = MerchantConnectorCreate,
examples(
(
"Create a merchant connector account with minimal fields" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
}
})
)
),
(
"Create a merchant connector account under a specific profile" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
},
"profile_id": "{{profile_id}}"
})
)
),
(
"Create a merchant account with custom connector label" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_label": "EU_adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
}
})
)
),
)
),
responses(
(status = 200, description = "Merchant Connector Created", body = MerchantConnectorResponse),
(status = 400, description = "Missing Mandatory fields"),
),
tag = "Merchant Connector Account",
operation_id = "Create a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_create() {}
/// Merchant Connector - Retrieve
///
/// Retrieves details of a Connector account
#[cfg(feature = "v1")]
#[utoipa::path(
get,
path = "/accounts/{account_id}/connectors/{connector_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("connector_id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector retrieved successfully", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Retrieve a Merchant Connector",
security(("api_key" = []))
)]
pub async fn connector_retrieve() {}
/// Connector Account - Retrieve
///
/// Retrieves details of a Connector account
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/connector-accounts/{id}",
params(
("id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector retrieved successfully", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Retrieve a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_retrieve() {}
/// Merchant Connector - List
///
/// List Merchant Connector Details for the merchant
#[utoipa::path(
get,
path = "/accounts/{account_id}/connectors",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
),
responses(
(status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnectorListResponse>),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "List all Merchant Connectors",
security(("api_key" = []))
)]
pub async fn connector_list() {}
/// Merchant Connector - Update
///
/// To update an existing Merchant Connector account. Helpful in enabling/disabling different payment methods and other settings for the connector
#[cfg(feature = "v1")]
#[utoipa::path(
post,
path = "/accounts/{account_id}/connectors/{connector_id}",
request_body(
content = MerchantConnectorUpdate,
examples(
(
"Enable card payment method" = (
value = json! ({
"connector_type": "payment_processor",
"payment_methods_enabled": [
{
"payment_method": "card"
}
]
})
)
),
(
"Update webhook secret" = (
value = json! ({
"connector_webhook_details": {
"merchant_secret": "{{webhook_secret}}"
}
})
)
)
),
),
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("connector_id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Updated", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Update a Merchant Connector",
security(("api_key" = []))
)]
pub async fn connector_update() {}
/// Connector Account - Update
///
/// To update an existing Connector account. Helpful in enabling/disabling different payment methods and other settings for the connector
#[cfg(feature = "v2")]
#[utoipa::path(
put,
path = "/v2/connector-accounts/{id}",
request_body(
content = MerchantConnectorUpdate,
examples(
(
"Enable card payment method" = (
value = json! ({
"connector_type": "payment_processor",
"payment_methods_enabled": [
{
"payment_method": "card"
}
]
})
)
),
(
"Update webhook secret" = (
value = json! ({
"connector_webhook_details": {
"merchant_secret": "{{webhook_secret}}"
}
})
)
)
),
),
params(
("id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Updated", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Update a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_update() {}
/// Merchant Connector - Delete
///
/// Delete or Detach a Merchant Connector from Merchant Account
#[cfg(feature = "v1")]
#[utoipa::path(
delete,
path = "/accounts/{account_id}/connectors/{connector_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("connector_id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Deleted", body = MerchantConnectorDeleteResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Delete a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_delete() {}
/// Merchant Connector - Delete
///
/// Delete or Detach a Merchant Connector from Merchant Account
#[cfg(feature = "v2")]
#[utoipa::path(
delete,
path = "/v2/connector-accounts/{id}",
params(
("id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Deleted", body = MerchantConnectorDeleteResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Delete a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_delete() {}
| 2,430 | 2,280 |
hyperswitch | crates/openapi/src/routes/profile.rs | .rs | // ******************************************** V1 profile routes ******************************************** //
#[cfg(feature = "v1")]
/// Profile - Create
///
/// Creates a new *profile* for a merchant
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile",
params (
("account_id" = String, Path, description = "The unique identifier for the merchant account")
),
request_body(
content = ProfileCreate,
examples(
(
"Create a profile with minimal fields" = (
value = json!({})
)
),
(
"Create a profile with profile name" = (
value = json!({
"profile_name": "shoe_business"
})
)
)
)
),
responses(
(status = 200, description = "Profile Created", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Create A Profile",
security(("api_key" = []))
)]
pub async fn profile_create() {}
#[cfg(feature = "v1")]
/// Profile - Update
///
/// Update the *profile*
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile/{profile_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("profile_id" = String, Path, description = "The unique identifier for the profile")
),
request_body(
content = ProfileCreate,
examples(
(
"Update profile with profile name fields" = (
value = json!({
"profile_name" : "shoe_business"
})
)
)
)),
responses(
(status = 200, description = "Profile Updated", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Update a Profile",
security(("api_key" = []))
)]
pub async fn profile_update() {}
#[cfg(feature = "v1")]
/// Profile - Retrieve
///
/// Retrieve existing *profile*
#[utoipa::path(
get,
path = "/account/{account_id}/business_profile/{profile_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("profile_id" = String, Path, description = "The unique identifier for the profile")
),
responses(
(status = 200, description = "Profile Updated", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Retrieve a Profile",
security(("api_key" = []))
)]
pub async fn profile_retrieve() {}
// ******************************************** Common profile routes ******************************************** //
/// Profile - Delete
///
/// Delete the *profile*
#[utoipa::path(
delete,
path = "/account/{account_id}/business_profile/{profile_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("profile_id" = String, Path, description = "The unique identifier for the profile")
),
responses(
(status = 200, description = "Profiles Deleted", body = bool),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Delete the Profile",
security(("admin_api_key" = []))
)]
pub async fn profile_delete() {}
/// Profile - List
///
/// Lists all the *profiles* under a merchant
#[utoipa::path(
get,
path = "/account/{account_id}/business_profile",
params (
("account_id" = String, Path, description = "Merchant Identifier"),
),
responses(
(status = 200, description = "Profiles Retrieved", body = Vec<ProfileResponse>)
),
tag = "Profile",
operation_id = "List Profiles",
security(("api_key" = []))
)]
pub async fn profile_list() {}
// ******************************************** V2 profile routes ******************************************** //
#[cfg(feature = "v2")]
/// Profile - Create
///
/// Creates a new *profile* for a merchant
#[utoipa::path(
post,
path = "/v2/profiles",
params(
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
),
),
request_body(
content = ProfileCreate,
examples(
(
"Create a profile with profile name" = (
value = json!({
"profile_name": "shoe_business"
})
)
)
)
),
responses(
(status = 200, description = "Account Created", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Create A Profile",
security(("admin_api_key" = []))
)]
pub async fn profile_create() {}
#[cfg(feature = "v2")]
/// Profile - Update
///
/// Update the *profile*
#[utoipa::path(
put,
path = "/v2/profiles/{id}",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
),
),
request_body(
content = ProfileCreate,
examples(
(
"Update profile with profile name fields" = (
value = json!({
"profile_name" : "shoe_business"
})
)
)
)),
responses(
(status = 200, description = "Profile Updated", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Update a Profile",
security(("admin_api_key" = []))
)]
pub async fn profile_update() {}
#[cfg(feature = "v2")]
/// Profile - Activate routing algorithm
///
/// Activates a routing algorithm under a profile
#[utoipa::path(
patch,
path = "/v2/profiles/{id}/activate-routing-algorithm",
request_body ( content = RoutingAlgorithmId,
examples( (
"Activate a routing algorithm" = (
value = json!({
"routing_algorithm_id": "routing_algorithm_123"
})
)
))),
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Routing Algorithm is activated", body = RoutingDictionaryRecord),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 400, description = "Bad request")
),
tag = "Profile",
operation_id = "Activates a routing algorithm under a profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_link_config() {}
#[cfg(feature = "v2")]
/// Profile - Deactivate routing algorithm
///
/// Deactivates a routing algorithm under a profile
#[utoipa::path(
patch,
path = "/v2/profiles/{id}/deactivate-routing-algorithm",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Successfully deactivated routing config", body = RoutingDictionaryRecord),
(status = 500, description = "Internal server error"),
(status = 400, description = "Malformed request"),
(status = 403, description = "Malformed request"),
(status = 422, description = "Unprocessable request")
),
tag = "Profile",
operation_id = " Deactivates a routing algorithm under a profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_unlink_config() {}
#[cfg(feature = "v2")]
/// Profile - Update Default Fallback Routing Algorithm
///
/// Update the default fallback routing algorithm for the profile
#[utoipa::path(
patch,
path = "/v2/profiles/{id}/fallback-routing",
request_body = Vec<RoutableConnectorChoice>,
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Successfully updated the default fallback routing algorithm", body = Vec<RoutableConnectorChoice>),
(status = 500, description = "Internal server error"),
(status = 400, description = "Malformed request"),
(status = 422, description = "Unprocessable request")
),
tag = "Profile",
operation_id = "Update the default fallback routing algorithm for the profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_update_default_config() {}
#[cfg(feature = "v2")]
/// Profile - Retrieve
///
/// Retrieve existing *profile*
#[utoipa::path(
get,
path = "/v2/profiles/{id}",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
),
),
responses(
(status = 200, description = "Profile Updated", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Retrieve a Profile",
security(("admin_api_key" = []))
)]
pub async fn profile_retrieve() {}
#[cfg(feature = "v2")]
/// Profile - Retrieve Active Routing Algorithm
///_
/// Retrieve active routing algorithm under the profile
#[utoipa::path(
get,
path = "/v2/profiles/{id}/routing-algorithm",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
("limit" = Option<u16>, Query, description = "The number of records of the algorithms to be returned"),
("offset" = Option<u8>, Query, description = "The record offset of the algorithm from which to start gathering the results")),
responses(
(status = 200, description = "Successfully retrieved active config", body = LinkedRoutingConfigRetrieveResponse),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 403, description = "Forbidden")
),
tag = "Profile",
operation_id = "Retrieve the active routing algorithm under the profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_linked_config() {}
#[cfg(feature = "v2")]
/// Profile - Retrieve Default Fallback Routing Algorithm
///
/// Retrieve the default fallback routing algorithm for the profile
#[utoipa::path(
get,
path = "/v2/profiles/{id}/fallback-routing",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Successfully retrieved default fallback routing algorithm", body = Vec<RoutableConnectorChoice>),
(status = 500, description = "Internal server error")
),
tag = "Profile",
operation_id = "Retrieve the default fallback routing algorithm for the profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_default_config() {}
/// Profile - Connector Accounts List
///
/// List Connector Accounts for the profile
#[utoipa::path(
get,
path = "/v2/profiles/{id}/connector-accounts",
params(
("id" = String, Path, description = "The unique identifier for the business profile"),
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
),
),
responses(
(status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnectorResponse>),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Business Profile",
operation_id = "List all Merchant Connectors",
security(("admin_api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn connector_list() {}
| 2,906 | 2,281 |
hyperswitch | crates/openapi/src/routes/blocklist.rs | .rs | #[utoipa::path(
post,
path = "/blocklist/toggle",
params (
("status" = bool, Query, description = "Boolean value to enable/disable blocklist"),
),
responses(
(status = 200, description = "Blocklist guard enabled/disabled", body = ToggleBlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "Toggle blocklist guard for a particular merchant",
security(("api_key" = []))
)]
pub async fn toggle_blocklist_guard() {}
#[utoipa::path(
post,
path = "/blocklist",
request_body = BlocklistRequest,
responses(
(status = 200, description = "Fingerprint Blocked", body = BlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "Block a Fingerprint",
security(("api_key" = []))
)]
pub async fn add_entry_to_blocklist() {}
#[utoipa::path(
delete,
path = "/blocklist",
request_body = BlocklistRequest,
responses(
(status = 200, description = "Fingerprint Unblocked", body = BlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "Unblock a Fingerprint",
security(("api_key" = []))
)]
pub async fn remove_entry_from_blocklist() {}
#[utoipa::path(
get,
path = "/blocklist",
params (
("data_kind" = BlocklistDataKind, Query, description = "Kind of the fingerprint list requested"),
),
responses(
(status = 200, description = "Blocked Fingerprints", body = BlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "List Blocked fingerprints of a particular kind",
security(("api_key" = []))
)]
pub async fn list_blocked_payment_methods() {}
| 462 | 2,282 |
hyperswitch | crates/openapi/src/routes/webhook_events.rs | .rs | /// Events - List
///
/// List all Events associated with a Merchant Account or Profile.
#[utoipa::path(
get,
path = "/events/{merchant_id}",
params(
(
"merchant_id" = String,
Path,
description = "The unique identifier for the Merchant Account."
),
(
"created_after" = Option<PrimitiveDateTime>,
Query,
description = "Only include Events created after the specified time. \
Either only `object_id` must be specified, or one or more of `created_after`, `created_before`, `limit` and `offset` must be specified."
),
(
"created_before" = Option<PrimitiveDateTime>,
Query,
description = "Only include Events created before the specified time. \
Either only `object_id` must be specified, or one or more of `created_after`, `created_before`, `limit` and `offset` must be specified."
),
(
"limit" = Option<i64>,
Query,
description = "The maximum number of Events to include in the response. \
Either only `object_id` must be specified, or one or more of `created_after`, `created_before`, `limit` and `offset` must be specified."
),
(
"offset" = Option<i64>,
Query,
description = "The number of Events to skip when retrieving the list of Events.
Either only `object_id` must be specified, or one or more of `created_after`, `created_before`, `limit` and `offset` must be specified."
),
(
"object_id" = Option<String>,
Query,
description = "Only include Events associated with the specified object (Payment Intent ID, Refund ID, etc.). \
Either only `object_id` must be specified, or one or more of `created_after`, `created_before`, `limit` and `offset` must be specified."
),
(
"profile_id" = Option<String>,
Query,
description = "Only include Events associated with the Profile identified by the specified Profile ID."
),
(
"is_delivered" = Option<bool>,
Query,
description = "Only include Events which are ultimately delivered to the merchant."
),
),
responses(
(status = 200, description = "List of Events retrieved successfully", body = TotalEventsResponse),
),
tag = "Event",
operation_id = "List all Events associated with a Merchant Account or Profile",
security(("admin_api_key" = []))
)]
pub fn list_initial_webhook_delivery_attempts() {}
/// Events - List
///
/// List all Events associated with a Profile.
#[utoipa::path(
get,
path = "/events/profile/list",
params(
(
"created_after" = Option<PrimitiveDateTime>,
Query,
description = "Only include Events created after the specified time. \
Either only `object_id` must be specified, or one or more of `created_after`, `created_before`, `limit` and `offset` must be specified."
),
(
"created_before" = Option<PrimitiveDateTime>,
Query,
description = "Only include Events created before the specified time. \
Either only `object_id` must be specified, or one or more of `created_after`, `created_before`, `limit` and `offset` must be specified."
),
(
"limit" = Option<i64>,
Query,
description = "The maximum number of Events to include in the response. \
Either only `object_id` must be specified, or one or more of `created_after`, `created_before`, `limit` and `offset` must be specified."
),
(
"offset" = Option<i64>,
Query,
description = "The number of Events to skip when retrieving the list of Events.
Either only `object_id` must be specified, or one or more of `created_after`, `created_before`, `limit` and `offset` must be specified."
),
(
"object_id" = Option<String>,
Query,
description = "Only include Events associated with the specified object (Payment Intent ID, Refund ID, etc.). \
Either only `object_id` must be specified, or one or more of `created_after`, `created_before`, `limit` and `offset` must be specified."
),
),
responses(
(status = 200, description = "List of Events retrieved successfully", body = Vec<EventListItemResponse>),
),
tag = "Event",
operation_id = "List all Events associated with a Profile",
security(("jwt_key" = []))
)]
pub fn list_initial_webhook_delivery_attempts_with_jwtauth() {}
/// Events - Delivery Attempt List
///
/// List all delivery attempts for the specified Event.
#[utoipa::path(
get,
path = "/events/{merchant_id}/{event_id}/attempts",
params(
("merchant_id" = String, Path, description = "The unique identifier for the Merchant Account."),
("event_id" = String, Path, description = "The unique identifier for the Event"),
),
responses(
(status = 200, description = "List of delivery attempts retrieved successfully", body = Vec<EventRetrieveResponse>),
),
tag = "Event",
operation_id = "List all delivery attempts for an Event",
security(("admin_api_key" = []))
)]
pub fn list_webhook_delivery_attempts() {}
/// Events - Manual Retry
///
/// Manually retry the delivery of the specified Event.
#[utoipa::path(
post,
path = "/events/{merchant_id}/{event_id}/retry",
params(
("merchant_id" = String, Path, description = "The unique identifier for the Merchant Account."),
("event_id" = String, Path, description = "The unique identifier for the Event"),
),
responses(
(
status = 200,
description = "The delivery of the Event was attempted. \
Check the `response` field in the response payload to identify the status of the delivery attempt.",
body = EventRetrieveResponse
),
),
tag = "Event",
operation_id = "Manually retry the delivery of an Event",
security(("admin_api_key" = []))
)]
pub fn retry_webhook_delivery_attempt() {}
| 1,353 | 2,283 |
hyperswitch | crates/openapi/src/routes/poll.rs | .rs | /// Poll - Retrieve Poll Status
#[utoipa::path(
get,
path = "/poll/status/{poll_id}",
params(
("poll_id" = String, Path, description = "The identifier for poll")
),
responses(
(status = 200, description = "The poll status was retrieved successfully", body = PollResponse),
(status = 404, description = "Poll not found")
),
tag = "Poll",
operation_id = "Retrieve Poll Status",
security(("publishable_key" = []))
)]
pub async fn retrieve_poll_status() {}
| 128 | 2,284 |
hyperswitch | crates/pm_auth/Cargo.toml | .toml | [package]
name = "pm_auth"
description = "Open banking services"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
readme = "README.md"
license.workspace = true
[features]
v1 = ["api_models/v1", "common_utils/v1"]
[dependencies]
# First party crates
api_models = { version = "0.1.0", path = "../api_models" }
common_enums = { version = "0.1.0", path = "../common_enums" }
common_utils = { version = "0.1.0", path = "../common_utils" }
masking = { version = "0.1.0", path = "../masking" }
# Third party crates
async-trait = "0.1.79"
bytes = "1.6.0"
error-stack = "0.4.1"
http = "0.2.12"
mime = "0.3.17"
serde = "1.0.197"
serde_json = "1.0.115"
strum = { version = "0.26.2", features = ["derive"] }
thiserror = "1.0.58"
[lints]
workspace = true
| 274 | 2,285 |
hyperswitch | crates/pm_auth/README.md | .md | # Payment Method Auth Services
An open banking services for payment method auth validation
| 16 | 2,286 |
hyperswitch | crates/pm_auth/src/core.rs | .rs | pub mod errors;
| 4 | 2,287 |
hyperswitch | crates/pm_auth/src/consts.rs | .rs | pub const REQUEST_TIME_OUT: u64 = 30; // will timeout after the mentioned limit
pub const REQUEST_TIMEOUT_ERROR_CODE: &str = "TIMEOUT"; // timeout error code
pub const REQUEST_TIMEOUT_ERROR_MESSAGE: &str = "Connector did not respond in specified time"; // error message for timed out request
pub const NO_ERROR_CODE: &str = "No error code";
pub const NO_ERROR_MESSAGE: &str = "No error message";
| 96 | 2,288 |
hyperswitch | crates/pm_auth/src/types.rs | .rs | pub mod api;
use std::marker::PhantomData;
use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate};
use api_models::enums as api_enums;
use common_enums::{CountryAlpha2, PaymentMethod, PaymentMethodType};
use common_utils::{id_type, types};
use masking::Secret;
#[derive(Debug, Clone)]
pub struct PaymentAuthRouterData<F, Request, Response> {
pub flow: PhantomData<F>,
pub merchant_id: Option<id_type::MerchantId>,
pub connector: Option<String>,
pub request: Request,
pub response: Result<Response, ErrorResponse>,
pub connector_auth_type: ConnectorAuthType,
pub connector_http_status_code: Option<u16>,
}
#[derive(Debug, Clone)]
pub struct LinkTokenRequest {
pub client_name: String,
pub country_codes: Option<Vec<String>>,
pub language: Option<String>,
pub user_info: Option<id_type::CustomerId>,
pub client_platform: Option<api_enums::ClientPlatform>,
pub android_package_name: Option<String>,
pub redirect_uri: Option<String>,
}
#[derive(Debug, Clone)]
pub struct LinkTokenResponse {
pub link_token: String,
}
pub type LinkTokenRouterData =
PaymentAuthRouterData<LinkToken, LinkTokenRequest, LinkTokenResponse>;
#[derive(Debug, Clone)]
pub struct ExchangeTokenRequest {
pub public_token: String,
}
#[derive(Debug, Clone)]
pub struct ExchangeTokenResponse {
pub access_token: String,
}
impl From<ExchangeTokenResponse> for api_models::pm_auth::ExchangeTokenCreateResponse {
fn from(value: ExchangeTokenResponse) -> Self {
Self {
access_token: value.access_token,
}
}
}
pub type ExchangeTokenRouterData =
PaymentAuthRouterData<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>;
#[derive(Debug, Clone)]
pub struct BankAccountCredentialsRequest {
pub access_token: Secret<String>,
pub optional_ids: Option<BankAccountOptionalIDs>,
}
#[derive(Debug, Clone)]
pub struct BankAccountOptionalIDs {
pub ids: Vec<Secret<String>>,
}
#[derive(Debug, Clone)]
pub struct BankAccountCredentialsResponse {
pub credentials: Vec<BankAccountDetails>,
}
#[derive(Debug, Clone)]
pub struct BankAccountDetails {
pub account_name: Option<String>,
pub account_details: PaymentMethodTypeDetails,
pub payment_method_type: PaymentMethodType,
pub payment_method: PaymentMethod,
pub account_id: Secret<String>,
pub account_type: Option<String>,
pub balance: Option<types::FloatMajorUnit>,
}
#[derive(Debug, Clone)]
pub enum PaymentMethodTypeDetails {
Ach(BankAccountDetailsAch),
Bacs(BankAccountDetailsBacs),
Sepa(BankAccountDetailsSepa),
}
#[derive(Debug, Clone)]
pub struct BankAccountDetailsAch {
pub account_number: Secret<String>,
pub routing_number: Secret<String>,
}
#[derive(Debug, Clone)]
pub struct BankAccountDetailsBacs {
pub account_number: Secret<String>,
pub sort_code: Secret<String>,
}
#[derive(Debug, Clone)]
pub struct BankAccountDetailsSepa {
pub iban: Secret<String>,
pub bic: Secret<String>,
}
pub type BankDetailsRouterData = PaymentAuthRouterData<
BankAccountCredentials,
BankAccountCredentialsRequest,
BankAccountCredentialsResponse,
>;
#[derive(Debug, Clone)]
pub struct RecipientCreateRequest {
pub name: String,
pub account_data: RecipientAccountData,
pub address: Option<RecipientCreateAddress>,
}
#[derive(Debug, Clone)]
pub struct RecipientCreateResponse {
pub recipient_id: String,
}
#[derive(Debug, Clone)]
pub enum RecipientAccountData {
Iban(Secret<String>),
Bacs {
sort_code: Secret<String>,
account_number: Secret<String>,
},
}
#[derive(Debug, Clone)]
pub struct RecipientCreateAddress {
pub street: String,
pub city: String,
pub postal_code: String,
pub country: CountryAlpha2,
}
pub type RecipientCreateRouterData =
PaymentAuthRouterData<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>;
pub type PaymentAuthLinkTokenType =
dyn api::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>;
pub type PaymentAuthExchangeTokenType =
dyn api::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>;
pub type PaymentAuthBankAccountDetailsType = dyn api::ConnectorIntegration<
BankAccountCredentials,
BankAccountCredentialsRequest,
BankAccountCredentialsResponse,
>;
pub type PaymentInitiationRecipientCreateType =
dyn api::ConnectorIntegration<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>;
#[derive(Clone, Debug, strum::EnumString, strum::Display)]
#[strum(serialize_all = "snake_case")]
pub enum PaymentMethodAuthConnectors {
Plaid,
}
#[derive(Debug, Clone)]
pub struct ResponseRouterData<Flow, R, Request, Response> {
pub response: R,
pub data: PaymentAuthRouterData<Flow, Request, Response>,
pub http_code: u16,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct ErrorResponse {
pub code: String,
pub message: String,
pub reason: Option<String>,
pub status_code: u16,
}
impl ErrorResponse {
fn get_not_implemented() -> Self {
Self {
code: "IR_00".to_string(),
message: "This API is under development and will be made available soon.".to_string(),
reason: None,
status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
}
}
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub enum MerchantAccountData {
Iban {
iban: Secret<String>,
name: String,
},
Bacs {
account_number: Secret<String>,
sort_code: Secret<String>,
name: String,
},
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MerchantRecipientData {
ConnectorRecipientId(Secret<String>),
WalletId(Secret<String>),
AccountData(MerchantAccountData),
}
#[derive(Default, Debug, Clone, serde::Deserialize)]
pub enum ConnectorAuthType {
BodyKey {
client_id: Secret<String>,
secret: Secret<String>,
},
#[default]
NoKey,
}
#[derive(Clone, Debug)]
pub struct Response {
pub headers: Option<http::HeaderMap>,
pub response: bytes::Bytes,
pub status_code: u16,
}
#[derive(serde::Deserialize, Clone)]
pub struct AuthServiceQueryParam {
pub client_secret: Option<String>,
}
| 1,432 | 2,289 |
hyperswitch | crates/pm_auth/src/lib.rs | .rs | pub mod connector;
pub mod consts;
pub mod core;
pub mod types;
| 16 | 2,290 |
hyperswitch | crates/pm_auth/src/connector.rs | .rs | pub mod plaid;
pub use self::plaid::Plaid;
| 15 | 2,291 |
hyperswitch | crates/pm_auth/src/types/api.rs | .rs | pub mod auth_service;
use std::fmt::Debug;
use common_utils::{
errors::CustomResult,
request::{Request, RequestContent},
};
use masking::Maskable;
use crate::{
core::errors::ConnectorError,
types::{
self as auth_types,
api::auth_service::{AuthService, PaymentInitiation},
},
};
#[async_trait::async_trait]
pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Resp> + Sync {
fn get_headers(
&self,
_req: &super::PaymentAuthRouterData<T, Req, Resp>,
_connectors: &auth_types::PaymentMethodAuthConnectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
Ok(vec![])
}
fn get_content_type(&self) -> &'static str {
mime::APPLICATION_JSON.essence_str()
}
fn get_url(
&self,
_req: &super::PaymentAuthRouterData<T, Req, Resp>,
_connectors: &auth_types::PaymentMethodAuthConnectors,
) -> CustomResult<String, ConnectorError> {
Ok(String::new())
}
fn get_request_body(
&self,
_req: &super::PaymentAuthRouterData<T, Req, Resp>,
) -> CustomResult<RequestContent, ConnectorError> {
Ok(RequestContent::Json(Box::new(serde_json::json!(r#"{}"#))))
}
fn build_request(
&self,
_req: &super::PaymentAuthRouterData<T, Req, Resp>,
_connectors: &auth_types::PaymentMethodAuthConnectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Ok(None)
}
fn handle_response(
&self,
data: &super::PaymentAuthRouterData<T, Req, Resp>,
_res: auth_types::Response,
) -> CustomResult<super::PaymentAuthRouterData<T, Req, Resp>, ConnectorError>
where
T: Clone,
Req: Clone,
Resp: Clone,
{
Ok(data.clone())
}
fn get_error_response(
&self,
_res: auth_types::Response,
) -> CustomResult<auth_types::ErrorResponse, ConnectorError> {
Ok(auth_types::ErrorResponse::get_not_implemented())
}
fn get_5xx_error_response(
&self,
res: auth_types::Response,
) -> CustomResult<auth_types::ErrorResponse, ConnectorError> {
let error_message = match res.status_code {
500 => "internal_server_error",
501 => "not_implemented",
502 => "bad_gateway",
503 => "service_unavailable",
504 => "gateway_timeout",
505 => "http_version_not_supported",
506 => "variant_also_negotiates",
507 => "insufficient_storage",
508 => "loop_detected",
510 => "not_extended",
511 => "network_authentication_required",
_ => "unknown_error",
};
Ok(auth_types::ErrorResponse {
code: res.status_code.to_string(),
message: error_message.to_string(),
reason: String::from_utf8(res.response.to_vec()).ok(),
status_code: res.status_code,
})
}
}
pub trait ConnectorCommonExt<Flow, Req, Resp>:
ConnectorCommon + ConnectorIntegration<Flow, Req, Resp>
{
fn build_headers(
&self,
_req: &auth_types::PaymentAuthRouterData<Flow, Req, Resp>,
_connectors: &auth_types::PaymentMethodAuthConnectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
Ok(Vec::new())
}
}
pub type BoxedConnectorIntegration<'a, T, Req, Resp> =
Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>;
pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static {
fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>;
}
impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S
where
S: ConnectorIntegration<T, Req, Resp>,
{
fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp> {
Box::new(self)
}
}
pub trait AuthServiceConnector: AuthService + Send + Debug + PaymentInitiation {}
impl<T: Send + Debug + AuthService + PaymentInitiation> AuthServiceConnector for T {}
pub type BoxedPaymentAuthConnector = Box<&'static (dyn AuthServiceConnector + Sync)>;
#[derive(Clone, Debug)]
pub struct PaymentAuthConnectorData {
pub connector: BoxedPaymentAuthConnector,
pub connector_name: super::PaymentMethodAuthConnectors,
}
pub trait ConnectorCommon {
fn id(&self) -> &'static str;
fn get_auth_header(
&self,
_auth_type: &auth_types::ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
Ok(Vec::new())
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a auth_types::PaymentMethodAuthConnectors) -> &'a str;
fn build_error_response(
&self,
res: auth_types::Response,
) -> CustomResult<auth_types::ErrorResponse, ConnectorError> {
Ok(auth_types::ErrorResponse {
status_code: res.status_code,
code: crate::consts::NO_ERROR_CODE.to_string(),
message: crate::consts::NO_ERROR_MESSAGE.to_string(),
reason: None,
})
}
}
| 1,259 | 2,292 |
hyperswitch | crates/pm_auth/src/types/api/auth_service.rs | .rs | use crate::types::{
BankAccountCredentialsRequest, BankAccountCredentialsResponse, ExchangeTokenRequest,
ExchangeTokenResponse, LinkTokenRequest, LinkTokenResponse, RecipientCreateRequest,
RecipientCreateResponse,
};
pub trait AuthService:
super::ConnectorCommon
+ AuthServiceLinkToken
+ AuthServiceExchangeToken
+ AuthServiceBankAccountCredentials
{
}
pub trait PaymentInitiation: super::ConnectorCommon + PaymentInitiationRecipientCreate {}
#[derive(Debug, Clone)]
pub struct LinkToken;
pub trait AuthServiceLinkToken:
super::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>
{
}
#[derive(Debug, Clone)]
pub struct ExchangeToken;
pub trait AuthServiceExchangeToken:
super::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>
{
}
#[derive(Debug, Clone)]
pub struct BankAccountCredentials;
pub trait AuthServiceBankAccountCredentials:
super::ConnectorIntegration<
BankAccountCredentials,
BankAccountCredentialsRequest,
BankAccountCredentialsResponse,
>
{
}
#[derive(Debug, Clone)]
pub struct RecipientCreate;
pub trait PaymentInitiationRecipientCreate:
super::ConnectorIntegration<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>
{
}
| 250 | 2,293 |
hyperswitch | crates/pm_auth/src/connector/plaid.rs | .rs | pub mod transformers;
use std::fmt::Debug;
use common_utils::{
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
};
use error_stack::ResultExt;
use masking::{Mask, Maskable};
use transformers as plaid;
use crate::{
core::errors,
types::{
self as auth_types,
api::{
auth_service::{
self, BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate,
},
ConnectorCommon, ConnectorCommonExt, ConnectorIntegration,
},
},
};
#[derive(Debug, Clone)]
pub struct Plaid;
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Plaid
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &auth_types::PaymentAuthRouterData<Flow, Request, Response>,
_connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
"Content-Type".to_string(),
self.get_content_type().to_string().into(),
)];
let mut auth = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut auth);
Ok(header)
}
}
impl ConnectorCommon for Plaid {
fn id(&self) -> &'static str {
"plaid"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, _connectors: &'a auth_types::PaymentMethodAuthConnectors) -> &'a str {
"https://sandbox.plaid.com"
}
fn get_auth_header(
&self,
auth_type: &auth_types::ConnectorAuthType,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = plaid::PlaidAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let client_id = auth.client_id.into_masked();
let secret = auth.secret.into_masked();
Ok(vec![
("PLAID-CLIENT-ID".to_string(), client_id),
("PLAID-SECRET".to_string(), secret),
])
}
fn build_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
let response: plaid::PlaidErrorResponse =
res.response
.parse_struct("PlaidErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
Ok(auth_types::ErrorResponse {
status_code: res.status_code,
code: crate::consts::NO_ERROR_CODE.to_string(),
message: response.error_message,
reason: response.display_message,
})
}
}
impl auth_service::AuthService for Plaid {}
impl auth_service::PaymentInitiationRecipientCreate for Plaid {}
impl auth_service::PaymentInitiation for Plaid {}
impl auth_service::AuthServiceLinkToken for Plaid {}
impl ConnectorIntegration<LinkToken, auth_types::LinkTokenRequest, auth_types::LinkTokenResponse>
for Plaid
{
fn get_headers(
&self,
req: &auth_types::LinkTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &auth_types::LinkTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"/link/token/create"
))
}
fn get_request_body(
&self,
req: &auth_types::LinkTokenRouterData,
) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = plaid::PlaidLinkTokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &auth_types::LinkTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&auth_types::PaymentAuthLinkTokenType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(auth_types::PaymentAuthLinkTokenType::get_headers(
self, req, connectors,
)?)
.set_body(auth_types::PaymentAuthLinkTokenType::get_request_body(
self, req,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &auth_types::LinkTokenRouterData,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::LinkTokenRouterData, errors::ConnectorError> {
let response: plaid::PlaidLinkTokenResponse = res
.response
.parse_struct("PlaidLinkTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
<auth_types::LinkTokenRouterData>::try_from(auth_types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
impl auth_service::AuthServiceExchangeToken for Plaid {}
impl
ConnectorIntegration<
ExchangeToken,
auth_types::ExchangeTokenRequest,
auth_types::ExchangeTokenResponse,
> for Plaid
{
fn get_headers(
&self,
req: &auth_types::ExchangeTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &auth_types::ExchangeTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"/item/public_token/exchange"
))
}
fn get_request_body(
&self,
req: &auth_types::ExchangeTokenRouterData,
) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = plaid::PlaidExchangeTokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &auth_types::ExchangeTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&auth_types::PaymentAuthExchangeTokenType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(auth_types::PaymentAuthExchangeTokenType::get_headers(
self, req, connectors,
)?)
.set_body(auth_types::PaymentAuthExchangeTokenType::get_request_body(
self, req,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &auth_types::ExchangeTokenRouterData,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ExchangeTokenRouterData, errors::ConnectorError> {
let response: plaid::PlaidExchangeTokenResponse = res
.response
.parse_struct("PlaidExchangeTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
<auth_types::ExchangeTokenRouterData>::try_from(auth_types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
impl auth_service::AuthServiceBankAccountCredentials for Plaid {}
impl
ConnectorIntegration<
BankAccountCredentials,
auth_types::BankAccountCredentialsRequest,
auth_types::BankAccountCredentialsResponse,
> for Plaid
{
fn get_headers(
&self,
req: &auth_types::BankDetailsRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &auth_types::BankDetailsRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "/auth/get"))
}
fn get_request_body(
&self,
req: &auth_types::BankDetailsRouterData,
) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = plaid::PlaidBankAccountCredentialsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &auth_types::BankDetailsRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&auth_types::PaymentAuthBankAccountDetailsType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(auth_types::PaymentAuthBankAccountDetailsType::get_headers(
self, req, connectors,
)?)
.set_body(
auth_types::PaymentAuthBankAccountDetailsType::get_request_body(self, req)?,
)
.build(),
))
}
fn handle_response(
&self,
data: &auth_types::BankDetailsRouterData,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::BankDetailsRouterData, errors::ConnectorError> {
let response: plaid::PlaidBankAccountCredentialsResponse = res
.response
.parse_struct("PlaidBankAccountCredentialsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
<auth_types::BankDetailsRouterData>::try_from(auth_types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
impl
ConnectorIntegration<
RecipientCreate,
auth_types::RecipientCreateRequest,
auth_types::RecipientCreateResponse,
> for Plaid
{
fn get_headers(
&self,
req: &auth_types::RecipientCreateRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &auth_types::RecipientCreateRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"/payment_initiation/recipient/create"
))
}
fn get_request_body(
&self,
req: &auth_types::RecipientCreateRouterData,
) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = plaid::PlaidRecipientCreateRequest::from(req);
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &auth_types::RecipientCreateRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&auth_types::PaymentInitiationRecipientCreateType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(
auth_types::PaymentInitiationRecipientCreateType::get_headers(
self, req, connectors,
)?,
)
.set_body(
auth_types::PaymentInitiationRecipientCreateType::get_request_body(self, req)?,
)
.build(),
))
}
fn handle_response(
&self,
data: &auth_types::RecipientCreateRouterData,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::RecipientCreateRouterData, errors::ConnectorError> {
let response: plaid::PlaidRecipientCreateResponse = res
.response
.parse_struct("PlaidRecipientCreateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
Ok(<auth_types::RecipientCreateRouterData>::from(
auth_types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
))
}
fn get_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
| 3,130 | 2,294 |
hyperswitch | crates/pm_auth/src/connector/plaid/transformers.rs | .rs | use std::collections::HashMap;
use common_enums::{PaymentMethod, PaymentMethodType};
use common_utils::{id_type, types as util_types};
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{core::errors, types};
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidLinkTokenRequest {
client_name: String,
country_codes: Vec<String>,
language: String,
products: Vec<String>,
user: User,
android_package_name: Option<String>,
redirect_uri: Option<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct User {
pub client_user_id: id_type::CustomerId,
}
impl TryFrom<&types::LinkTokenRouterData> for PlaidLinkTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::LinkTokenRouterData) -> Result<Self, Self::Error> {
Ok(Self {
client_name: item.request.client_name.clone(),
country_codes: item.request.country_codes.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "country_codes",
},
)?,
language: item.request.language.clone().unwrap_or("en".to_string()),
products: vec!["auth".to_string()],
user: User {
client_user_id: item.request.user_info.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "country_codes",
},
)?,
},
android_package_name: match item.request.client_platform {
Some(api_models::enums::ClientPlatform::Android) => {
item.request.android_package_name.clone()
}
Some(api_models::enums::ClientPlatform::Ios)
| Some(api_models::enums::ClientPlatform::Web)
| Some(api_models::enums::ClientPlatform::Unknown)
| None => None,
},
redirect_uri: match item.request.client_platform {
Some(api_models::enums::ClientPlatform::Ios) => item.request.redirect_uri.clone(),
Some(api_models::enums::ClientPlatform::Android)
| Some(api_models::enums::ClientPlatform::Web)
| Some(api_models::enums::ClientPlatform::Unknown)
| None => None,
},
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidLinkTokenResponse {
link_token: String,
}
impl<F, T>
TryFrom<types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::LinkTokenResponse>>
for types::PaymentAuthRouterData<F, T, types::LinkTokenResponse>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::LinkTokenResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::LinkTokenResponse {
link_token: item.response.link_token,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidExchangeTokenRequest {
public_token: String,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidExchangeTokenResponse {
pub access_token: String,
}
impl<F, T>
TryFrom<
types::ResponseRouterData<F, PlaidExchangeTokenResponse, T, types::ExchangeTokenResponse>,
> for types::PaymentAuthRouterData<F, T, types::ExchangeTokenResponse>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: types::ResponseRouterData<
F,
PlaidExchangeTokenResponse,
T,
types::ExchangeTokenResponse,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::ExchangeTokenResponse {
access_token: item.response.access_token,
}),
..item.data
})
}
}
impl TryFrom<&types::ExchangeTokenRouterData> for PlaidExchangeTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::ExchangeTokenRouterData) -> Result<Self, Self::Error> {
Ok(Self {
public_token: item.request.public_token.clone(),
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PlaidRecipientCreateRequest {
pub name: String,
#[serde(flatten)]
pub account_data: PlaidRecipientAccountData,
pub address: Option<PlaidRecipientCreateAddress>,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidRecipientCreateResponse {
pub recipient_id: String,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum PlaidRecipientAccountData {
Iban(Secret<String>),
Bacs {
sort_code: Secret<String>,
account: Secret<String>,
},
}
impl From<&types::RecipientAccountData> for PlaidRecipientAccountData {
fn from(item: &types::RecipientAccountData) -> Self {
match item {
types::RecipientAccountData::Iban(iban) => Self::Iban(iban.clone()),
types::RecipientAccountData::Bacs {
sort_code,
account_number,
} => Self::Bacs {
sort_code: sort_code.clone(),
account: account_number.clone(),
},
}
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PlaidRecipientCreateAddress {
pub street: String,
pub city: String,
pub postal_code: String,
pub country: String,
}
impl From<&types::RecipientCreateAddress> for PlaidRecipientCreateAddress {
fn from(item: &types::RecipientCreateAddress) -> Self {
Self {
street: item.street.clone(),
city: item.city.clone(),
postal_code: item.postal_code.clone(),
country: common_enums::CountryAlpha2::to_string(&item.country),
}
}
}
impl From<&types::RecipientCreateRouterData> for PlaidRecipientCreateRequest {
fn from(item: &types::RecipientCreateRouterData) -> Self {
Self {
name: item.request.name.clone(),
account_data: PlaidRecipientAccountData::from(&item.request.account_data),
address: item
.request
.address
.as_ref()
.map(PlaidRecipientCreateAddress::from),
}
}
}
impl<F, T>
From<
types::ResponseRouterData<
F,
PlaidRecipientCreateResponse,
T,
types::RecipientCreateResponse,
>,
> for types::PaymentAuthRouterData<F, T, types::RecipientCreateResponse>
{
fn from(
item: types::ResponseRouterData<
F,
PlaidRecipientCreateResponse,
T,
types::RecipientCreateResponse,
>,
) -> Self {
Self {
response: Ok(types::RecipientCreateResponse {
recipient_id: item.response.recipient_id,
}),
..item.data
}
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidBankAccountCredentialsRequest {
access_token: String,
options: Option<BankAccountCredentialsOptions>,
}
#[derive(Debug, Deserialize, PartialEq)]
pub struct PlaidBankAccountCredentialsResponse {
pub accounts: Vec<PlaidBankAccountCredentialsAccounts>,
pub numbers: PlaidBankAccountCredentialsNumbers,
// pub item: PlaidBankAccountCredentialsItem,
pub request_id: String,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct BankAccountCredentialsOptions {
account_ids: Vec<String>,
}
#[derive(Debug, Deserialize, PartialEq)]
pub struct PlaidBankAccountCredentialsAccounts {
pub account_id: String,
pub name: String,
pub subtype: Option<String>,
pub balances: Option<PlaidBankAccountCredentialsBalances>,
}
#[derive(Debug, Deserialize, PartialEq)]
pub struct PlaidBankAccountCredentialsBalances {
pub available: Option<util_types::FloatMajorUnit>,
pub current: Option<util_types::FloatMajorUnit>,
pub limit: Option<util_types::FloatMajorUnit>,
pub iso_currency_code: Option<String>,
pub unofficial_currency_code: Option<String>,
pub last_updated_datetime: Option<String>,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsNumbers {
pub ach: Vec<PlaidBankAccountCredentialsACH>,
pub eft: Vec<PlaidBankAccountCredentialsEFT>,
pub international: Vec<PlaidBankAccountCredentialsInternational>,
pub bacs: Vec<PlaidBankAccountCredentialsBacs>,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsItem {
pub item_id: String,
pub institution_id: Option<String>,
pub webhook: Option<String>,
pub error: Option<PlaidErrorResponse>,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsACH {
pub account_id: String,
pub account: String,
pub routing: String,
pub wire_routing: Option<String>,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsEFT {
pub account_id: String,
pub account: String,
pub institution: String,
pub branch: String,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsInternational {
pub account_id: String,
pub iban: String,
pub bic: String,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsBacs {
pub account_id: String,
pub account: String,
pub sort_code: String,
}
impl TryFrom<&types::BankDetailsRouterData> for PlaidBankAccountCredentialsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::BankDetailsRouterData) -> Result<Self, Self::Error> {
let options = item.request.optional_ids.as_ref().map(|bank_account_ids| {
let ids = bank_account_ids
.ids
.iter()
.map(|id| id.peek().to_string())
.collect::<Vec<_>>();
BankAccountCredentialsOptions { account_ids: ids }
});
Ok(Self {
access_token: item.request.access_token.peek().to_string(),
options,
})
}
}
impl<F, T>
TryFrom<
types::ResponseRouterData<
F,
PlaidBankAccountCredentialsResponse,
T,
types::BankAccountCredentialsResponse,
>,
> for types::PaymentAuthRouterData<F, T, types::BankAccountCredentialsResponse>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: types::ResponseRouterData<
F,
PlaidBankAccountCredentialsResponse,
T,
types::BankAccountCredentialsResponse,
>,
) -> Result<Self, Self::Error> {
let (account_numbers, accounts_info) = (item.response.numbers, item.response.accounts);
let mut bank_account_vec = Vec::new();
let mut id_to_subtype = HashMap::new();
accounts_info.into_iter().for_each(|acc| {
id_to_subtype.insert(
acc.account_id,
(
acc.subtype,
acc.name,
acc.balances.and_then(|balance| balance.available),
),
);
});
account_numbers.ach.into_iter().for_each(|ach| {
let (acc_type, acc_name, available_balance) = if let Some((
_type,
name,
available_balance,
)) = id_to_subtype.get(&ach.account_id)
{
(_type.to_owned(), Some(name.clone()), *available_balance)
} else {
(None, None, None)
};
let account_details =
types::PaymentMethodTypeDetails::Ach(types::BankAccountDetailsAch {
account_number: Secret::new(ach.account),
routing_number: Secret::new(ach.routing),
});
let bank_details_new = types::BankAccountDetails {
account_name: acc_name,
account_details,
payment_method_type: PaymentMethodType::Ach,
payment_method: PaymentMethod::BankDebit,
account_id: ach.account_id.into(),
account_type: acc_type,
balance: available_balance,
};
bank_account_vec.push(bank_details_new);
});
account_numbers.bacs.into_iter().for_each(|bacs| {
let (acc_type, acc_name, available_balance) =
if let Some((_type, name, available_balance)) = id_to_subtype.get(&bacs.account_id)
{
(_type.to_owned(), Some(name.clone()), *available_balance)
} else {
(None, None, None)
};
let account_details =
types::PaymentMethodTypeDetails::Bacs(types::BankAccountDetailsBacs {
account_number: Secret::new(bacs.account),
sort_code: Secret::new(bacs.sort_code),
});
let bank_details_new = types::BankAccountDetails {
account_name: acc_name,
account_details,
payment_method_type: PaymentMethodType::Bacs,
payment_method: PaymentMethod::BankDebit,
account_id: bacs.account_id.into(),
account_type: acc_type,
balance: available_balance,
};
bank_account_vec.push(bank_details_new);
});
account_numbers.international.into_iter().for_each(|sepa| {
let (acc_type, acc_name, available_balance) =
if let Some((_type, name, available_balance)) = id_to_subtype.get(&sepa.account_id)
{
(_type.to_owned(), Some(name.clone()), *available_balance)
} else {
(None, None, None)
};
let account_details =
types::PaymentMethodTypeDetails::Sepa(types::BankAccountDetailsSepa {
iban: Secret::new(sepa.iban),
bic: Secret::new(sepa.bic),
});
let bank_details_new = types::BankAccountDetails {
account_name: acc_name,
account_details,
payment_method_type: PaymentMethodType::Sepa,
payment_method: PaymentMethod::BankDebit,
account_id: sepa.account_id.into(),
account_type: acc_type,
balance: available_balance,
};
bank_account_vec.push(bank_details_new);
});
Ok(Self {
response: Ok(types::BankAccountCredentialsResponse {
credentials: bank_account_vec,
}),
..item.data
})
}
}
pub struct PlaidAuthType {
pub client_id: Secret<String>,
pub secret: Secret<String>,
}
impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
types::ConnectorAuthType::BodyKey { client_id, secret } => Ok(Self {
client_id: client_id.to_owned(),
secret: secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, 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>,
}
| 3,357 | 2,295 |
hyperswitch | crates/pm_auth/src/core/errors.rs | .rs | #[derive(Debug, thiserror::Error, PartialEq)]
pub enum ConnectorError {
#[error("Failed to obtain authentication type")]
FailedToObtainAuthType,
#[error("Missing required field: {field_name}")]
MissingRequiredField { field_name: &'static str },
#[error("Failed to execute a processing step: {0:?}")]
ProcessingStepFailed(Option<bytes::Bytes>),
#[error("Failed to deserialize connector response")]
ResponseDeserializationFailed,
#[error("Failed to encode connector request")]
RequestEncodingFailed,
}
pub type CustomResult<T, E> = error_stack::Result<T, E>;
#[derive(Debug, thiserror::Error)]
pub enum ParsingError {
#[error("Failed to parse enum: {0}")]
EnumParseFailure(&'static str),
#[error("Failed to parse struct: {0}")]
StructParseFailure(&'static str),
#[error("Failed to serialize to {0} format")]
EncodeError(&'static str),
#[error("Unknown error while parsing")]
UnknownError,
}
| 225 | 2,296 |
hyperswitch | crates/kgraph_utils/Cargo.toml | .toml | [package]
name = "kgraph_utils"
description = "Utilities for constructing and working with Knowledge Graphs"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[features]
dummy_connector = ["api_models/dummy_connector", "euclid/dummy_connector"]
v1 = ["api_models/v1", "common_utils/v1", "common_types/v1"]
v2 = ["api_models/v2", "common_utils/v2", "common_types/v2", "common_enums/v2"]
[dependencies]
api_models = { version = "0.1.0", path = "../api_models", package = "api_models" }
common_enums = { version = "0.1.0", path = "../common_enums" }
common_utils = { version = "0.1.0", path = "../common_utils" }
common_types = {version = "0.1.0", path = "../common_types" }
euclid = { version = "0.1.0", path = "../euclid" }
hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph", features = ["viz"] }
masking = { version = "0.1.0", path = "../masking/" }
# Third party crates
serde = "1.0.197"
serde_json = "1.0.115"
strum = { version = "0.26", features = ["derive"] }
thiserror = "1.0.58"
[dev-dependencies]
criterion = "0.5"
[[bench]]
name = "evaluation"
harness = false
[lints]
workspace = true
| 370 | 2,297 |
hyperswitch | crates/kgraph_utils/benches/evaluation.rs | .rs | #![allow(unused, clippy::expect_used)]
use std::{collections::HashMap, str::FromStr};
use api_models::{
admin as admin_api, enums as api_enums, payment_methods::RequestPaymentMethodTypes,
};
use common_utils::types::MinorUnit;
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use euclid::{
dirval,
dssa::graph::{self, CgraphExt},
frontend::dir,
types::{NumValue, NumValueRefinement},
};
use hyperswitch_constraint_graph::{CycleCheck, Memoization};
use kgraph_utils::{error::KgraphError, transformers::IntoDirValue, types::CountryCurrencyFilter};
#[cfg(feature = "v1")]
fn build_test_data(
total_enabled: usize,
total_pm_types: usize,
) -> hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue> {
use api_models::{admin::*, payment_methods::*};
let mut pms_enabled: Vec<PaymentMethodsEnabled> = Vec::new();
for _ in (0..total_enabled) {
let mut pm_types: Vec<RequestPaymentMethodTypes> = Vec::new();
for _ in (0..total_pm_types) {
pm_types.push(RequestPaymentMethodTypes {
payment_method_type: api_enums::PaymentMethodType::Credit,
payment_experience: None,
card_networks: Some(vec![
api_enums::CardNetwork::Visa,
api_enums::CardNetwork::Mastercard,
]),
accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![
api_enums::Currency::USD,
api_enums::Currency::INR,
])),
accepted_countries: None,
minimum_amount: Some(MinorUnit::new(10)),
maximum_amount: Some(MinorUnit::new(1000)),
recurring_enabled: true,
installment_payment_enabled: true,
});
}
pms_enabled.push(PaymentMethodsEnabled {
payment_method: api_enums::PaymentMethod::Card,
payment_method_types: Some(pm_types),
});
}
let profile_id = common_utils::generate_profile_id_of_default_length();
// #[cfg(feature = "v2")]
// let stripe_account = MerchantConnectorResponse {
// connector_type: api_enums::ConnectorType::FizOperations,
// connector_name: "stripe".to_string(),
// id: common_utils::generate_merchant_connector_account_id_of_default_length(),
// connector_account_details: masking::Secret::new(serde_json::json!({})),
// disabled: None,
// metadata: None,
// payment_methods_enabled: Some(pms_enabled),
// connector_label: Some("something".to_string()),
// frm_configs: None,
// connector_webhook_details: None,
// profile_id,
// applepay_verified_domains: None,
// pm_auth_config: None,
// status: api_enums::ConnectorStatus::Inactive,
// additional_merchant_data: None,
// connector_wallets_details: None,
// };
#[cfg(feature = "v1")]
let stripe_account = MerchantConnectorResponse {
connector_type: api_enums::ConnectorType::FizOperations,
connector_name: "stripe".to_string(),
merchant_connector_id:
common_utils::generate_merchant_connector_account_id_of_default_length(),
connector_account_details: masking::Secret::new(serde_json::json!({})),
test_mode: None,
disabled: None,
metadata: None,
payment_methods_enabled: Some(pms_enabled),
business_country: Some(api_enums::CountryAlpha2::US),
business_label: Some("hello".to_string()),
connector_label: Some("something".to_string()),
business_sub_label: Some("something".to_string()),
frm_configs: None,
connector_webhook_details: None,
profile_id,
applepay_verified_domains: None,
pm_auth_config: None,
status: api_enums::ConnectorStatus::Inactive,
additional_merchant_data: None,
connector_wallets_details: None,
};
let config = CountryCurrencyFilter {
connector_configs: HashMap::new(),
default_configs: None,
};
#[cfg(feature = "v1")]
kgraph_utils::mca::make_mca_graph(vec![stripe_account], &config)
.expect("Failed graph construction")
}
#[cfg(feature = "v1")]
fn evaluation(c: &mut Criterion) {
let small_graph = build_test_data(3, 8);
let big_graph = build_test_data(20, 20);
c.bench_function("MCA Small Graph Evaluation", |b| {
b.iter(|| {
small_graph.key_value_analysis(
dirval!(Connector = Stripe),
&graph::AnalysisContext::from_dir_values([
dirval!(Connector = Stripe),
dirval!(PaymentMethod = Card),
dirval!(CardType = Credit),
dirval!(CardNetwork = Visa),
dirval!(PaymentCurrency = BWP),
dirval!(PaymentAmount = 100),
]),
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
});
});
c.bench_function("MCA Big Graph Evaluation", |b| {
b.iter(|| {
big_graph.key_value_analysis(
dirval!(Connector = Stripe),
&graph::AnalysisContext::from_dir_values([
dirval!(Connector = Stripe),
dirval!(PaymentMethod = Card),
dirval!(CardType = Credit),
dirval!(CardNetwork = Visa),
dirval!(PaymentCurrency = BWP),
dirval!(PaymentAmount = 100),
]),
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
});
});
}
#[cfg(feature = "v1")]
criterion_group!(benches, evaluation);
#[cfg(feature = "v1")]
criterion_main!(benches);
#[cfg(feature = "v2")]
fn main() {}
| 1,305 | 2,298 |
hyperswitch | crates/kgraph_utils/src/mca.rs | .rs | use std::str::FromStr;
use api_models::{
admin as admin_api, enums as api_enums, payment_methods::RequestPaymentMethodTypes,
refunds::MinorUnit,
};
use euclid::{
dirval,
frontend::{ast, dir},
types::{NumValue, NumValueRefinement},
};
use hyperswitch_constraint_graph as cgraph;
use strum::IntoEnumIterator;
use crate::{error::KgraphError, transformers::IntoDirValue, types as kgraph_types};
pub const DOMAIN_IDENTIFIER: &str = "payment_methods_enabled_for_merchantconnectoraccount";
// #[cfg(feature = "v1")]
fn get_dir_value_payment_method(
from: api_enums::PaymentMethodType,
) -> Result<dir::DirValue, KgraphError> {
match from {
api_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)),
api_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)),
api_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)),
#[cfg(feature = "v2")]
api_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)),
api_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)),
api_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)),
api_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)),
api_enums::PaymentMethodType::Eps => Ok(dirval!(BankRedirectType = Eps)),
api_enums::PaymentMethodType::Eft => Ok(dirval!(BankRedirectType = Eft)),
api_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)),
api_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)),
api_enums::PaymentMethodType::AfterpayClearpay => {
Ok(dirval!(PayLaterType = AfterpayClearpay))
}
api_enums::PaymentMethodType::GooglePay => Ok(dirval!(WalletType = GooglePay)),
api_enums::PaymentMethodType::ApplePay => Ok(dirval!(WalletType = ApplePay)),
api_enums::PaymentMethodType::Paypal => Ok(dirval!(WalletType = Paypal)),
api_enums::PaymentMethodType::CryptoCurrency => Ok(dirval!(CryptoType = CryptoCurrency)),
api_enums::PaymentMethodType::Ach => Ok(dirval!(BankDebitType = Ach)),
api_enums::PaymentMethodType::Bacs => Ok(dirval!(BankDebitType = Bacs)),
api_enums::PaymentMethodType::Becs => Ok(dirval!(BankDebitType = Becs)),
api_enums::PaymentMethodType::Sepa => Ok(dirval!(BankDebitType = Sepa)),
api_enums::PaymentMethodType::AliPay => Ok(dirval!(WalletType = AliPay)),
api_enums::PaymentMethodType::AliPayHk => Ok(dirval!(WalletType = AliPayHk)),
api_enums::PaymentMethodType::BancontactCard => {
Ok(dirval!(BankRedirectType = BancontactCard))
}
api_enums::PaymentMethodType::Blik => Ok(dirval!(BankRedirectType = Blik)),
api_enums::PaymentMethodType::MbWay => Ok(dirval!(WalletType = MbWay)),
api_enums::PaymentMethodType::MobilePay => Ok(dirval!(WalletType = MobilePay)),
api_enums::PaymentMethodType::Cashapp => Ok(dirval!(WalletType = Cashapp)),
api_enums::PaymentMethodType::Multibanco => Ok(dirval!(BankTransferType = Multibanco)),
api_enums::PaymentMethodType::Pix => Ok(dirval!(BankTransferType = Pix)),
api_enums::PaymentMethodType::Pse => Ok(dirval!(BankTransferType = Pse)),
api_enums::PaymentMethodType::Interac => Ok(dirval!(BankRedirectType = Interac)),
api_enums::PaymentMethodType::OnlineBankingCzechRepublic => {
Ok(dirval!(BankRedirectType = OnlineBankingCzechRepublic))
}
api_enums::PaymentMethodType::OnlineBankingFinland => {
Ok(dirval!(BankRedirectType = OnlineBankingFinland))
}
api_enums::PaymentMethodType::OnlineBankingPoland => {
Ok(dirval!(BankRedirectType = OnlineBankingPoland))
}
api_enums::PaymentMethodType::OnlineBankingSlovakia => {
Ok(dirval!(BankRedirectType = OnlineBankingSlovakia))
}
api_enums::PaymentMethodType::Swish => Ok(dirval!(WalletType = Swish)),
api_enums::PaymentMethodType::Trustly => Ok(dirval!(BankRedirectType = Trustly)),
api_enums::PaymentMethodType::Bizum => Ok(dirval!(BankRedirectType = Bizum)),
api_enums::PaymentMethodType::PayBright => Ok(dirval!(PayLaterType = PayBright)),
api_enums::PaymentMethodType::Walley => Ok(dirval!(PayLaterType = Walley)),
api_enums::PaymentMethodType::Przelewy24 => Ok(dirval!(BankRedirectType = Przelewy24)),
api_enums::PaymentMethodType::WeChatPay => Ok(dirval!(WalletType = WeChatPay)),
api_enums::PaymentMethodType::ClassicReward => Ok(dirval!(RewardType = ClassicReward)),
api_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)),
api_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)),
api_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)),
api_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)),
api_enums::PaymentMethodType::Twint => Ok(dirval!(WalletType = Twint)),
api_enums::PaymentMethodType::Gcash => Ok(dirval!(WalletType = Gcash)),
api_enums::PaymentMethodType::Vipps => Ok(dirval!(WalletType = Vipps)),
api_enums::PaymentMethodType::Momo => Ok(dirval!(WalletType = Momo)),
api_enums::PaymentMethodType::Alma => Ok(dirval!(PayLaterType = Alma)),
api_enums::PaymentMethodType::Dana => Ok(dirval!(WalletType = Dana)),
api_enums::PaymentMethodType::OnlineBankingFpx => {
Ok(dirval!(BankRedirectType = OnlineBankingFpx))
}
api_enums::PaymentMethodType::OnlineBankingThailand => {
Ok(dirval!(BankRedirectType = OnlineBankingThailand))
}
api_enums::PaymentMethodType::LocalBankRedirect => {
Ok(dirval!(BankRedirectType = LocalBankRedirect))
}
api_enums::PaymentMethodType::TouchNGo => Ok(dirval!(WalletType = TouchNGo)),
api_enums::PaymentMethodType::Atome => Ok(dirval!(PayLaterType = Atome)),
api_enums::PaymentMethodType::Boleto => Ok(dirval!(VoucherType = Boleto)),
api_enums::PaymentMethodType::Efecty => Ok(dirval!(VoucherType = Efecty)),
api_enums::PaymentMethodType::PagoEfectivo => Ok(dirval!(VoucherType = PagoEfectivo)),
api_enums::PaymentMethodType::RedCompra => Ok(dirval!(VoucherType = RedCompra)),
api_enums::PaymentMethodType::RedPagos => Ok(dirval!(VoucherType = RedPagos)),
api_enums::PaymentMethodType::Alfamart => Ok(dirval!(VoucherType = Alfamart)),
api_enums::PaymentMethodType::BcaBankTransfer => {
Ok(dirval!(BankTransferType = BcaBankTransfer))
}
api_enums::PaymentMethodType::BniVa => Ok(dirval!(BankTransferType = BniVa)),
api_enums::PaymentMethodType::BriVa => Ok(dirval!(BankTransferType = BriVa)),
api_enums::PaymentMethodType::CimbVa => Ok(dirval!(BankTransferType = CimbVa)),
api_enums::PaymentMethodType::DanamonVa => Ok(dirval!(BankTransferType = DanamonVa)),
api_enums::PaymentMethodType::Indomaret => Ok(dirval!(VoucherType = Indomaret)),
api_enums::PaymentMethodType::MandiriVa => Ok(dirval!(BankTransferType = MandiriVa)),
api_enums::PaymentMethodType::LocalBankTransfer => {
Ok(dirval!(BankTransferType = LocalBankTransfer))
}
api_enums::PaymentMethodType::InstantBankTransfer => {
Ok(dirval!(BankTransferType = InstantBankTransfer))
}
api_enums::PaymentMethodType::SepaBankTransfer => {
Ok(dirval!(BankTransferType = SepaBankTransfer))
}
api_enums::PaymentMethodType::PermataBankTransfer => {
Ok(dirval!(BankTransferType = PermataBankTransfer))
}
api_enums::PaymentMethodType::PaySafeCard => Ok(dirval!(GiftCardType = PaySafeCard)),
api_enums::PaymentMethodType::SevenEleven => Ok(dirval!(VoucherType = SevenEleven)),
api_enums::PaymentMethodType::Lawson => Ok(dirval!(VoucherType = Lawson)),
api_enums::PaymentMethodType::MiniStop => Ok(dirval!(VoucherType = MiniStop)),
api_enums::PaymentMethodType::FamilyMart => Ok(dirval!(VoucherType = FamilyMart)),
api_enums::PaymentMethodType::Seicomart => Ok(dirval!(VoucherType = Seicomart)),
api_enums::PaymentMethodType::PayEasy => Ok(dirval!(VoucherType = PayEasy)),
api_enums::PaymentMethodType::Givex => Ok(dirval!(GiftCardType = Givex)),
api_enums::PaymentMethodType::Benefit => Ok(dirval!(CardRedirectType = Benefit)),
api_enums::PaymentMethodType::Knet => Ok(dirval!(CardRedirectType = Knet)),
api_enums::PaymentMethodType::OpenBankingUk => {
Ok(dirval!(BankRedirectType = OpenBankingUk))
}
api_enums::PaymentMethodType::MomoAtm => Ok(dirval!(CardRedirectType = MomoAtm)),
api_enums::PaymentMethodType::Oxxo => Ok(dirval!(VoucherType = Oxxo)),
api_enums::PaymentMethodType::CardRedirect => Ok(dirval!(CardRedirectType = CardRedirect)),
api_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)),
api_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)),
api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)),
api_enums::PaymentMethodType::Mifinity => Ok(dirval!(WalletType = Mifinity)),
api_enums::PaymentMethodType::Fps => Ok(dirval!(RealTimePaymentType = Fps)),
api_enums::PaymentMethodType::DuitNow => Ok(dirval!(RealTimePaymentType = DuitNow)),
api_enums::PaymentMethodType::PromptPay => Ok(dirval!(RealTimePaymentType = PromptPay)),
api_enums::PaymentMethodType::VietQr => Ok(dirval!(RealTimePaymentType = VietQr)),
api_enums::PaymentMethodType::OpenBankingPIS => {
Ok(dirval!(OpenBankingType = OpenBankingPIS))
}
api_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)),
api_enums::PaymentMethodType::DirectCarrierBilling => {
Ok(dirval!(MobilePaymentType = DirectCarrierBilling))
}
}
}
#[cfg(feature = "v2")]
fn compile_request_pm_types(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
pm_types: common_types::payment_methods::RequestPaymentMethodTypes,
pm: api_enums::PaymentMethod,
) -> Result<cgraph::NodeId, KgraphError> {
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
let pmt_info = "PaymentMethodType";
let pmt_id = builder.make_value_node(
(pm_types.payment_method_subtype, pm)
.into_dir_value()
.map(Into::into)?,
Some(pmt_info),
None::<()>,
);
agg_nodes.push((
pmt_id,
cgraph::Relation::Positive,
match pm_types.payment_method_subtype {
api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => {
cgraph::Strength::Weak
}
_ => cgraph::Strength::Strong,
},
));
if let Some(card_networks) = pm_types.card_networks {
if !card_networks.is_empty() {
let dir_vals: Vec<dir::DirValue> = card_networks
.into_iter()
.map(IntoDirValue::into_dir_value)
.collect::<Result<_, _>>()?;
let card_network_info = "Card Networks";
let card_network_id = builder
.make_in_aggregator(dir_vals, Some(card_network_info), None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
card_network_id,
cgraph::Relation::Positive,
cgraph::Strength::Weak,
));
}
}
let currencies_data = pm_types
.accepted_currencies
.and_then(|accepted_currencies| match accepted_currencies {
common_types::payment_methods::AcceptedCurrencies::EnableOnly(curr)
if !curr.is_empty() =>
{
Some((
curr.into_iter()
.map(IntoDirValue::into_dir_value)
.collect::<Result<_, _>>()
.ok()?,
cgraph::Relation::Positive,
))
}
common_types::payment_methods::AcceptedCurrencies::DisableOnly(curr)
if !curr.is_empty() =>
{
Some((
curr.into_iter()
.map(IntoDirValue::into_dir_value)
.collect::<Result<_, _>>()
.ok()?,
cgraph::Relation::Negative,
))
}
_ => None,
});
if let Some((currencies, relation)) = currencies_data {
let accepted_currencies_info = "Accepted Currencies";
let accepted_currencies_id = builder
.make_in_aggregator(currencies, Some(accepted_currencies_info), None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((accepted_currencies_id, relation, cgraph::Strength::Strong));
}
let mut amount_nodes = Vec::with_capacity(2);
if let Some(min_amt) = pm_types.minimum_amount {
let num_val = NumValue {
number: min_amt,
refinement: Some(NumValueRefinement::GreaterThanEqual),
};
let min_amt_info = "Minimum Amount";
let min_amt_id = builder.make_value_node(
dir::DirValue::PaymentAmount(num_val).into(),
Some(min_amt_info),
None::<()>,
);
amount_nodes.push(min_amt_id);
}
if let Some(max_amt) = pm_types.maximum_amount {
let num_val = NumValue {
number: max_amt,
refinement: Some(NumValueRefinement::LessThanEqual),
};
let max_amt_info = "Maximum Amount";
let max_amt_id = builder.make_value_node(
dir::DirValue::PaymentAmount(num_val).into(),
Some(max_amt_info),
None::<()>,
);
amount_nodes.push(max_amt_id);
}
if !amount_nodes.is_empty() {
let zero_num_val = NumValue {
number: MinorUnit::zero(),
refinement: None,
};
let zero_amt_id = builder.make_value_node(
dir::DirValue::PaymentAmount(zero_num_val).into(),
Some("zero_amount"),
None::<()>,
);
let or_node_neighbor_id = if amount_nodes.len() == 1 {
amount_nodes
.first()
.copied()
.ok_or(KgraphError::IndexingError)?
} else {
let nodes = amount_nodes
.iter()
.copied()
.map(|node_id| {
(
node_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
)
})
.collect::<Vec<_>>();
builder
.make_all_aggregator(
&nodes,
Some("amount_constraint_aggregator"),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?
};
let any_aggregator = builder
.make_any_aggregator(
&[
(
zero_amt_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
(
or_node_neighbor_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
],
Some("zero_plus_limits_amount_aggregator"),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
any_aggregator,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
));
}
let pmt_all_aggregator_info = "All Aggregator for PaymentMethodType";
builder
.make_all_aggregator(&agg_nodes, Some(pmt_all_aggregator_info), None::<()>, None)
.map_err(KgraphError::GraphConstructionError)
}
#[cfg(feature = "v1")]
fn compile_request_pm_types(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
pm_types: RequestPaymentMethodTypes,
pm: api_enums::PaymentMethod,
) -> Result<cgraph::NodeId, KgraphError> {
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
let pmt_info = "PaymentMethodType";
let pmt_id = builder.make_value_node(
(pm_types.payment_method_type, pm)
.into_dir_value()
.map(Into::into)?,
Some(pmt_info),
None::<()>,
);
agg_nodes.push((
pmt_id,
cgraph::Relation::Positive,
match pm_types.payment_method_type {
api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => {
cgraph::Strength::Weak
}
_ => cgraph::Strength::Strong,
},
));
if let Some(card_networks) = pm_types.card_networks {
if !card_networks.is_empty() {
let dir_vals: Vec<dir::DirValue> = card_networks
.into_iter()
.map(IntoDirValue::into_dir_value)
.collect::<Result<_, _>>()?;
let card_network_info = "Card Networks";
let card_network_id = builder
.make_in_aggregator(dir_vals, Some(card_network_info), None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
card_network_id,
cgraph::Relation::Positive,
cgraph::Strength::Weak,
));
}
}
let currencies_data = pm_types
.accepted_currencies
.and_then(|accepted_currencies| match accepted_currencies {
admin_api::AcceptedCurrencies::EnableOnly(curr) if !curr.is_empty() => Some((
curr.into_iter()
.map(IntoDirValue::into_dir_value)
.collect::<Result<_, _>>()
.ok()?,
cgraph::Relation::Positive,
)),
admin_api::AcceptedCurrencies::DisableOnly(curr) if !curr.is_empty() => Some((
curr.into_iter()
.map(IntoDirValue::into_dir_value)
.collect::<Result<_, _>>()
.ok()?,
cgraph::Relation::Negative,
)),
_ => None,
});
if let Some((currencies, relation)) = currencies_data {
let accepted_currencies_info = "Accepted Currencies";
let accepted_currencies_id = builder
.make_in_aggregator(currencies, Some(accepted_currencies_info), None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((accepted_currencies_id, relation, cgraph::Strength::Strong));
}
let mut amount_nodes = Vec::with_capacity(2);
if let Some(min_amt) = pm_types.minimum_amount {
let num_val = NumValue {
number: min_amt,
refinement: Some(NumValueRefinement::GreaterThanEqual),
};
let min_amt_info = "Minimum Amount";
let min_amt_id = builder.make_value_node(
dir::DirValue::PaymentAmount(num_val).into(),
Some(min_amt_info),
None::<()>,
);
amount_nodes.push(min_amt_id);
}
if let Some(max_amt) = pm_types.maximum_amount {
let num_val = NumValue {
number: max_amt,
refinement: Some(NumValueRefinement::LessThanEqual),
};
let max_amt_info = "Maximum Amount";
let max_amt_id = builder.make_value_node(
dir::DirValue::PaymentAmount(num_val).into(),
Some(max_amt_info),
None::<()>,
);
amount_nodes.push(max_amt_id);
}
if !amount_nodes.is_empty() {
let zero_num_val = NumValue {
number: MinorUnit::zero(),
refinement: None,
};
let zero_amt_id = builder.make_value_node(
dir::DirValue::PaymentAmount(zero_num_val).into(),
Some("zero_amount"),
None::<()>,
);
let or_node_neighbor_id = if amount_nodes.len() == 1 {
amount_nodes
.first()
.copied()
.ok_or(KgraphError::IndexingError)?
} else {
let nodes = amount_nodes
.iter()
.copied()
.map(|node_id| {
(
node_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
)
})
.collect::<Vec<_>>();
builder
.make_all_aggregator(
&nodes,
Some("amount_constraint_aggregator"),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?
};
let any_aggregator = builder
.make_any_aggregator(
&[
(
zero_amt_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
(
or_node_neighbor_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
],
Some("zero_plus_limits_amount_aggregator"),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
any_aggregator,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
));
}
let pmt_all_aggregator_info = "All Aggregator for PaymentMethodType";
builder
.make_all_aggregator(&agg_nodes, Some(pmt_all_aggregator_info), None::<()>, None)
.map_err(KgraphError::GraphConstructionError)
}
#[cfg(feature = "v2")]
fn compile_payment_method_enabled(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
enabled: common_types::payment_methods::PaymentMethodsEnabled,
) -> Result<Option<cgraph::NodeId>, KgraphError> {
let agg_id = if !enabled
.payment_method_subtypes
.as_ref()
.map(|v| v.is_empty())
.unwrap_or(true)
{
let pm_info = "PaymentMethod";
let pm_id = builder.make_value_node(
enabled
.payment_method_type
.into_dir_value()
.map(Into::into)?,
Some(pm_info),
None::<()>,
);
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
if let Some(pm_types) = enabled.payment_method_subtypes {
for pm_type in pm_types {
let node_id =
compile_request_pm_types(builder, pm_type, enabled.payment_method_type)?;
agg_nodes.push((
node_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
));
}
}
let any_aggregator_info = "Any aggregation for PaymentMethodsType";
let pm_type_agg_id = builder
.make_any_aggregator(&agg_nodes, Some(any_aggregator_info), None::<()>, None)
.map_err(KgraphError::GraphConstructionError)?;
let all_aggregator_info = "All aggregation for PaymentMethod";
let enabled_pm_agg_id = builder
.make_all_aggregator(
&[
(pm_id, cgraph::Relation::Positive, cgraph::Strength::Strong),
(
pm_type_agg_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
],
Some(all_aggregator_info),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?;
Some(enabled_pm_agg_id)
} else {
None
};
Ok(agg_id)
}
#[cfg(feature = "v1")]
fn compile_payment_method_enabled(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
enabled: admin_api::PaymentMethodsEnabled,
) -> Result<Option<cgraph::NodeId>, KgraphError> {
let agg_id = if !enabled
.payment_method_types
.as_ref()
.map(|v| v.is_empty())
.unwrap_or(true)
{
let pm_info = "PaymentMethod";
let pm_id = builder.make_value_node(
enabled.payment_method.into_dir_value().map(Into::into)?,
Some(pm_info),
None::<()>,
);
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
if let Some(pm_types) = enabled.payment_method_types {
for pm_type in pm_types {
let node_id = compile_request_pm_types(builder, pm_type, enabled.payment_method)?;
agg_nodes.push((
node_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
));
}
}
let any_aggregator_info = "Any aggregation for PaymentMethodsType";
let pm_type_agg_id = builder
.make_any_aggregator(&agg_nodes, Some(any_aggregator_info), None::<()>, None)
.map_err(KgraphError::GraphConstructionError)?;
let all_aggregator_info = "All aggregation for PaymentMethod";
let enabled_pm_agg_id = builder
.make_all_aggregator(
&[
(pm_id, cgraph::Relation::Positive, cgraph::Strength::Strong),
(
pm_type_agg_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
],
Some(all_aggregator_info),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?;
Some(enabled_pm_agg_id)
} else {
None
};
Ok(agg_id)
}
macro_rules! collect_global_variants {
($parent_enum:ident) => {
&mut dir::enums::$parent_enum::iter()
.map(dir::DirValue::$parent_enum)
.collect::<Vec<_>>()
};
}
// #[cfg(feature = "v1")]
fn global_vec_pmt(
enabled_pmt: Vec<dir::DirValue>,
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
) -> Vec<cgraph::NodeId> {
let mut global_vector: Vec<dir::DirValue> = Vec::new();
global_vector.append(collect_global_variants!(PayLaterType));
global_vector.append(collect_global_variants!(WalletType));
global_vector.append(collect_global_variants!(BankRedirectType));
global_vector.append(collect_global_variants!(BankDebitType));
global_vector.append(collect_global_variants!(CryptoType));
global_vector.append(collect_global_variants!(RewardType));
global_vector.append(collect_global_variants!(RealTimePaymentType));
global_vector.append(collect_global_variants!(UpiType));
global_vector.append(collect_global_variants!(VoucherType));
global_vector.append(collect_global_variants!(GiftCardType));
global_vector.append(collect_global_variants!(BankTransferType));
global_vector.append(collect_global_variants!(CardRedirectType));
global_vector.append(collect_global_variants!(OpenBankingType));
global_vector.append(collect_global_variants!(MobilePaymentType));
global_vector.push(dir::DirValue::PaymentMethod(
dir::enums::PaymentMethod::Card,
));
let global_vector = global_vector
.into_iter()
.filter(|global_value| !enabled_pmt.contains(global_value))
.collect::<Vec<_>>();
global_vector
.into_iter()
.map(|dir_v| {
builder.make_value_node(
cgraph::NodeValue::Value(dir_v),
Some("Payment Method Type"),
None::<()>,
)
})
.collect::<Vec<_>>()
}
fn compile_graph_for_countries_and_currencies(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
config: &kgraph_types::CurrencyCountryFlowFilter,
payment_method_type_node: cgraph::NodeId,
) -> Result<cgraph::NodeId, KgraphError> {
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
agg_nodes.push((
payment_method_type_node,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
));
if let Some(country) = config.country.clone() {
let node_country = country
.into_iter()
.map(|country| dir::DirValue::BillingCountry(api_enums::Country::from_alpha2(country)))
.collect();
let country_agg = builder
.make_in_aggregator(node_country, Some("Configs for Country"), None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
country_agg,
cgraph::Relation::Positive,
cgraph::Strength::Weak,
))
}
if let Some(currency) = config.currency.clone() {
let node_currency = currency
.into_iter()
.map(IntoDirValue::into_dir_value)
.collect::<Result<Vec<_>, _>>()?;
let currency_agg = builder
.make_in_aggregator(node_currency, Some("Configs for Currency"), None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
currency_agg,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
))
}
if let Some(capture_method) = config
.not_available_flows
.and_then(|naf| naf.capture_method)
{
let make_capture_node = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::CaptureMethod(capture_method)),
Some("Configs for CaptureMethod"),
None::<()>,
);
agg_nodes.push((
make_capture_node,
cgraph::Relation::Negative,
cgraph::Strength::Normal,
))
}
builder
.make_all_aggregator(
&agg_nodes,
Some("Country & Currency Configs With Payment Method Type"),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)
}
// #[cfg(feature = "v1")]
fn compile_config_graph(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
config: &kgraph_types::CountryCurrencyFilter,
connector: api_enums::RoutableConnectors,
) -> Result<cgraph::NodeId, KgraphError> {
let mut agg_node_id: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
let mut pmt_enabled: Vec<dir::DirValue> = Vec::new();
if let Some(pmt) = config
.connector_configs
.get(&connector)
.or(config.default_configs.as_ref())
.map(|inner| inner.0.clone())
{
for pm_filter_key in pmt {
match pm_filter_key {
(kgraph_types::PaymentMethodFilterKey::PaymentMethodType(pm), filter) => {
let dir_val_pm = get_dir_value_payment_method(pm)?;
let pm_node = if pm == api_enums::PaymentMethodType::Credit
|| pm == api_enums::PaymentMethodType::Debit
{
pmt_enabled
.push(dir::DirValue::PaymentMethod(api_enums::PaymentMethod::Card));
builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(
dir::enums::PaymentMethod::Card,
)),
Some("PaymentMethod"),
None::<()>,
)
} else {
pmt_enabled.push(dir_val_pm.clone());
builder.make_value_node(
cgraph::NodeValue::Value(dir_val_pm),
Some("PaymentMethodType"),
None::<()>,
)
};
let node_config =
compile_graph_for_countries_and_currencies(builder, &filter, pm_node)?;
agg_node_id.push((
node_config,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
));
}
(kgraph_types::PaymentMethodFilterKey::CardNetwork(cn), filter) => {
let dir_val_cn = cn.clone().into_dir_value()?;
pmt_enabled.push(dir_val_cn);
let cn_node = builder.make_value_node(
cn.clone().into_dir_value().map(Into::into)?,
Some("CardNetwork"),
None::<()>,
);
let node_config =
compile_graph_for_countries_and_currencies(builder, &filter, cn_node)?;
agg_node_id.push((
node_config,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
));
}
}
}
}
let global_vector_pmt: Vec<cgraph::NodeId> = global_vec_pmt(pmt_enabled, builder);
let any_agg_pmt: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = global_vector_pmt
.into_iter()
.map(|node| (node, cgraph::Relation::Positive, cgraph::Strength::Normal))
.collect::<Vec<_>>();
let any_agg_node = builder
.make_any_aggregator(
&any_agg_pmt,
Some("Any Aggregator For Payment Method Types"),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?;
agg_node_id.push((
any_agg_node,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
));
builder
.make_any_aggregator(&agg_node_id, Some("Configs"), None::<()>, None)
.map_err(KgraphError::GraphConstructionError)
}
#[cfg(feature = "v2")]
fn compile_merchant_connector_graph(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
mca: admin_api::MerchantConnectorResponse,
config: &kgraph_types::CountryCurrencyFilter,
) -> Result<(), KgraphError> {
let connector = common_enums::RoutableConnectors::try_from(mca.connector_name)
.map_err(|_| KgraphError::InvalidConnectorName(mca.connector_name))?;
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
if let Some(pms_enabled) = mca.payment_methods_enabled.clone() {
for pm_enabled in pms_enabled {
let maybe_pm_enabled_id = compile_payment_method_enabled(builder, pm_enabled)?;
if let Some(pm_enabled_id) = maybe_pm_enabled_id {
agg_nodes.push((
pm_enabled_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
));
}
}
}
let aggregator_info = "Available Payment methods for connector";
let pms_enabled_agg_id = builder
.make_any_aggregator(&agg_nodes, Some(aggregator_info), None::<()>, None)
.map_err(KgraphError::GraphConstructionError)?;
let config_info = "Config for respective PaymentMethodType for the connector";
let config_enabled_agg_id = compile_config_graph(builder, config, connector)?;
let domain_level_node_id = builder
.make_all_aggregator(
&[
(
config_enabled_agg_id,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
),
(
pms_enabled_agg_id,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
),
],
Some(config_info),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?;
let connector_dir_val = dir::DirValue::Connector(Box::new(ast::ConnectorChoice { connector }));
let connector_info = "Connector";
let connector_node_id =
builder.make_value_node(connector_dir_val.into(), Some(connector_info), None::<()>);
builder
.make_edge(
domain_level_node_id,
connector_node_id,
cgraph::Strength::Normal,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.map_err(KgraphError::GraphConstructionError)?;
Ok(())
}
#[cfg(feature = "v1")]
fn compile_merchant_connector_graph(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
mca: admin_api::MerchantConnectorResponse,
config: &kgraph_types::CountryCurrencyFilter,
) -> Result<(), KgraphError> {
let connector = common_enums::RoutableConnectors::from_str(&mca.connector_name)
.map_err(|_| KgraphError::InvalidConnectorName(mca.connector_name.clone()))?;
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
if let Some(pms_enabled) = mca.payment_methods_enabled.clone() {
for pm_enabled in pms_enabled {
let maybe_pm_enabled_id = compile_payment_method_enabled(builder, pm_enabled)?;
if let Some(pm_enabled_id) = maybe_pm_enabled_id {
agg_nodes.push((
pm_enabled_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
));
}
}
}
let aggregator_info = "Available Payment methods for connector";
let pms_enabled_agg_id = builder
.make_any_aggregator(&agg_nodes, Some(aggregator_info), None::<()>, None)
.map_err(KgraphError::GraphConstructionError)?;
let config_info = "Config for respective PaymentMethodType for the connector";
let config_enabled_agg_id = compile_config_graph(builder, config, connector)?;
let domain_level_node_id = builder
.make_all_aggregator(
&[
(
config_enabled_agg_id,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
),
(
pms_enabled_agg_id,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
),
],
Some(config_info),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?;
let connector_dir_val = dir::DirValue::Connector(Box::new(ast::ConnectorChoice { connector }));
let connector_info = "Connector";
let connector_node_id =
builder.make_value_node(connector_dir_val.into(), Some(connector_info), None::<()>);
builder
.make_edge(
domain_level_node_id,
connector_node_id,
cgraph::Strength::Normal,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.map_err(KgraphError::GraphConstructionError)?;
Ok(())
}
// #[cfg(feature = "v1")]
pub fn make_mca_graph(
accts: Vec<admin_api::MerchantConnectorResponse>,
config: &kgraph_types::CountryCurrencyFilter,
) -> Result<cgraph::ConstraintGraph<dir::DirValue>, KgraphError> {
let mut builder = cgraph::ConstraintGraphBuilder::new();
let _domain = builder.make_domain(
DOMAIN_IDENTIFIER.to_string(),
"Payment methods enabled for MerchantConnectorAccount",
);
for acct in accts {
compile_merchant_connector_graph(&mut builder, acct, config)?;
}
Ok(builder.build())
}
#[cfg(feature = "v1")]
#[cfg(test)]
mod tests {
#![allow(clippy::expect_used)]
use std::collections::{HashMap, HashSet};
use api_models::enums as api_enums;
use euclid::{
dirval,
dssa::graph::{AnalysisContext, CgraphExt},
};
use hyperswitch_constraint_graph::{ConstraintGraph, CycleCheck, Memoization};
use super::*;
use crate::types as kgraph_types;
fn build_test_data() -> ConstraintGraph<dir::DirValue> {
use api_models::{admin::*, payment_methods::*};
let profile_id = common_utils::generate_profile_id_of_default_length();
// #[cfg(feature = "v2")]
// let stripe_account = MerchantConnectorResponse {
// connector_type: api_enums::ConnectorType::FizOperations,
// connector_name: "stripe".to_string(),
// id: common_utils::generate_merchant_connector_account_id_of_default_length(),
// connector_label: Some("something".to_string()),
// connector_account_details: masking::Secret::new(serde_json::json!({})),
// disabled: None,
// metadata: None,
// payment_methods_enabled: Some(vec![PaymentMethodsEnabled {
// payment_method: api_enums::PaymentMethod::Card,
// payment_method_types: Some(vec![
// RequestPaymentMethodTypes {
// payment_method_type: api_enums::PaymentMethodType::Credit,
// payment_experience: None,
// card_networks: Some(vec![
// api_enums::CardNetwork::Visa,
// api_enums::CardNetwork::Mastercard,
// ]),
// accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![
// api_enums::Currency::INR,
// ])),
// accepted_countries: None,
// minimum_amount: Some(MinorUnit::new(10)),
// maximum_amount: Some(MinorUnit::new(1000)),
// recurring_enabled: true,
// installment_payment_enabled: true,
// },
// RequestPaymentMethodTypes {
// payment_method_type: api_enums::PaymentMethodType::Debit,
// payment_experience: None,
// card_networks: Some(vec![
// api_enums::CardNetwork::Maestro,
// api_enums::CardNetwork::JCB,
// ]),
// accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![
// api_enums::Currency::GBP,
// ])),
// accepted_countries: None,
// minimum_amount: Some(MinorUnit::new(10)),
// maximum_amount: Some(MinorUnit::new(1000)),
// recurring_enabled: true,
// installment_payment_enabled: true,
// },
// ]),
// }]),
// frm_configs: None,
// connector_webhook_details: None,
// profile_id,
// applepay_verified_domains: None,
// pm_auth_config: None,
// status: api_enums::ConnectorStatus::Inactive,
// additional_merchant_data: None,
// connector_wallets_details: None,
// };
#[cfg(feature = "v1")]
let stripe_account = MerchantConnectorResponse {
connector_type: api_enums::ConnectorType::FizOperations,
connector_name: "stripe".to_string(),
merchant_connector_id:
common_utils::generate_merchant_connector_account_id_of_default_length(),
business_country: Some(api_enums::CountryAlpha2::US),
connector_label: Some("something".to_string()),
business_label: Some("food".to_string()),
business_sub_label: None,
connector_account_details: masking::Secret::new(serde_json::json!({})),
test_mode: None,
disabled: None,
metadata: None,
payment_methods_enabled: Some(vec![PaymentMethodsEnabled {
payment_method: api_enums::PaymentMethod::Card,
payment_method_types: Some(vec![
RequestPaymentMethodTypes {
payment_method_type: api_enums::PaymentMethodType::Credit,
payment_experience: None,
card_networks: Some(vec![
api_enums::CardNetwork::Visa,
api_enums::CardNetwork::Mastercard,
]),
accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![
api_enums::Currency::INR,
])),
accepted_countries: None,
minimum_amount: Some(MinorUnit::new(10)),
maximum_amount: Some(MinorUnit::new(1000)),
recurring_enabled: true,
installment_payment_enabled: true,
},
RequestPaymentMethodTypes {
payment_method_type: api_enums::PaymentMethodType::Debit,
payment_experience: None,
card_networks: Some(vec![
api_enums::CardNetwork::Maestro,
api_enums::CardNetwork::JCB,
]),
accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![
api_enums::Currency::GBP,
])),
accepted_countries: None,
minimum_amount: Some(MinorUnit::new(10)),
maximum_amount: Some(MinorUnit::new(1000)),
recurring_enabled: true,
installment_payment_enabled: true,
},
]),
}]),
frm_configs: None,
connector_webhook_details: None,
profile_id,
applepay_verified_domains: None,
pm_auth_config: None,
status: api_enums::ConnectorStatus::Inactive,
additional_merchant_data: None,
connector_wallets_details: None,
};
let config_map = kgraph_types::CountryCurrencyFilter {
connector_configs: HashMap::from([(
api_enums::RoutableConnectors::Stripe,
kgraph_types::PaymentMethodFilters(HashMap::from([
(
kgraph_types::PaymentMethodFilterKey::PaymentMethodType(
api_enums::PaymentMethodType::Credit,
),
kgraph_types::CurrencyCountryFlowFilter {
currency: Some(HashSet::from([
api_enums::Currency::INR,
api_enums::Currency::USD,
])),
country: Some(HashSet::from([api_enums::CountryAlpha2::IN])),
not_available_flows: Some(kgraph_types::NotAvailableFlows {
capture_method: Some(api_enums::CaptureMethod::Manual),
}),
},
),
(
kgraph_types::PaymentMethodFilterKey::PaymentMethodType(
api_enums::PaymentMethodType::Debit,
),
kgraph_types::CurrencyCountryFlowFilter {
currency: Some(HashSet::from([
api_enums::Currency::GBP,
api_enums::Currency::PHP,
])),
country: Some(HashSet::from([api_enums::CountryAlpha2::IN])),
not_available_flows: Some(kgraph_types::NotAvailableFlows {
capture_method: Some(api_enums::CaptureMethod::Manual),
}),
},
),
])),
)]),
default_configs: None,
};
make_mca_graph(vec![stripe_account], &config_map).expect("Failed graph construction")
}
#[test]
fn test_credit_card_success_case() {
let graph = build_test_data();
let result = graph.key_value_analysis(
dirval!(Connector = Stripe),
&AnalysisContext::from_dir_values([
dirval!(Connector = Stripe),
dirval!(PaymentMethod = Card),
dirval!(CardType = Credit),
dirval!(CardNetwork = Visa),
dirval!(PaymentCurrency = INR),
dirval!(PaymentAmount = 101),
]),
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_debit_card_success_case() {
let graph = build_test_data();
let result = graph.key_value_analysis(
dirval!(Connector = Stripe),
&AnalysisContext::from_dir_values([
dirval!(Connector = Stripe),
dirval!(PaymentMethod = Card),
dirval!(CardType = Debit),
dirval!(CardNetwork = Maestro),
dirval!(PaymentCurrency = GBP),
dirval!(PaymentAmount = 100),
]),
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_single_mismatch_failure_case() {
let graph = build_test_data();
let result = graph.key_value_analysis(
dirval!(Connector = Stripe),
&AnalysisContext::from_dir_values([
dirval!(Connector = Stripe),
dirval!(PaymentMethod = Card),
dirval!(CardType = Debit),
dirval!(CardNetwork = Maestro),
dirval!(PaymentCurrency = PHP),
dirval!(PaymentAmount = 100),
]),
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_amount_mismatch_failure_case() {
let graph = build_test_data();
let result = graph.key_value_analysis(
dirval!(Connector = Stripe),
&AnalysisContext::from_dir_values([
dirval!(Connector = Stripe),
dirval!(PaymentMethod = Card),
dirval!(CardType = Debit),
dirval!(CardNetwork = Visa),
dirval!(PaymentCurrency = GBP),
dirval!(PaymentAmount = 7),
]),
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_incomplete_data_failure_case() {
let graph = build_test_data();
let result = graph.key_value_analysis(
dirval!(Connector = Stripe),
&AnalysisContext::from_dir_values([
dirval!(Connector = Stripe),
dirval!(PaymentMethod = Card),
dirval!(CardType = Debit),
dirval!(PaymentCurrency = GBP),
dirval!(PaymentAmount = 7),
]),
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
//println!("{:#?}", result);
//println!("{}", serde_json::to_string_pretty(&result).expect("Hello"));
assert!(result.is_err());
}
#[test]
fn test_incomplete_data_failure_case2() {
let graph = build_test_data();
let result = graph.key_value_analysis(
dirval!(Connector = Stripe),
&AnalysisContext::from_dir_values([
dirval!(Connector = Stripe),
dirval!(CardType = Debit),
dirval!(CardNetwork = Visa),
dirval!(PaymentCurrency = GBP),
dirval!(PaymentAmount = 100),
]),
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
//println!("{:#?}", result);
//println!("{}", serde_json::to_string_pretty(&result).expect("Hello"));
assert!(result.is_err());
}
#[test]
fn test_sandbox_applepay_bug_usecase() {
let value = serde_json::json!([
{
"connector_type": "payment_processor",
"connector_name": "bluesnap",
"merchant_connector_id": "REDACTED",
"status": "inactive",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "REDACTED",
"key1": "REDACTED"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Mastercard",
"Visa",
"AmericanExpress",
"JCB",
"DinersClub",
"Discover",
"CartesBancaires",
"UnionPay"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Mastercard",
"Visa",
"Interac",
"AmericanExpress",
"JCB",
"DinersClub",
"Discover",
"CartesBancaires",
"UnionPay"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {},
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"frm_configs": null
},
{
"connector_type": "payment_processor",
"connector_name": "stripe",
"merchant_connector_id": "REDACTED",
"status": "inactive",
"connector_account_details": {
"auth_type": "HeaderKey",
"api_key": "REDACTED"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Mastercard",
"Visa",
"AmericanExpress",
"JCB",
"DinersClub",
"Discover",
"CartesBancaires",
"UnionPay"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Mastercard",
"Visa",
"Interac",
"AmericanExpress",
"JCB",
"DinersClub",
"Discover",
"CartesBancaires",
"UnionPay"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": []
}
],
"metadata": {},
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"frm_configs": null
}
]);
let data: Vec<admin_api::MerchantConnectorResponse> =
serde_json::from_value(value).expect("data");
let config = kgraph_types::CountryCurrencyFilter {
connector_configs: HashMap::new(),
default_configs: None,
};
let graph = make_mca_graph(data, &config).expect("graph");
let context = AnalysisContext::from_dir_values([
dirval!(Connector = Stripe),
dirval!(PaymentAmount = 212),
dirval!(PaymentCurrency = ILS),
dirval!(PaymentMethod = Wallet),
dirval!(WalletType = ApplePay),
]);
let result = graph.key_value_analysis(
dirval!(Connector = Stripe),
&context,
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok(), "stripe validation failed");
let result = graph.key_value_analysis(
dirval!(Connector = Bluesnap),
&context,
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
assert!(result.is_err(), "bluesnap validation failed");
}
}
| 12,742 | 2,299 |
hyperswitch | crates/kgraph_utils/src/transformers.rs | .rs | use api_models::enums as api_enums;
use euclid::{
backend::BackendInput,
dirval,
dssa::types::AnalysisErrorType,
frontend::{ast, dir},
types::{NumValue, StrValue},
};
use crate::error::KgraphError;
pub trait IntoContext {
fn into_context(self) -> Result<Vec<dir::DirValue>, KgraphError>;
}
impl IntoContext for BackendInput {
fn into_context(self) -> Result<Vec<dir::DirValue>, KgraphError> {
let mut ctx: Vec<dir::DirValue> = Vec::new();
ctx.push(dir::DirValue::PaymentAmount(NumValue {
number: self.payment.amount,
refinement: None,
}));
ctx.push(dir::DirValue::PaymentCurrency(self.payment.currency));
if let Some(auth_type) = self.payment.authentication_type {
ctx.push(dir::DirValue::AuthenticationType(auth_type));
}
if let Some(capture_method) = self.payment.capture_method {
ctx.push(dir::DirValue::CaptureMethod(capture_method));
}
if let Some(business_country) = self.payment.business_country {
ctx.push(dir::DirValue::BusinessCountry(business_country));
}
if let Some(business_label) = self.payment.business_label {
ctx.push(dir::DirValue::BusinessLabel(StrValue {
value: business_label,
}));
}
if let Some(billing_country) = self.payment.billing_country {
ctx.push(dir::DirValue::BillingCountry(billing_country));
}
if let Some(payment_method) = self.payment_method.payment_method {
ctx.push(dir::DirValue::PaymentMethod(payment_method));
}
if let (Some(pm_type), Some(payment_method)) = (
self.payment_method.payment_method_type,
self.payment_method.payment_method,
) {
ctx.push((pm_type, payment_method).into_dir_value()?)
}
if let Some(card_network) = self.payment_method.card_network {
ctx.push(dir::DirValue::CardNetwork(card_network));
}
if let Some(setup_future_usage) = self.payment.setup_future_usage {
ctx.push(dir::DirValue::SetupFutureUsage(setup_future_usage));
}
if let Some(mandate_acceptance_type) = self.mandate.mandate_acceptance_type {
ctx.push(dir::DirValue::MandateAcceptanceType(
mandate_acceptance_type,
));
}
if let Some(mandate_type) = self.mandate.mandate_type {
ctx.push(dir::DirValue::MandateType(mandate_type));
}
if let Some(payment_type) = self.mandate.payment_type {
ctx.push(dir::DirValue::PaymentType(payment_type));
}
Ok(ctx)
}
}
pub trait IntoDirValue {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError>;
}
impl IntoDirValue for ast::ConnectorChoice {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> {
Ok(dir::DirValue::Connector(Box::new(self)))
}
}
impl IntoDirValue for api_enums::PaymentMethod {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> {
match self {
Self::Card => Ok(dirval!(PaymentMethod = Card)),
Self::Wallet => Ok(dirval!(PaymentMethod = Wallet)),
Self::PayLater => Ok(dirval!(PaymentMethod = PayLater)),
Self::BankRedirect => Ok(dirval!(PaymentMethod = BankRedirect)),
Self::Crypto => Ok(dirval!(PaymentMethod = Crypto)),
Self::BankDebit => Ok(dirval!(PaymentMethod = BankDebit)),
Self::BankTransfer => Ok(dirval!(PaymentMethod = BankTransfer)),
Self::Reward => Ok(dirval!(PaymentMethod = Reward)),
Self::RealTimePayment => Ok(dirval!(PaymentMethod = RealTimePayment)),
Self::Upi => Ok(dirval!(PaymentMethod = Upi)),
Self::Voucher => Ok(dirval!(PaymentMethod = Voucher)),
Self::GiftCard => Ok(dirval!(PaymentMethod = GiftCard)),
Self::CardRedirect => Ok(dirval!(PaymentMethod = CardRedirect)),
Self::OpenBanking => Ok(dirval!(PaymentMethod = OpenBanking)),
Self::MobilePayment => Ok(dirval!(PaymentMethod = MobilePayment)),
}
}
}
impl IntoDirValue for api_enums::AuthenticationType {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> {
match self {
Self::ThreeDs => Ok(dirval!(AuthenticationType = ThreeDs)),
Self::NoThreeDs => Ok(dirval!(AuthenticationType = NoThreeDs)),
}
}
}
impl IntoDirValue for api_enums::FutureUsage {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> {
match self {
Self::OnSession => Ok(dirval!(SetupFutureUsage = OnSession)),
Self::OffSession => Ok(dirval!(SetupFutureUsage = OffSession)),
}
}
}
impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> {
match self.0 {
api_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)),
api_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)),
api_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)),
#[cfg(feature = "v2")]
api_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)),
api_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)),
api_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)),
api_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)),
api_enums::PaymentMethodType::Eft => Ok(dirval!(BankRedirectType = Eft)),
api_enums::PaymentMethodType::Eps => Ok(dirval!(BankRedirectType = Eps)),
api_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)),
api_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)),
api_enums::PaymentMethodType::AfterpayClearpay => {
Ok(dirval!(PayLaterType = AfterpayClearpay))
}
api_enums::PaymentMethodType::GooglePay => Ok(dirval!(WalletType = GooglePay)),
api_enums::PaymentMethodType::ApplePay => Ok(dirval!(WalletType = ApplePay)),
api_enums::PaymentMethodType::Paypal => Ok(dirval!(WalletType = Paypal)),
api_enums::PaymentMethodType::CryptoCurrency => {
Ok(dirval!(CryptoType = CryptoCurrency))
}
api_enums::PaymentMethodType::Ach => match self.1 {
api_enums::PaymentMethod::BankDebit => Ok(dirval!(BankDebitType = Ach)),
api_enums::PaymentMethod::BankTransfer => Ok(dirval!(BankTransferType = Ach)),
api_enums::PaymentMethod::BankRedirect
| api_enums::PaymentMethod::Card
| api_enums::PaymentMethod::CardRedirect
| api_enums::PaymentMethod::PayLater
| api_enums::PaymentMethod::Wallet
| api_enums::PaymentMethod::Crypto
| api_enums::PaymentMethod::Reward
| api_enums::PaymentMethod::RealTimePayment
| api_enums::PaymentMethod::Upi
| api_enums::PaymentMethod::MobilePayment
| api_enums::PaymentMethod::Voucher
| api_enums::PaymentMethod::OpenBanking
| api_enums::PaymentMethod::GiftCard => Err(KgraphError::ContextConstructionError(
AnalysisErrorType::NotSupported,
)),
},
api_enums::PaymentMethodType::Bacs => match self.1 {
api_enums::PaymentMethod::BankDebit => Ok(dirval!(BankDebitType = Bacs)),
api_enums::PaymentMethod::BankTransfer => Ok(dirval!(BankTransferType = Bacs)),
api_enums::PaymentMethod::BankRedirect
| api_enums::PaymentMethod::Card
| api_enums::PaymentMethod::CardRedirect
| api_enums::PaymentMethod::PayLater
| api_enums::PaymentMethod::Wallet
| api_enums::PaymentMethod::Crypto
| api_enums::PaymentMethod::Reward
| api_enums::PaymentMethod::RealTimePayment
| api_enums::PaymentMethod::Upi
| api_enums::PaymentMethod::MobilePayment
| api_enums::PaymentMethod::Voucher
| api_enums::PaymentMethod::OpenBanking
| api_enums::PaymentMethod::GiftCard => Err(KgraphError::ContextConstructionError(
AnalysisErrorType::NotSupported,
)),
},
api_enums::PaymentMethodType::Becs => Ok(dirval!(BankDebitType = Becs)),
api_enums::PaymentMethodType::Sepa => Ok(dirval!(BankDebitType = Sepa)),
api_enums::PaymentMethodType::SepaBankTransfer => {
Ok(dirval!(BankTransferType = SepaBankTransfer))
}
api_enums::PaymentMethodType::AliPay => Ok(dirval!(WalletType = AliPay)),
api_enums::PaymentMethodType::AliPayHk => Ok(dirval!(WalletType = AliPayHk)),
api_enums::PaymentMethodType::BancontactCard => {
Ok(dirval!(BankRedirectType = BancontactCard))
}
api_enums::PaymentMethodType::Blik => Ok(dirval!(BankRedirectType = Blik)),
api_enums::PaymentMethodType::MbWay => Ok(dirval!(WalletType = MbWay)),
api_enums::PaymentMethodType::MobilePay => Ok(dirval!(WalletType = MobilePay)),
api_enums::PaymentMethodType::Cashapp => Ok(dirval!(WalletType = Cashapp)),
api_enums::PaymentMethodType::Multibanco => Ok(dirval!(BankTransferType = Multibanco)),
api_enums::PaymentMethodType::Pix => Ok(dirval!(BankTransferType = Pix)),
api_enums::PaymentMethodType::Pse => Ok(dirval!(BankTransferType = Pse)),
api_enums::PaymentMethodType::Interac => Ok(dirval!(BankRedirectType = Interac)),
api_enums::PaymentMethodType::OnlineBankingCzechRepublic => {
Ok(dirval!(BankRedirectType = OnlineBankingCzechRepublic))
}
api_enums::PaymentMethodType::OnlineBankingFinland => {
Ok(dirval!(BankRedirectType = OnlineBankingFinland))
}
api_enums::PaymentMethodType::OnlineBankingPoland => {
Ok(dirval!(BankRedirectType = OnlineBankingPoland))
}
api_enums::PaymentMethodType::OnlineBankingSlovakia => {
Ok(dirval!(BankRedirectType = OnlineBankingSlovakia))
}
api_enums::PaymentMethodType::Swish => Ok(dirval!(WalletType = Swish)),
api_enums::PaymentMethodType::Trustly => Ok(dirval!(BankRedirectType = Trustly)),
api_enums::PaymentMethodType::Bizum => Ok(dirval!(BankRedirectType = Bizum)),
api_enums::PaymentMethodType::PayBright => Ok(dirval!(PayLaterType = PayBright)),
api_enums::PaymentMethodType::Walley => Ok(dirval!(PayLaterType = Walley)),
api_enums::PaymentMethodType::Przelewy24 => Ok(dirval!(BankRedirectType = Przelewy24)),
api_enums::PaymentMethodType::WeChatPay => Ok(dirval!(WalletType = WeChatPay)),
api_enums::PaymentMethodType::ClassicReward => Ok(dirval!(RewardType = ClassicReward)),
api_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)),
api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)),
api_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)),
api_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)),
api_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)),
api_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)),
api_enums::PaymentMethodType::Twint => Ok(dirval!(WalletType = Twint)),
api_enums::PaymentMethodType::Gcash => Ok(dirval!(WalletType = Gcash)),
api_enums::PaymentMethodType::Vipps => Ok(dirval!(WalletType = Vipps)),
api_enums::PaymentMethodType::Momo => Ok(dirval!(WalletType = Momo)),
api_enums::PaymentMethodType::Alma => Ok(dirval!(PayLaterType = Alma)),
api_enums::PaymentMethodType::Dana => Ok(dirval!(WalletType = Dana)),
api_enums::PaymentMethodType::OnlineBankingFpx => {
Ok(dirval!(BankRedirectType = OnlineBankingFpx))
}
api_enums::PaymentMethodType::LocalBankRedirect => {
Ok(dirval!(BankRedirectType = LocalBankRedirect))
}
api_enums::PaymentMethodType::OnlineBankingThailand => {
Ok(dirval!(BankRedirectType = OnlineBankingThailand))
}
api_enums::PaymentMethodType::TouchNGo => Ok(dirval!(WalletType = TouchNGo)),
api_enums::PaymentMethodType::Atome => Ok(dirval!(PayLaterType = Atome)),
api_enums::PaymentMethodType::Boleto => Ok(dirval!(VoucherType = Boleto)),
api_enums::PaymentMethodType::Efecty => Ok(dirval!(VoucherType = Efecty)),
api_enums::PaymentMethodType::PagoEfectivo => Ok(dirval!(VoucherType = PagoEfectivo)),
api_enums::PaymentMethodType::RedCompra => Ok(dirval!(VoucherType = RedCompra)),
api_enums::PaymentMethodType::RedPagos => Ok(dirval!(VoucherType = RedPagos)),
api_enums::PaymentMethodType::Alfamart => Ok(dirval!(VoucherType = Alfamart)),
api_enums::PaymentMethodType::BcaBankTransfer => {
Ok(dirval!(BankTransferType = BcaBankTransfer))
}
api_enums::PaymentMethodType::BniVa => Ok(dirval!(BankTransferType = BniVa)),
api_enums::PaymentMethodType::BriVa => Ok(dirval!(BankTransferType = BriVa)),
api_enums::PaymentMethodType::CimbVa => Ok(dirval!(BankTransferType = CimbVa)),
api_enums::PaymentMethodType::DanamonVa => Ok(dirval!(BankTransferType = DanamonVa)),
api_enums::PaymentMethodType::Indomaret => Ok(dirval!(VoucherType = Indomaret)),
api_enums::PaymentMethodType::MandiriVa => Ok(dirval!(BankTransferType = MandiriVa)),
api_enums::PaymentMethodType::LocalBankTransfer => {
Ok(dirval!(BankTransferType = LocalBankTransfer))
}
api_enums::PaymentMethodType::InstantBankTransfer => {
Ok(dirval!(BankTransferType = InstantBankTransfer))
}
api_enums::PaymentMethodType::PermataBankTransfer => {
Ok(dirval!(BankTransferType = PermataBankTransfer))
}
api_enums::PaymentMethodType::PaySafeCard => Ok(dirval!(GiftCardType = PaySafeCard)),
api_enums::PaymentMethodType::SevenEleven => Ok(dirval!(VoucherType = SevenEleven)),
api_enums::PaymentMethodType::Lawson => Ok(dirval!(VoucherType = Lawson)),
api_enums::PaymentMethodType::MiniStop => Ok(dirval!(VoucherType = MiniStop)),
api_enums::PaymentMethodType::FamilyMart => Ok(dirval!(VoucherType = FamilyMart)),
api_enums::PaymentMethodType::Seicomart => Ok(dirval!(VoucherType = Seicomart)),
api_enums::PaymentMethodType::PayEasy => Ok(dirval!(VoucherType = PayEasy)),
api_enums::PaymentMethodType::Givex => Ok(dirval!(GiftCardType = Givex)),
api_enums::PaymentMethodType::Benefit => Ok(dirval!(CardRedirectType = Benefit)),
api_enums::PaymentMethodType::Knet => Ok(dirval!(CardRedirectType = Knet)),
api_enums::PaymentMethodType::OpenBankingUk => {
Ok(dirval!(BankRedirectType = OpenBankingUk))
}
api_enums::PaymentMethodType::MomoAtm => Ok(dirval!(CardRedirectType = MomoAtm)),
api_enums::PaymentMethodType::Oxxo => Ok(dirval!(VoucherType = Oxxo)),
api_enums::PaymentMethodType::CardRedirect => {
Ok(dirval!(CardRedirectType = CardRedirect))
}
api_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)),
api_enums::PaymentMethodType::Mifinity => Ok(dirval!(WalletType = Mifinity)),
api_enums::PaymentMethodType::Fps => Ok(dirval!(RealTimePaymentType = Fps)),
api_enums::PaymentMethodType::DuitNow => Ok(dirval!(RealTimePaymentType = DuitNow)),
api_enums::PaymentMethodType::PromptPay => Ok(dirval!(RealTimePaymentType = PromptPay)),
api_enums::PaymentMethodType::VietQr => Ok(dirval!(RealTimePaymentType = VietQr)),
api_enums::PaymentMethodType::OpenBankingPIS => {
Ok(dirval!(OpenBankingType = OpenBankingPIS))
}
api_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)),
api_enums::PaymentMethodType::DirectCarrierBilling => {
Ok(dirval!(MobilePaymentType = DirectCarrierBilling))
}
}
}
}
impl IntoDirValue for api_enums::CardNetwork {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> {
match self {
Self::Visa => Ok(dirval!(CardNetwork = Visa)),
Self::Mastercard => Ok(dirval!(CardNetwork = Mastercard)),
Self::AmericanExpress => Ok(dirval!(CardNetwork = AmericanExpress)),
Self::JCB => Ok(dirval!(CardNetwork = JCB)),
Self::DinersClub => Ok(dirval!(CardNetwork = DinersClub)),
Self::Discover => Ok(dirval!(CardNetwork = Discover)),
Self::CartesBancaires => Ok(dirval!(CardNetwork = CartesBancaires)),
Self::UnionPay => Ok(dirval!(CardNetwork = UnionPay)),
Self::Interac => Ok(dirval!(CardNetwork = Interac)),
Self::RuPay => Ok(dirval!(CardNetwork = RuPay)),
Self::Maestro => Ok(dirval!(CardNetwork = Maestro)),
}
}
}
impl IntoDirValue for api_enums::Currency {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> {
match self {
Self::AED => Ok(dirval!(PaymentCurrency = AED)),
Self::AFN => Ok(dirval!(PaymentCurrency = AFN)),
Self::ALL => Ok(dirval!(PaymentCurrency = ALL)),
Self::AMD => Ok(dirval!(PaymentCurrency = AMD)),
Self::ANG => Ok(dirval!(PaymentCurrency = ANG)),
Self::AOA => Ok(dirval!(PaymentCurrency = AOA)),
Self::ARS => Ok(dirval!(PaymentCurrency = ARS)),
Self::AUD => Ok(dirval!(PaymentCurrency = AUD)),
Self::AWG => Ok(dirval!(PaymentCurrency = AWG)),
Self::AZN => Ok(dirval!(PaymentCurrency = AZN)),
Self::BAM => Ok(dirval!(PaymentCurrency = BAM)),
Self::BBD => Ok(dirval!(PaymentCurrency = BBD)),
Self::BDT => Ok(dirval!(PaymentCurrency = BDT)),
Self::BGN => Ok(dirval!(PaymentCurrency = BGN)),
Self::BHD => Ok(dirval!(PaymentCurrency = BHD)),
Self::BIF => Ok(dirval!(PaymentCurrency = BIF)),
Self::BMD => Ok(dirval!(PaymentCurrency = BMD)),
Self::BND => Ok(dirval!(PaymentCurrency = BND)),
Self::BOB => Ok(dirval!(PaymentCurrency = BOB)),
Self::BRL => Ok(dirval!(PaymentCurrency = BRL)),
Self::BSD => Ok(dirval!(PaymentCurrency = BSD)),
Self::BTN => Ok(dirval!(PaymentCurrency = BTN)),
Self::BWP => Ok(dirval!(PaymentCurrency = BWP)),
Self::BYN => Ok(dirval!(PaymentCurrency = BYN)),
Self::BZD => Ok(dirval!(PaymentCurrency = BZD)),
Self::CAD => Ok(dirval!(PaymentCurrency = CAD)),
Self::CDF => Ok(dirval!(PaymentCurrency = CDF)),
Self::CHF => Ok(dirval!(PaymentCurrency = CHF)),
Self::CLF => Ok(dirval!(PaymentCurrency = CLF)),
Self::CLP => Ok(dirval!(PaymentCurrency = CLP)),
Self::CNY => Ok(dirval!(PaymentCurrency = CNY)),
Self::COP => Ok(dirval!(PaymentCurrency = COP)),
Self::CRC => Ok(dirval!(PaymentCurrency = CRC)),
Self::CUC => Ok(dirval!(PaymentCurrency = CUC)),
Self::CUP => Ok(dirval!(PaymentCurrency = CUP)),
Self::CVE => Ok(dirval!(PaymentCurrency = CVE)),
Self::CZK => Ok(dirval!(PaymentCurrency = CZK)),
Self::DJF => Ok(dirval!(PaymentCurrency = DJF)),
Self::DKK => Ok(dirval!(PaymentCurrency = DKK)),
Self::DOP => Ok(dirval!(PaymentCurrency = DOP)),
Self::DZD => Ok(dirval!(PaymentCurrency = DZD)),
Self::EGP => Ok(dirval!(PaymentCurrency = EGP)),
Self::ERN => Ok(dirval!(PaymentCurrency = ERN)),
Self::ETB => Ok(dirval!(PaymentCurrency = ETB)),
Self::EUR => Ok(dirval!(PaymentCurrency = EUR)),
Self::FJD => Ok(dirval!(PaymentCurrency = FJD)),
Self::FKP => Ok(dirval!(PaymentCurrency = FKP)),
Self::GBP => Ok(dirval!(PaymentCurrency = GBP)),
Self::GEL => Ok(dirval!(PaymentCurrency = GEL)),
Self::GHS => Ok(dirval!(PaymentCurrency = GHS)),
Self::GIP => Ok(dirval!(PaymentCurrency = GIP)),
Self::GMD => Ok(dirval!(PaymentCurrency = GMD)),
Self::GNF => Ok(dirval!(PaymentCurrency = GNF)),
Self::GTQ => Ok(dirval!(PaymentCurrency = GTQ)),
Self::GYD => Ok(dirval!(PaymentCurrency = GYD)),
Self::HKD => Ok(dirval!(PaymentCurrency = HKD)),
Self::HNL => Ok(dirval!(PaymentCurrency = HNL)),
Self::HRK => Ok(dirval!(PaymentCurrency = HRK)),
Self::HTG => Ok(dirval!(PaymentCurrency = HTG)),
Self::HUF => Ok(dirval!(PaymentCurrency = HUF)),
Self::IDR => Ok(dirval!(PaymentCurrency = IDR)),
Self::ILS => Ok(dirval!(PaymentCurrency = ILS)),
Self::INR => Ok(dirval!(PaymentCurrency = INR)),
Self::IQD => Ok(dirval!(PaymentCurrency = IQD)),
Self::IRR => Ok(dirval!(PaymentCurrency = IRR)),
Self::ISK => Ok(dirval!(PaymentCurrency = ISK)),
Self::JMD => Ok(dirval!(PaymentCurrency = JMD)),
Self::JOD => Ok(dirval!(PaymentCurrency = JOD)),
Self::JPY => Ok(dirval!(PaymentCurrency = JPY)),
Self::KES => Ok(dirval!(PaymentCurrency = KES)),
Self::KGS => Ok(dirval!(PaymentCurrency = KGS)),
Self::KHR => Ok(dirval!(PaymentCurrency = KHR)),
Self::KMF => Ok(dirval!(PaymentCurrency = KMF)),
Self::KPW => Ok(dirval!(PaymentCurrency = KPW)),
Self::KRW => Ok(dirval!(PaymentCurrency = KRW)),
Self::KWD => Ok(dirval!(PaymentCurrency = KWD)),
Self::KYD => Ok(dirval!(PaymentCurrency = KYD)),
Self::KZT => Ok(dirval!(PaymentCurrency = KZT)),
Self::LAK => Ok(dirval!(PaymentCurrency = LAK)),
Self::LBP => Ok(dirval!(PaymentCurrency = LBP)),
Self::LKR => Ok(dirval!(PaymentCurrency = LKR)),
Self::LRD => Ok(dirval!(PaymentCurrency = LRD)),
Self::LSL => Ok(dirval!(PaymentCurrency = LSL)),
Self::LYD => Ok(dirval!(PaymentCurrency = LYD)),
Self::MAD => Ok(dirval!(PaymentCurrency = MAD)),
Self::MDL => Ok(dirval!(PaymentCurrency = MDL)),
Self::MGA => Ok(dirval!(PaymentCurrency = MGA)),
Self::MKD => Ok(dirval!(PaymentCurrency = MKD)),
Self::MMK => Ok(dirval!(PaymentCurrency = MMK)),
Self::MNT => Ok(dirval!(PaymentCurrency = MNT)),
Self::MOP => Ok(dirval!(PaymentCurrency = MOP)),
Self::MRU => Ok(dirval!(PaymentCurrency = MRU)),
Self::MUR => Ok(dirval!(PaymentCurrency = MUR)),
Self::MVR => Ok(dirval!(PaymentCurrency = MVR)),
Self::MWK => Ok(dirval!(PaymentCurrency = MWK)),
Self::MXN => Ok(dirval!(PaymentCurrency = MXN)),
Self::MYR => Ok(dirval!(PaymentCurrency = MYR)),
Self::MZN => Ok(dirval!(PaymentCurrency = MZN)),
Self::NAD => Ok(dirval!(PaymentCurrency = NAD)),
Self::NGN => Ok(dirval!(PaymentCurrency = NGN)),
Self::NIO => Ok(dirval!(PaymentCurrency = NIO)),
Self::NOK => Ok(dirval!(PaymentCurrency = NOK)),
Self::NPR => Ok(dirval!(PaymentCurrency = NPR)),
Self::NZD => Ok(dirval!(PaymentCurrency = NZD)),
Self::OMR => Ok(dirval!(PaymentCurrency = OMR)),
Self::PAB => Ok(dirval!(PaymentCurrency = PAB)),
Self::PEN => Ok(dirval!(PaymentCurrency = PEN)),
Self::PGK => Ok(dirval!(PaymentCurrency = PGK)),
Self::PHP => Ok(dirval!(PaymentCurrency = PHP)),
Self::PKR => Ok(dirval!(PaymentCurrency = PKR)),
Self::PLN => Ok(dirval!(PaymentCurrency = PLN)),
Self::PYG => Ok(dirval!(PaymentCurrency = PYG)),
Self::QAR => Ok(dirval!(PaymentCurrency = QAR)),
Self::RON => Ok(dirval!(PaymentCurrency = RON)),
Self::RSD => Ok(dirval!(PaymentCurrency = RSD)),
Self::RUB => Ok(dirval!(PaymentCurrency = RUB)),
Self::RWF => Ok(dirval!(PaymentCurrency = RWF)),
Self::SAR => Ok(dirval!(PaymentCurrency = SAR)),
Self::SBD => Ok(dirval!(PaymentCurrency = SBD)),
Self::SCR => Ok(dirval!(PaymentCurrency = SCR)),
Self::SDG => Ok(dirval!(PaymentCurrency = SDG)),
Self::SEK => Ok(dirval!(PaymentCurrency = SEK)),
Self::SGD => Ok(dirval!(PaymentCurrency = SGD)),
Self::SHP => Ok(dirval!(PaymentCurrency = SHP)),
Self::SLE => Ok(dirval!(PaymentCurrency = SLE)),
Self::SLL => Ok(dirval!(PaymentCurrency = SLL)),
Self::SOS => Ok(dirval!(PaymentCurrency = SOS)),
Self::SRD => Ok(dirval!(PaymentCurrency = SRD)),
Self::SSP => Ok(dirval!(PaymentCurrency = SSP)),
Self::STD => Ok(dirval!(PaymentCurrency = STD)),
Self::STN => Ok(dirval!(PaymentCurrency = STN)),
Self::SVC => Ok(dirval!(PaymentCurrency = SVC)),
Self::SYP => Ok(dirval!(PaymentCurrency = SYP)),
Self::SZL => Ok(dirval!(PaymentCurrency = SZL)),
Self::THB => Ok(dirval!(PaymentCurrency = THB)),
Self::TJS => Ok(dirval!(PaymentCurrency = TJS)),
Self::TMT => Ok(dirval!(PaymentCurrency = TMT)),
Self::TND => Ok(dirval!(PaymentCurrency = TND)),
Self::TOP => Ok(dirval!(PaymentCurrency = TOP)),
Self::TRY => Ok(dirval!(PaymentCurrency = TRY)),
Self::TTD => Ok(dirval!(PaymentCurrency = TTD)),
Self::TWD => Ok(dirval!(PaymentCurrency = TWD)),
Self::TZS => Ok(dirval!(PaymentCurrency = TZS)),
Self::UAH => Ok(dirval!(PaymentCurrency = UAH)),
Self::UGX => Ok(dirval!(PaymentCurrency = UGX)),
Self::USD => Ok(dirval!(PaymentCurrency = USD)),
Self::UYU => Ok(dirval!(PaymentCurrency = UYU)),
Self::UZS => Ok(dirval!(PaymentCurrency = UZS)),
Self::VES => Ok(dirval!(PaymentCurrency = VES)),
Self::VND => Ok(dirval!(PaymentCurrency = VND)),
Self::VUV => Ok(dirval!(PaymentCurrency = VUV)),
Self::WST => Ok(dirval!(PaymentCurrency = WST)),
Self::XAF => Ok(dirval!(PaymentCurrency = XAF)),
Self::XCD => Ok(dirval!(PaymentCurrency = XCD)),
Self::XOF => Ok(dirval!(PaymentCurrency = XOF)),
Self::XPF => Ok(dirval!(PaymentCurrency = XPF)),
Self::YER => Ok(dirval!(PaymentCurrency = YER)),
Self::ZAR => Ok(dirval!(PaymentCurrency = ZAR)),
Self::ZMW => Ok(dirval!(PaymentCurrency = ZMW)),
Self::ZWL => Ok(dirval!(PaymentCurrency = ZWL)),
}
}
}
pub fn get_dir_country_dir_value(c: api_enums::Country) -> dir::enums::Country {
match c {
api_enums::Country::Afghanistan => dir::enums::Country::Afghanistan,
api_enums::Country::AlandIslands => dir::enums::Country::AlandIslands,
api_enums::Country::Albania => dir::enums::Country::Albania,
api_enums::Country::Algeria => dir::enums::Country::Algeria,
api_enums::Country::AmericanSamoa => dir::enums::Country::AmericanSamoa,
api_enums::Country::Andorra => dir::enums::Country::Andorra,
api_enums::Country::Angola => dir::enums::Country::Angola,
api_enums::Country::Anguilla => dir::enums::Country::Anguilla,
api_enums::Country::Antarctica => dir::enums::Country::Antarctica,
api_enums::Country::AntiguaAndBarbuda => dir::enums::Country::AntiguaAndBarbuda,
api_enums::Country::Argentina => dir::enums::Country::Argentina,
api_enums::Country::Armenia => dir::enums::Country::Armenia,
api_enums::Country::Aruba => dir::enums::Country::Aruba,
api_enums::Country::Australia => dir::enums::Country::Australia,
api_enums::Country::Austria => dir::enums::Country::Austria,
api_enums::Country::Azerbaijan => dir::enums::Country::Azerbaijan,
api_enums::Country::Bahamas => dir::enums::Country::Bahamas,
api_enums::Country::Bahrain => dir::enums::Country::Bahrain,
api_enums::Country::Bangladesh => dir::enums::Country::Bangladesh,
api_enums::Country::Barbados => dir::enums::Country::Barbados,
api_enums::Country::Belarus => dir::enums::Country::Belarus,
api_enums::Country::Belgium => dir::enums::Country::Belgium,
api_enums::Country::Belize => dir::enums::Country::Belize,
api_enums::Country::Benin => dir::enums::Country::Benin,
api_enums::Country::Bermuda => dir::enums::Country::Bermuda,
api_enums::Country::Bhutan => dir::enums::Country::Bhutan,
api_enums::Country::BoliviaPlurinationalState => {
dir::enums::Country::BoliviaPlurinationalState
}
api_enums::Country::BonaireSintEustatiusAndSaba => {
dir::enums::Country::BonaireSintEustatiusAndSaba
}
api_enums::Country::BosniaAndHerzegovina => dir::enums::Country::BosniaAndHerzegovina,
api_enums::Country::Botswana => dir::enums::Country::Botswana,
api_enums::Country::BouvetIsland => dir::enums::Country::BouvetIsland,
api_enums::Country::Brazil => dir::enums::Country::Brazil,
api_enums::Country::BritishIndianOceanTerritory => {
dir::enums::Country::BritishIndianOceanTerritory
}
api_enums::Country::BruneiDarussalam => dir::enums::Country::BruneiDarussalam,
api_enums::Country::Bulgaria => dir::enums::Country::Bulgaria,
api_enums::Country::BurkinaFaso => dir::enums::Country::BurkinaFaso,
api_enums::Country::Burundi => dir::enums::Country::Burundi,
api_enums::Country::CaboVerde => dir::enums::Country::CaboVerde,
api_enums::Country::Cambodia => dir::enums::Country::Cambodia,
api_enums::Country::Cameroon => dir::enums::Country::Cameroon,
api_enums::Country::Canada => dir::enums::Country::Canada,
api_enums::Country::CaymanIslands => dir::enums::Country::CaymanIslands,
api_enums::Country::CentralAfricanRepublic => dir::enums::Country::CentralAfricanRepublic,
api_enums::Country::Chad => dir::enums::Country::Chad,
api_enums::Country::Chile => dir::enums::Country::Chile,
api_enums::Country::China => dir::enums::Country::China,
api_enums::Country::ChristmasIsland => dir::enums::Country::ChristmasIsland,
api_enums::Country::CocosKeelingIslands => dir::enums::Country::CocosKeelingIslands,
api_enums::Country::Colombia => dir::enums::Country::Colombia,
api_enums::Country::Comoros => dir::enums::Country::Comoros,
api_enums::Country::Congo => dir::enums::Country::Congo,
api_enums::Country::CongoDemocraticRepublic => dir::enums::Country::CongoDemocraticRepublic,
api_enums::Country::CookIslands => dir::enums::Country::CookIslands,
api_enums::Country::CostaRica => dir::enums::Country::CostaRica,
api_enums::Country::CotedIvoire => dir::enums::Country::CotedIvoire,
api_enums::Country::Croatia => dir::enums::Country::Croatia,
api_enums::Country::Cuba => dir::enums::Country::Cuba,
api_enums::Country::Curacao => dir::enums::Country::Curacao,
api_enums::Country::Cyprus => dir::enums::Country::Cyprus,
api_enums::Country::Czechia => dir::enums::Country::Czechia,
api_enums::Country::Denmark => dir::enums::Country::Denmark,
api_enums::Country::Djibouti => dir::enums::Country::Djibouti,
api_enums::Country::Dominica => dir::enums::Country::Dominica,
api_enums::Country::DominicanRepublic => dir::enums::Country::DominicanRepublic,
api_enums::Country::Ecuador => dir::enums::Country::Ecuador,
api_enums::Country::Egypt => dir::enums::Country::Egypt,
api_enums::Country::ElSalvador => dir::enums::Country::ElSalvador,
api_enums::Country::EquatorialGuinea => dir::enums::Country::EquatorialGuinea,
api_enums::Country::Eritrea => dir::enums::Country::Eritrea,
api_enums::Country::Estonia => dir::enums::Country::Estonia,
api_enums::Country::Ethiopia => dir::enums::Country::Ethiopia,
api_enums::Country::FalklandIslandsMalvinas => dir::enums::Country::FalklandIslandsMalvinas,
api_enums::Country::FaroeIslands => dir::enums::Country::FaroeIslands,
api_enums::Country::Fiji => dir::enums::Country::Fiji,
api_enums::Country::Finland => dir::enums::Country::Finland,
api_enums::Country::France => dir::enums::Country::France,
api_enums::Country::FrenchGuiana => dir::enums::Country::FrenchGuiana,
api_enums::Country::FrenchPolynesia => dir::enums::Country::FrenchPolynesia,
api_enums::Country::FrenchSouthernTerritories => {
dir::enums::Country::FrenchSouthernTerritories
}
api_enums::Country::Gabon => dir::enums::Country::Gabon,
api_enums::Country::Gambia => dir::enums::Country::Gambia,
api_enums::Country::Georgia => dir::enums::Country::Georgia,
api_enums::Country::Germany => dir::enums::Country::Germany,
api_enums::Country::Ghana => dir::enums::Country::Ghana,
api_enums::Country::Gibraltar => dir::enums::Country::Gibraltar,
api_enums::Country::Greece => dir::enums::Country::Greece,
api_enums::Country::Greenland => dir::enums::Country::Greenland,
api_enums::Country::Grenada => dir::enums::Country::Grenada,
api_enums::Country::Guadeloupe => dir::enums::Country::Guadeloupe,
api_enums::Country::Guam => dir::enums::Country::Guam,
api_enums::Country::Guatemala => dir::enums::Country::Guatemala,
api_enums::Country::Guernsey => dir::enums::Country::Guernsey,
api_enums::Country::Guinea => dir::enums::Country::Guinea,
api_enums::Country::GuineaBissau => dir::enums::Country::GuineaBissau,
api_enums::Country::Guyana => dir::enums::Country::Guyana,
api_enums::Country::Haiti => dir::enums::Country::Haiti,
api_enums::Country::HeardIslandAndMcDonaldIslands => {
dir::enums::Country::HeardIslandAndMcDonaldIslands
}
api_enums::Country::HolySee => dir::enums::Country::HolySee,
api_enums::Country::Honduras => dir::enums::Country::Honduras,
api_enums::Country::HongKong => dir::enums::Country::HongKong,
api_enums::Country::Hungary => dir::enums::Country::Hungary,
api_enums::Country::Iceland => dir::enums::Country::Iceland,
api_enums::Country::India => dir::enums::Country::India,
api_enums::Country::Indonesia => dir::enums::Country::Indonesia,
api_enums::Country::IranIslamicRepublic => dir::enums::Country::IranIslamicRepublic,
api_enums::Country::Iraq => dir::enums::Country::Iraq,
api_enums::Country::Ireland => dir::enums::Country::Ireland,
api_enums::Country::IsleOfMan => dir::enums::Country::IsleOfMan,
api_enums::Country::Israel => dir::enums::Country::Israel,
api_enums::Country::Italy => dir::enums::Country::Italy,
api_enums::Country::Jamaica => dir::enums::Country::Jamaica,
api_enums::Country::Japan => dir::enums::Country::Japan,
api_enums::Country::Jersey => dir::enums::Country::Jersey,
api_enums::Country::Jordan => dir::enums::Country::Jordan,
api_enums::Country::Kazakhstan => dir::enums::Country::Kazakhstan,
api_enums::Country::Kenya => dir::enums::Country::Kenya,
api_enums::Country::Kiribati => dir::enums::Country::Kiribati,
api_enums::Country::KoreaDemocraticPeoplesRepublic => {
dir::enums::Country::KoreaDemocraticPeoplesRepublic
}
api_enums::Country::KoreaRepublic => dir::enums::Country::KoreaRepublic,
api_enums::Country::Kuwait => dir::enums::Country::Kuwait,
api_enums::Country::Kyrgyzstan => dir::enums::Country::Kyrgyzstan,
api_enums::Country::LaoPeoplesDemocraticRepublic => {
dir::enums::Country::LaoPeoplesDemocraticRepublic
}
api_enums::Country::Latvia => dir::enums::Country::Latvia,
api_enums::Country::Lebanon => dir::enums::Country::Lebanon,
api_enums::Country::Lesotho => dir::enums::Country::Lesotho,
api_enums::Country::Liberia => dir::enums::Country::Liberia,
api_enums::Country::Libya => dir::enums::Country::Libya,
api_enums::Country::Liechtenstein => dir::enums::Country::Liechtenstein,
api_enums::Country::Lithuania => dir::enums::Country::Lithuania,
api_enums::Country::Luxembourg => dir::enums::Country::Luxembourg,
api_enums::Country::Macao => dir::enums::Country::Macao,
api_enums::Country::MacedoniaTheFormerYugoslavRepublic => {
dir::enums::Country::MacedoniaTheFormerYugoslavRepublic
}
api_enums::Country::Madagascar => dir::enums::Country::Madagascar,
api_enums::Country::Malawi => dir::enums::Country::Malawi,
api_enums::Country::Malaysia => dir::enums::Country::Malaysia,
api_enums::Country::Maldives => dir::enums::Country::Maldives,
api_enums::Country::Mali => dir::enums::Country::Mali,
api_enums::Country::Malta => dir::enums::Country::Malta,
api_enums::Country::MarshallIslands => dir::enums::Country::MarshallIslands,
api_enums::Country::Martinique => dir::enums::Country::Martinique,
api_enums::Country::Mauritania => dir::enums::Country::Mauritania,
api_enums::Country::Mauritius => dir::enums::Country::Mauritius,
api_enums::Country::Mayotte => dir::enums::Country::Mayotte,
api_enums::Country::Mexico => dir::enums::Country::Mexico,
api_enums::Country::MicronesiaFederatedStates => {
dir::enums::Country::MicronesiaFederatedStates
}
api_enums::Country::MoldovaRepublic => dir::enums::Country::MoldovaRepublic,
api_enums::Country::Monaco => dir::enums::Country::Monaco,
api_enums::Country::Mongolia => dir::enums::Country::Mongolia,
api_enums::Country::Montenegro => dir::enums::Country::Montenegro,
api_enums::Country::Montserrat => dir::enums::Country::Montserrat,
api_enums::Country::Morocco => dir::enums::Country::Morocco,
api_enums::Country::Mozambique => dir::enums::Country::Mozambique,
api_enums::Country::Myanmar => dir::enums::Country::Myanmar,
api_enums::Country::Namibia => dir::enums::Country::Namibia,
api_enums::Country::Nauru => dir::enums::Country::Nauru,
api_enums::Country::Nepal => dir::enums::Country::Nepal,
api_enums::Country::Netherlands => dir::enums::Country::Netherlands,
api_enums::Country::NewCaledonia => dir::enums::Country::NewCaledonia,
api_enums::Country::NewZealand => dir::enums::Country::NewZealand,
api_enums::Country::Nicaragua => dir::enums::Country::Nicaragua,
api_enums::Country::Niger => dir::enums::Country::Niger,
api_enums::Country::Nigeria => dir::enums::Country::Nigeria,
api_enums::Country::Niue => dir::enums::Country::Niue,
api_enums::Country::NorfolkIsland => dir::enums::Country::NorfolkIsland,
api_enums::Country::NorthernMarianaIslands => dir::enums::Country::NorthernMarianaIslands,
api_enums::Country::Norway => dir::enums::Country::Norway,
api_enums::Country::Oman => dir::enums::Country::Oman,
api_enums::Country::Pakistan => dir::enums::Country::Pakistan,
api_enums::Country::Palau => dir::enums::Country::Palau,
api_enums::Country::PalestineState => dir::enums::Country::PalestineState,
api_enums::Country::Panama => dir::enums::Country::Panama,
api_enums::Country::PapuaNewGuinea => dir::enums::Country::PapuaNewGuinea,
api_enums::Country::Paraguay => dir::enums::Country::Paraguay,
api_enums::Country::Peru => dir::enums::Country::Peru,
api_enums::Country::Philippines => dir::enums::Country::Philippines,
api_enums::Country::Pitcairn => dir::enums::Country::Pitcairn,
api_enums::Country::Poland => dir::enums::Country::Poland,
api_enums::Country::Portugal => dir::enums::Country::Portugal,
api_enums::Country::PuertoRico => dir::enums::Country::PuertoRico,
api_enums::Country::Qatar => dir::enums::Country::Qatar,
api_enums::Country::Reunion => dir::enums::Country::Reunion,
api_enums::Country::Romania => dir::enums::Country::Romania,
api_enums::Country::RussianFederation => dir::enums::Country::RussianFederation,
api_enums::Country::Rwanda => dir::enums::Country::Rwanda,
api_enums::Country::SaintBarthelemy => dir::enums::Country::SaintBarthelemy,
api_enums::Country::SaintHelenaAscensionAndTristandaCunha => {
dir::enums::Country::SaintHelenaAscensionAndTristandaCunha
}
api_enums::Country::SaintKittsAndNevis => dir::enums::Country::SaintKittsAndNevis,
api_enums::Country::SaintLucia => dir::enums::Country::SaintLucia,
api_enums::Country::SaintMartinFrenchpart => dir::enums::Country::SaintMartinFrenchpart,
api_enums::Country::SaintPierreAndMiquelon => dir::enums::Country::SaintPierreAndMiquelon,
api_enums::Country::SaintVincentAndTheGrenadines => {
dir::enums::Country::SaintVincentAndTheGrenadines
}
api_enums::Country::Samoa => dir::enums::Country::Samoa,
api_enums::Country::SanMarino => dir::enums::Country::SanMarino,
api_enums::Country::SaoTomeAndPrincipe => dir::enums::Country::SaoTomeAndPrincipe,
api_enums::Country::SaudiArabia => dir::enums::Country::SaudiArabia,
api_enums::Country::Senegal => dir::enums::Country::Senegal,
api_enums::Country::Serbia => dir::enums::Country::Serbia,
api_enums::Country::Seychelles => dir::enums::Country::Seychelles,
api_enums::Country::SierraLeone => dir::enums::Country::SierraLeone,
api_enums::Country::Singapore => dir::enums::Country::Singapore,
api_enums::Country::SintMaartenDutchpart => dir::enums::Country::SintMaartenDutchpart,
api_enums::Country::Slovakia => dir::enums::Country::Slovakia,
api_enums::Country::Slovenia => dir::enums::Country::Slovenia,
api_enums::Country::SolomonIslands => dir::enums::Country::SolomonIslands,
api_enums::Country::Somalia => dir::enums::Country::Somalia,
api_enums::Country::SouthAfrica => dir::enums::Country::SouthAfrica,
api_enums::Country::SouthGeorgiaAndTheSouthSandwichIslands => {
dir::enums::Country::SouthGeorgiaAndTheSouthSandwichIslands
}
api_enums::Country::SouthSudan => dir::enums::Country::SouthSudan,
api_enums::Country::Spain => dir::enums::Country::Spain,
api_enums::Country::SriLanka => dir::enums::Country::SriLanka,
api_enums::Country::Sudan => dir::enums::Country::Sudan,
api_enums::Country::Suriname => dir::enums::Country::Suriname,
api_enums::Country::SvalbardAndJanMayen => dir::enums::Country::SvalbardAndJanMayen,
api_enums::Country::Swaziland => dir::enums::Country::Swaziland,
api_enums::Country::Sweden => dir::enums::Country::Sweden,
api_enums::Country::Switzerland => dir::enums::Country::Switzerland,
api_enums::Country::SyrianArabRepublic => dir::enums::Country::SyrianArabRepublic,
api_enums::Country::TaiwanProvinceOfChina => dir::enums::Country::TaiwanProvinceOfChina,
api_enums::Country::Tajikistan => dir::enums::Country::Tajikistan,
api_enums::Country::TanzaniaUnitedRepublic => dir::enums::Country::TanzaniaUnitedRepublic,
api_enums::Country::Thailand => dir::enums::Country::Thailand,
api_enums::Country::TimorLeste => dir::enums::Country::TimorLeste,
api_enums::Country::Togo => dir::enums::Country::Togo,
api_enums::Country::Tokelau => dir::enums::Country::Tokelau,
api_enums::Country::Tonga => dir::enums::Country::Tonga,
api_enums::Country::TrinidadAndTobago => dir::enums::Country::TrinidadAndTobago,
api_enums::Country::Tunisia => dir::enums::Country::Tunisia,
api_enums::Country::Turkey => dir::enums::Country::Turkey,
api_enums::Country::Turkmenistan => dir::enums::Country::Turkmenistan,
api_enums::Country::TurksAndCaicosIslands => dir::enums::Country::TurksAndCaicosIslands,
api_enums::Country::Tuvalu => dir::enums::Country::Tuvalu,
api_enums::Country::Uganda => dir::enums::Country::Uganda,
api_enums::Country::Ukraine => dir::enums::Country::Ukraine,
api_enums::Country::UnitedArabEmirates => dir::enums::Country::UnitedArabEmirates,
api_enums::Country::UnitedKingdomOfGreatBritainAndNorthernIreland => {
dir::enums::Country::UnitedKingdomOfGreatBritainAndNorthernIreland
}
api_enums::Country::UnitedStatesOfAmerica => dir::enums::Country::UnitedStatesOfAmerica,
api_enums::Country::UnitedStatesMinorOutlyingIslands => {
dir::enums::Country::UnitedStatesMinorOutlyingIslands
}
api_enums::Country::Uruguay => dir::enums::Country::Uruguay,
api_enums::Country::Uzbekistan => dir::enums::Country::Uzbekistan,
api_enums::Country::Vanuatu => dir::enums::Country::Vanuatu,
api_enums::Country::VenezuelaBolivarianRepublic => {
dir::enums::Country::VenezuelaBolivarianRepublic
}
api_enums::Country::Vietnam => dir::enums::Country::Vietnam,
api_enums::Country::VirginIslandsBritish => dir::enums::Country::VirginIslandsBritish,
api_enums::Country::VirginIslandsUS => dir::enums::Country::VirginIslandsUS,
api_enums::Country::WallisAndFutuna => dir::enums::Country::WallisAndFutuna,
api_enums::Country::WesternSahara => dir::enums::Country::WesternSahara,
api_enums::Country::Yemen => dir::enums::Country::Yemen,
api_enums::Country::Zambia => dir::enums::Country::Zambia,
api_enums::Country::Zimbabwe => dir::enums::Country::Zimbabwe,
}
}
pub fn business_country_to_dir_value(c: api_enums::Country) -> dir::DirValue {
dir::DirValue::BusinessCountry(get_dir_country_dir_value(c))
}
pub fn billing_country_to_dir_value(c: api_enums::Country) -> dir::DirValue {
dir::DirValue::BillingCountry(get_dir_country_dir_value(c))
}
| 12,357 | 2,300 |
hyperswitch | crates/kgraph_utils/src/types.rs | .rs | use std::collections::{HashMap, HashSet};
use api_models::enums as api_enums;
use serde::Deserialize;
#[derive(Debug, Deserialize, Clone, Default)]
pub struct CountryCurrencyFilter {
pub connector_configs: HashMap<api_enums::RoutableConnectors, PaymentMethodFilters>,
pub default_configs: Option<PaymentMethodFilters>,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(transparent)]
pub struct PaymentMethodFilters(pub HashMap<PaymentMethodFilterKey, CurrencyCountryFlowFilter>);
#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Hash)]
#[serde(untagged)]
pub enum PaymentMethodFilterKey {
PaymentMethodType(api_enums::PaymentMethodType),
CardNetwork(api_enums::CardNetwork),
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct CurrencyCountryFlowFilter {
pub currency: Option<HashSet<api_enums::Currency>>,
pub country: Option<HashSet<api_enums::CountryAlpha2>>,
pub not_available_flows: Option<NotAvailableFlows>,
}
#[derive(Debug, Deserialize, Copy, Clone, Default)]
#[serde(default)]
pub struct NotAvailableFlows {
pub capture_method: Option<api_enums::CaptureMethod>,
}
| 261 | 2,301 |
hyperswitch | crates/kgraph_utils/src/lib.rs | .rs | pub mod error;
pub mod mca;
pub mod transformers;
pub mod types;
| 17 | 2,302 |
hyperswitch | crates/kgraph_utils/src/error.rs | .rs | #[cfg(feature = "v2")]
use common_enums::connector_enums;
use euclid::{dssa::types::AnalysisErrorType, frontend::dir};
#[derive(Debug, thiserror::Error, serde::Serialize)]
#[serde(tag = "type", content = "info", rename_all = "snake_case")]
pub enum KgraphError {
#[error("Invalid connector name encountered: '{0}'")]
InvalidConnectorName(
#[cfg(feature = "v1")] String,
#[cfg(feature = "v2")] connector_enums::Connector,
),
#[error("Error in domain creation")]
DomainCreationError,
#[error("There was an error constructing the graph: {0}")]
GraphConstructionError(hyperswitch_constraint_graph::GraphError<dir::DirValue>),
#[error("There was an error constructing the context")]
ContextConstructionError(AnalysisErrorType),
#[error("there was an unprecedented indexing error")]
IndexingError,
}
| 205 | 2,303 |
hyperswitch | crates/external_services/Cargo.toml | .toml | [package]
name = "external_services"
description = "Interactions of the router with external systems"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
readme = "README.md"
license.workspace = true
[features]
aws_kms = ["dep:aws-config", "dep:aws-sdk-kms"]
email = ["dep:aws-config"]
aws_s3 = ["dep:aws-config", "dep:aws-sdk-s3"]
hashicorp-vault = ["dep:vaultrs"]
v1 = ["hyperswitch_interfaces/v1", "common_utils/v1"]
dynamic_routing = ["dep:prost", "dep:tonic", "dep:tonic-reflection", "dep:tonic-types", "dep:api_models", "tokio/macros", "tokio/rt-multi-thread", "dep:tonic-build", "dep:router_env", "dep:hyper-util", "dep:http-body-util"]
[dependencies]
async-trait = "0.1.79"
aws-config = { version = "1.5.10", optional = true, features = ["behavior-version-latest"] }
aws-sdk-kms = { version = "1.51.0", optional = true }
aws-sdk-sesv2 = "1.57.0"
aws-sdk-sts = "1.51.0"
aws-sdk-s3 = { version = "1.65.0", optional = true }
aws-smithy-runtime = "1.8.0"
base64 = "0.22.0"
dyn-clone = "1.0.17"
error-stack = "0.4.1"
hex = "0.4.3"
hyper = "0.14.28"
hyper-proxy = "0.9.1"
lettre = "0.11.10"
once_cell = "1.19.0"
serde = { version = "1.0.197", features = ["derive"] }
thiserror = "1.0.58"
vaultrs = { version = "0.7.2", optional = true }
prost = { version = "0.13", optional = true }
tokio = "1.37.0"
tonic = { version = "0.12.2", optional = true }
tonic-reflection = { version = "0.12.2", optional = true }
tonic-types = { version = "0.12.2", optional = true }
hyper-util = { version = "0.1.9", optional = true }
http-body-util = { version = "0.1.2", optional = true }
# First party crates
common_utils = { version = "0.1.0", path = "../common_utils" }
hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false }
masking = { version = "0.1.0", path = "../masking" }
router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
api_models = { version = "0.1.0", path = "../api_models", optional = true }
[build-dependencies]
tonic-build = { version = "0.12", optional = true }
router_env = { version = "0.1.0", path = "../router_env", default-features = false, optional = true }
[lints]
workspace = true
| 774 | 2,304 |
hyperswitch | crates/external_services/build.rs | .rs | #[allow(clippy::expect_used)]
fn main() -> Result<(), Box<dyn std::error::Error>> {
#[cfg(feature = "dynamic_routing")]
{
// Get the directory of the current crate
let proto_path = router_env::workspace_path().join("proto");
let success_rate_proto_file = proto_path.join("success_rate.proto");
let contract_routing_proto_file = proto_path.join("contract_routing.proto");
let elimination_proto_file = proto_path.join("elimination_rate.proto");
let health_check_proto_file = proto_path.join("health_check.proto");
let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR")?);
// Compile the .proto file
tonic_build::configure()
.out_dir(out_dir)
.compile(
&[
success_rate_proto_file,
health_check_proto_file,
elimination_proto_file,
contract_routing_proto_file,
],
&[proto_path],
)
.expect("Failed to compile proto files");
}
Ok(())
}
| 219 | 2,305 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.