repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs | crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs | use common_enums::enums;
use common_utils::{
pii,
types::{MinorUnit, StringMajorUnit},
};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm},
types,
};
use hyperswitch_interfaces::{consts, errors};
use masking::Secret;
use reqwest::Url;
use serde::{Deserialize, Serialize};
use crate::{
types::ResponseRouterData,
utils::{self, CryptoData, ForeignTryFrom, PaymentsAuthorizeRequestData},
};
#[derive(Debug, Serialize)]
pub struct CryptopayRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for CryptopayRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct CryptopayPaymentsRequest {
price_amount: StringMajorUnit,
price_currency: enums::Currency,
pay_currency: String,
#[serde(skip_serializing_if = "Option::is_none")]
network: Option<String>,
success_redirect_url: Option<String>,
unsuccess_redirect_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
metadata: Option<pii::SecretSerdeValue>,
custom_id: String,
}
impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>>
for CryptopayPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CryptopayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let cryptopay_request = match item.router_data.request.payment_method_data {
PaymentMethodData::Crypto(ref cryptodata) => {
let pay_currency = cryptodata.get_pay_currency()?;
Ok(Self {
price_amount: item.amount.clone(),
price_currency: item.router_data.request.currency,
pay_currency,
network: cryptodata.network.to_owned(),
success_redirect_url: item.router_data.request.router_return_url.clone(),
unsuccess_redirect_url: item.router_data.request.router_return_url.clone(),
//Cryptopay only accepts metadata as Object. If any other type, payment will fail with error.
metadata: item.router_data.request.get_metadata_as_object(),
custom_id: item.router_data.connector_request_reference_id.clone(),
})
}
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("CryptoPay"),
))
}
}?;
Ok(cryptopay_request)
}
}
// Auth Struct
pub struct CryptopayAuthType {
pub(super) api_key: Secret<String>,
pub(super) api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for CryptopayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
api_key: api_key.to_owned(),
api_secret: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CryptopayPaymentStatus {
New,
Completed,
Unresolved,
Refunded,
Cancelled,
}
impl From<CryptopayPaymentStatus> for enums::AttemptStatus {
fn from(item: CryptopayPaymentStatus) -> Self {
match item {
CryptopayPaymentStatus::New => Self::AuthenticationPending,
CryptopayPaymentStatus::Completed => Self::Charged,
CryptopayPaymentStatus::Cancelled => Self::Failure,
CryptopayPaymentStatus::Unresolved | CryptopayPaymentStatus::Refunded => {
Self::Unresolved
} //mapped refunded to Unresolved because refund api is not available, also merchant has done the action on the connector dashboard.
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CryptopayPaymentsResponse {
pub data: CryptopayPaymentResponseData,
}
impl<F, T>
ForeignTryFrom<(
ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>,
Option<MinorUnit>,
)> for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, amount_captured_in_minor_units): (
ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>,
Option<MinorUnit>,
),
) -> Result<Self, Self::Error> {
let status = enums::AttemptStatus::from(item.response.data.status.clone());
let response = if utils::is_payment_failure(status) {
let payment_response = &item.response.data;
Err(ErrorResponse {
code: payment_response
.name
.clone()
.unwrap_or(consts::NO_ERROR_CODE.to_string()),
message: payment_response
.status_context
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: payment_response.status_context.clone(),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(payment_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
let redirection_data = item
.response
.data
.hosted_page_url
.map(|x| RedirectForm::from((x, common_utils::request::Method::Get)));
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.data.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
.response
.data
.custom_id
.or(Some(item.response.data.id)),
incremental_authorization_allowed: None,
charges: None,
})
};
match (amount_captured_in_minor_units, status) {
(Some(minor_amount), enums::AttemptStatus::Charged) => {
let amount_captured = Some(minor_amount.get_amount_as_i64());
Ok(Self {
status,
response,
amount_captured,
minor_amount_captured: amount_captured_in_minor_units,
..item.data
})
}
_ => Ok(Self {
status,
response,
..item.data
}),
}
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct CryptopayErrorData {
pub code: String,
pub message: String,
pub reason: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct CryptopayErrorResponse {
pub error: CryptopayErrorData,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CryptopayPaymentResponseData {
pub id: String,
pub custom_id: Option<String>,
pub customer_id: Option<String>,
pub status: CryptopayPaymentStatus,
pub status_context: Option<String>,
pub address: Option<Secret<String>>,
pub network: Option<String>,
pub uri: Option<String>,
pub price_amount: Option<StringMajorUnit>,
pub price_currency: Option<String>,
pub pay_amount: Option<StringMajorUnit>,
pub pay_currency: Option<String>,
pub fee: Option<String>,
pub fee_currency: Option<String>,
pub paid_amount: Option<String>,
pub name: Option<String>,
pub description: Option<String>,
pub success_redirect_url: Option<String>,
pub unsuccess_redirect_url: Option<String>,
pub hosted_page_url: Option<Url>,
pub created_at: Option<String>,
pub expires_at: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CryptopayWebhookDetails {
#[serde(rename = "type")]
pub service_type: String,
pub event: WebhookEvent,
pub data: CryptopayPaymentResponseData,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WebhookEvent {
TransactionCreated,
TransactionConfirmed,
StatusChanged,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/signifyd/transformers.rs | crates/hyperswitch_connectors/src/connectors/signifyd/transformers.rs | #[cfg(feature = "frm")]
pub mod api;
pub mod auth;
#[cfg(feature = "frm")]
pub use self::api::*;
pub use self::auth::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs | crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs | use api_models::webhooks::IncomingWebhookEvent;
use common_enums::{AttemptStatus, Currency, FraudCheckStatus, PaymentMethod};
use common_utils::{ext_traits::ValueExt, pii::Email};
use error_stack::{self, ResultExt};
pub use hyperswitch_domain_models::router_request_types::fraud_check::RefundMethod;
use hyperswitch_domain_models::{
router_data::RouterData,
router_flow_types::Fulfillment,
router_request_types::{
fraud_check::{self, FraudCheckFulfillmentData, FrmFulfillmentRequest},
ResponseId,
},
router_response_types::fraud_check::FraudCheckResponseData,
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::Secret;
use num_traits::ToPrimitive;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;
use crate::{
types::{
FrmCheckoutRouterData, FrmFulfillmentRouterData, FrmRecordReturnRouterData,
FrmSaleRouterData, FrmTransactionRouterData, ResponseRouterData,
},
utils::{
AddressDetailsData as _, FraudCheckCheckoutRequest, FraudCheckRecordReturnRequest as _,
FraudCheckSaleRequest as _, FraudCheckTransactionRequest as _, RouterData as _,
},
};
#[allow(dead_code)]
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DecisionDelivery {
Sync,
AsyncOnly,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Purchase {
#[serde(with = "common_utils::custom_serde::iso8601")]
created_at: PrimitiveDateTime,
order_channel: OrderChannel,
total_price: i64,
products: Vec<Products>,
shipments: Shipments,
currency: Option<Currency>,
total_shipping_cost: Option<i64>,
confirmation_email: Option<Email>,
confirmation_phone: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde(rename_all(serialize = "SCREAMING_SNAKE_CASE", deserialize = "snake_case"))]
pub enum OrderChannel {
Web,
Phone,
MobileApp,
Social,
Marketplace,
InStoreKiosk,
ScanAndGo,
SmartTv,
Mit,
}
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde(rename_all(serialize = "SCREAMING_SNAKE_CASE", deserialize = "snake_case"))]
pub enum FulfillmentMethod {
Delivery,
CounterPickup,
CubsidePickup,
LockerPickup,
StandardShipping,
ExpeditedShipping,
GasPickup,
ScheduledDelivery,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Products {
item_name: String,
item_price: i64,
item_quantity: i32,
item_id: Option<String>,
item_category: Option<String>,
item_sub_category: Option<String>,
item_is_digital: Option<bool>,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Shipments {
destination: Destination,
fulfillment_method: Option<FulfillmentMethod>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Destination {
full_name: Secret<String>,
organization: Option<String>,
email: Option<Email>,
address: Address,
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Address {
street_address: Secret<String>,
unit: Option<Secret<String>>,
postal_code: Secret<String>,
city: String,
province_code: Secret<String>,
country_code: common_enums::CountryAlpha2,
}
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde(rename_all(serialize = "SCREAMING_SNAKE_CASE", deserialize = "snake_case"))]
pub enum CoverageRequests {
Fraud, // use when you need a financial guarantee for Payment Fraud.
Inr, // use when you need a financial guarantee for Item Not Received.
Snad, // use when you need a financial guarantee for fraud alleging items are Significantly Not As Described.
All, // use when you need a financial guarantee on all chargebacks.
None, // use when you do not need a financial guarantee. Suggested actions in decision.checkpointAction are recommendations.
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsSaleRequest {
order_id: String,
purchase: Purchase,
decision_delivery: DecisionDelivery,
coverage_requests: Option<CoverageRequests>,
}
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde(rename_all(serialize = "camelCase", deserialize = "snake_case"))]
pub struct SignifydFrmMetadata {
pub total_shipping_cost: Option<i64>,
pub fulfillment_method: Option<FulfillmentMethod>,
pub coverage_request: Option<CoverageRequests>,
pub order_channel: OrderChannel,
}
impl TryFrom<&FrmSaleRouterData> for SignifydPaymentsSaleRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &FrmSaleRouterData) -> Result<Self, Self::Error> {
let products = item
.request
.get_order_details()?
.iter()
.map(|order_detail| Products {
item_name: order_detail.product_name.clone(),
item_price: order_detail.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future.
item_quantity: i32::from(order_detail.quantity),
item_id: order_detail.product_id.clone(),
item_category: order_detail.category.clone(),
item_sub_category: order_detail.sub_category.clone(),
item_is_digital: order_detail
.product_type
.as_ref()
.map(|product| product == &common_enums::ProductType::Digital),
})
.collect::<Vec<_>>();
let metadata: SignifydFrmMetadata = item
.frm_metadata
.clone()
.ok_or(ConnectorError::MissingRequiredField {
field_name: "frm_metadata",
})?
.parse_value("Signifyd Frm Metadata")
.change_context(ConnectorError::InvalidDataFormat {
field_name: "frm_metadata",
})?;
let ship_address = item.get_shipping_address()?;
let billing_address = item.get_billing()?;
let street_addr = ship_address.get_line1()?;
let city_addr = ship_address.get_city()?;
let zip_code_addr = ship_address.get_zip()?;
let country_code_addr = ship_address.get_country()?;
let _first_name_addr = ship_address.get_first_name()?;
let _last_name_addr = ship_address.get_last_name()?;
let address: Address = Address {
street_address: street_addr.clone(),
unit: None,
postal_code: zip_code_addr.clone(),
city: city_addr.clone(),
province_code: zip_code_addr.clone(),
country_code: country_code_addr.to_owned(),
};
let destination: Destination = Destination {
full_name: ship_address.get_full_name().unwrap_or_default(),
organization: None,
email: None,
address,
};
let created_at = common_utils::date_time::now();
let order_channel = metadata.order_channel;
let shipments = Shipments {
destination,
fulfillment_method: metadata.fulfillment_method,
};
let purchase = Purchase {
created_at,
order_channel,
total_price: item.request.amount,
products,
shipments,
currency: item.request.currency,
total_shipping_cost: metadata.total_shipping_cost,
confirmation_email: item.request.email.clone(),
confirmation_phone: billing_address
.clone()
.phone
.and_then(|phone_data| phone_data.number),
};
Ok(Self {
order_id: item.attempt_id.clone(),
purchase,
decision_delivery: DecisionDelivery::Sync, // Specify SYNC if you require the Response to contain a decision field. If you have registered for a webhook associated with this checkpoint, then the webhook will also be sent when SYNC is specified. If ASYNC_ONLY is specified, then the decision field in the response will be null, and you will require a Webhook integration to receive Signifyd's final decision
coverage_requests: metadata.coverage_request,
})
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Decision {
#[serde(with = "common_utils::custom_serde::iso8601")]
created_at: PrimitiveDateTime,
checkpoint_action: SignifydPaymentStatus,
checkpoint_action_reason: Option<String>,
checkpoint_action_policy: Option<String>,
score: Option<f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SignifydPaymentStatus {
Accept,
Challenge,
Credit,
Hold,
Reject,
}
impl From<SignifydPaymentStatus> for FraudCheckStatus {
fn from(item: SignifydPaymentStatus) -> Self {
match item {
SignifydPaymentStatus::Accept => Self::Legit,
SignifydPaymentStatus::Reject => Self::Fraud,
SignifydPaymentStatus::Hold => Self::ManualReview,
SignifydPaymentStatus::Challenge | SignifydPaymentStatus::Credit => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsResponse {
signifyd_id: i64,
order_id: String,
decision: Decision,
}
impl<F, T> TryFrom<ResponseRouterData<F, SignifydPaymentsResponse, T, FraudCheckResponseData>>
for RouterData<F, T, FraudCheckResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SignifydPaymentsResponse, T, FraudCheckResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id),
status: FraudCheckStatus::from(item.response.decision.checkpoint_action),
connector_metadata: None,
score: item.response.decision.score.and_then(|data| data.to_i32()),
reason: item
.response
.decision
.checkpoint_action_reason
.map(serde_json::Value::from),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct SignifydErrorResponse {
pub messages: Vec<String>,
pub errors: serde_json::Value,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Transactions {
transaction_id: String,
gateway_status_code: String,
payment_method: PaymentMethod,
amount: i64,
currency: Currency,
gateway: Option<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsTransactionRequest {
order_id: String,
checkout_id: String,
transactions: Transactions,
}
impl From<AttemptStatus> for GatewayStatusCode {
fn from(item: AttemptStatus) -> Self {
match item {
AttemptStatus::Pending => Self::Pending,
AttemptStatus::Failure => Self::Failure,
AttemptStatus::Charged => Self::Success,
_ => Self::Pending,
}
}
}
impl TryFrom<&FrmTransactionRouterData> for SignifydPaymentsTransactionRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &FrmTransactionRouterData) -> Result<Self, Self::Error> {
let currency = item.request.get_currency()?;
let transactions = Transactions {
amount: item.request.amount,
transaction_id: item.clone().payment_id,
gateway_status_code: GatewayStatusCode::from(item.status).to_string(),
payment_method: item.payment_method,
currency,
gateway: item.request.connector.clone(),
};
Ok(Self {
order_id: item.attempt_id.clone(),
checkout_id: item.payment_id.clone(),
transactions,
})
}
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
pub enum GatewayStatusCode {
Success,
Failure,
#[default]
Pending,
Error,
Cancelled,
Expired,
SoftDecline,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsCheckoutRequest {
checkout_id: String,
order_id: String,
purchase: Purchase,
coverage_requests: Option<CoverageRequests>,
}
impl TryFrom<&FrmCheckoutRouterData> for SignifydPaymentsCheckoutRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &FrmCheckoutRouterData) -> Result<Self, Self::Error> {
let products = item
.request
.get_order_details()?
.iter()
.map(|order_detail| Products {
item_name: order_detail.product_name.clone(),
item_price: order_detail.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future.
item_quantity: i32::from(order_detail.quantity),
item_id: order_detail.product_id.clone(),
item_category: order_detail.category.clone(),
item_sub_category: order_detail.sub_category.clone(),
item_is_digital: order_detail
.product_type
.as_ref()
.map(|product| product == &common_enums::ProductType::Digital),
})
.collect::<Vec<_>>();
let metadata: SignifydFrmMetadata = item
.frm_metadata
.clone()
.ok_or(ConnectorError::MissingRequiredField {
field_name: "frm_metadata",
})?
.parse_value("Signifyd Frm Metadata")
.change_context(ConnectorError::InvalidDataFormat {
field_name: "frm_metadata",
})?;
let ship_address = item.get_shipping_address()?;
let street_addr = ship_address.get_line1()?;
let city_addr = ship_address.get_city()?;
let zip_code_addr = ship_address.get_zip()?;
let country_code_addr = ship_address.get_country()?;
let _first_name_addr = ship_address.get_first_name()?;
let _last_name_addr = ship_address.get_last_name()?;
let billing_address = item.get_billing()?;
let address: Address = Address {
street_address: street_addr.clone(),
unit: None,
postal_code: zip_code_addr.clone(),
city: city_addr.clone(),
province_code: zip_code_addr.clone(),
country_code: country_code_addr.to_owned(),
};
let destination: Destination = Destination {
full_name: ship_address.get_full_name().unwrap_or_default(),
organization: None,
email: None,
address,
};
let created_at = common_utils::date_time::now();
let order_channel = metadata.order_channel;
let shipments: Shipments = Shipments {
destination,
fulfillment_method: metadata.fulfillment_method,
};
let purchase = Purchase {
created_at,
order_channel,
total_price: item.request.amount,
products,
shipments,
currency: item.request.currency,
total_shipping_cost: metadata.total_shipping_cost,
confirmation_email: item.request.email.clone(),
confirmation_phone: billing_address
.clone()
.phone
.and_then(|phone_data| phone_data.number),
};
Ok(Self {
checkout_id: item.payment_id.clone(),
order_id: item.attempt_id.clone(),
purchase,
coverage_requests: metadata.coverage_request,
})
}
}
#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct FrmFulfillmentSignifydRequest {
pub order_id: String,
pub fulfillment_status: Option<FulfillmentStatus>,
pub fulfillments: Vec<Fulfillments>,
}
#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde(untagged)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub enum FulfillmentStatus {
PARTIAL,
COMPLETE,
REPLACEMENT,
CANCELED,
}
#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct Fulfillments {
pub shipment_id: String,
pub products: Option<Vec<Product>>,
pub destination: Destination,
pub fulfillment_method: Option<String>,
pub carrier: Option<String>,
pub shipment_status: Option<String>,
pub tracking_urls: Option<Vec<String>>,
pub tracking_numbers: Option<Vec<String>>,
pub shipped_at: Option<String>,
}
#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct Product {
pub item_name: String,
pub item_quantity: i64,
pub item_id: String,
}
impl TryFrom<&FrmFulfillmentRouterData> for FrmFulfillmentSignifydRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &FrmFulfillmentRouterData) -> Result<Self, Self::Error> {
Ok(Self {
order_id: item.request.fulfillment_req.order_id.clone(),
fulfillment_status: item
.request
.fulfillment_req
.fulfillment_status
.as_ref()
.map(|fulfillment_status| FulfillmentStatus::from(&fulfillment_status.clone())),
fulfillments: get_signifyd_fulfillments_from_frm_fulfillment_request(
&item.request.fulfillment_req,
),
})
}
}
impl From<&fraud_check::FulfillmentStatus> for FulfillmentStatus {
fn from(status: &fraud_check::FulfillmentStatus) -> Self {
match status {
fraud_check::FulfillmentStatus::PARTIAL => Self::PARTIAL,
fraud_check::FulfillmentStatus::COMPLETE => Self::COMPLETE,
fraud_check::FulfillmentStatus::REPLACEMENT => Self::REPLACEMENT,
fraud_check::FulfillmentStatus::CANCELED => Self::CANCELED,
}
}
}
pub(crate) fn get_signifyd_fulfillments_from_frm_fulfillment_request(
fulfillment_req: &FrmFulfillmentRequest,
) -> Vec<Fulfillments> {
fulfillment_req
.fulfillments
.iter()
.map(|fulfillment| Fulfillments {
shipment_id: fulfillment.shipment_id.clone(),
products: fulfillment
.products
.as_ref()
.map(|products| products.iter().map(|p| Product::from(p.clone())).collect()),
destination: Destination::from(fulfillment.destination.clone()),
tracking_urls: fulfillment_req.tracking_urls.clone(),
tracking_numbers: fulfillment_req.tracking_numbers.clone(),
fulfillment_method: fulfillment_req.fulfillment_method.clone(),
carrier: fulfillment_req.carrier.clone(),
shipment_status: fulfillment_req.shipment_status.clone(),
shipped_at: fulfillment_req.shipped_at.clone(),
})
.collect()
}
impl From<fraud_check::Product> for Product {
fn from(product: fraud_check::Product) -> Self {
Self {
item_name: product.item_name,
item_quantity: product.item_quantity,
item_id: product.item_id,
}
}
}
impl From<fraud_check::Destination> for Destination {
fn from(destination: fraud_check::Destination) -> Self {
Self {
full_name: destination.full_name,
organization: destination.organization,
email: destination.email,
address: Address::from(destination.address),
}
}
}
impl From<fraud_check::Address> for Address {
fn from(address: fraud_check::Address) -> Self {
Self {
street_address: address.street_address,
unit: address.unit,
postal_code: address.postal_code,
city: address.city,
province_code: address.province_code,
country_code: address.country_code,
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct FrmFulfillmentSignifydApiResponse {
pub order_id: String,
pub shipment_ids: Vec<String>,
}
impl
TryFrom<
ResponseRouterData<
Fulfillment,
FrmFulfillmentSignifydApiResponse,
FraudCheckFulfillmentData,
FraudCheckResponseData,
>,
> for RouterData<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
Fulfillment,
FrmFulfillmentSignifydApiResponse,
FraudCheckFulfillmentData,
FraudCheckResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(FraudCheckResponseData::FulfillmentResponse {
order_id: item.response.order_id,
shipment_ids: item.response.shipment_ids,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct SignifydRefund {
method: RefundMethod,
amount: String,
currency: Currency,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsRecordReturnRequest {
order_id: String,
return_id: String,
refund_transaction_id: Option<String>,
refund: SignifydRefund,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsRecordReturnResponse {
return_id: String,
order_id: String,
}
impl<F, T>
TryFrom<ResponseRouterData<F, SignifydPaymentsRecordReturnResponse, T, FraudCheckResponseData>>
for RouterData<F, T, FraudCheckResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
SignifydPaymentsRecordReturnResponse,
T,
FraudCheckResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(FraudCheckResponseData::RecordReturnResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id),
return_id: Some(item.response.return_id.to_string()),
connector_metadata: None,
}),
..item.data
})
}
}
impl TryFrom<&FrmRecordReturnRouterData> for SignifydPaymentsRecordReturnRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &FrmRecordReturnRouterData) -> Result<Self, Self::Error> {
let currency = item.request.get_currency()?;
let refund = SignifydRefund {
method: item.request.refund_method.clone(),
amount: item.request.amount.to_string(),
currency,
};
Ok(Self {
return_id: uuid::Uuid::new_v4().to_string(),
refund_transaction_id: item.request.refund_transaction_id.clone(),
refund,
order_id: item.attempt_id.clone(),
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SignifydWebhookBody {
pub order_id: String,
pub review_disposition: ReviewDisposition,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ReviewDisposition {
Fraudulent,
Good,
}
impl From<ReviewDisposition> for IncomingWebhookEvent {
fn from(value: ReviewDisposition) -> Self {
match value {
ReviewDisposition::Fraudulent => Self::FrmRejected,
ReviewDisposition::Good => Self::FrmApproved,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/auth.rs | crates/hyperswitch_connectors/src/connectors/signifyd/transformers/auth.rs | use hyperswitch_domain_models::router_data::ConnectorAuthType;
use hyperswitch_interfaces::errors::ConnectorError;
use masking::Secret;
pub struct SignifydAuthType {
pub api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for SignifydAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs | crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs | use bytes::Bytes;
use common_enums::enums;
use common_utils::{
date_time::DateFormat, errors::CustomResult, ext_traits::ValueExt, types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{CompleteAuthorizeData, PaymentsAuthorizeData, ResponseId},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types,
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, CardData as _, CardMandateInfo, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, RouterData as _,
},
};
pub struct PayboxRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for PayboxRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
const AUTH_REQUEST: &str = "00001";
const CAPTURE_REQUEST: &str = "00002";
const AUTH_AND_CAPTURE_REQUEST: &str = "00003";
const SYNC_REQUEST: &str = "00017";
const REFUND_REQUEST: &str = "00014";
const SUCCESS_CODE: &str = "00000";
const VERSION_PAYBOX: &str = "00104";
const PAY_ORIGIN_INTERNET: &str = "024";
const THREE_DS_FAIL_CODE: &str = "00000000";
const RECURRING_ORIGIN: &str = "027";
const MANDATE_REQUEST: &str = "00056";
const MANDATE_AUTH_ONLY: &str = "00051";
const MANDATE_AUTH_AND_CAPTURE_ONLY: &str = "00053";
type Error = error_stack::Report<errors::ConnectorError>;
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PayboxPaymentsRequest {
Card(PaymentsRequest),
CardThreeDs(ThreeDSPaymentsRequest),
Mandate(MandatePaymentRequest),
}
#[derive(Debug, Serialize)]
pub struct PaymentsRequest {
#[serde(rename = "DATEQ")]
pub date: String,
#[serde(rename = "TYPE")]
pub transaction_type: String,
#[serde(rename = "NUMQUESTION")]
pub paybox_request_number: String,
#[serde(rename = "MONTANT")]
pub amount: MinorUnit,
#[serde(rename = "REFERENCE")]
pub description_reference: String,
#[serde(rename = "VERSION")]
pub version: String,
#[serde(rename = "DEVISE")]
pub currency: String,
#[serde(rename = "PORTEUR")]
pub card_number: cards::CardNumber,
#[serde(rename = "DATEVAL")]
pub expiration_date: Secret<String>,
#[serde(rename = "CVV")]
pub cvv: Secret<String>,
#[serde(rename = "ACTIVITE")]
pub activity: String,
#[serde(rename = "SITE")]
pub site: Secret<String>,
#[serde(rename = "RANG")]
pub rank: Secret<String>,
#[serde(rename = "CLE")]
pub key: Secret<String>,
#[serde(rename = "ID3D")]
#[serde(skip_serializing_if = "Option::is_none")]
pub three_ds_data: Option<Secret<String>>,
#[serde(rename = "REFABONNE")]
#[serde(skip_serializing_if = "Option::is_none")]
pub customer_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ThreeDSPaymentsRequest {
id_merchant: Secret<String>,
id_session: String,
amount: MinorUnit,
currency: String,
#[serde(rename = "CCNumber")]
cc_number: cards::CardNumber,
#[serde(rename = "CCExpDate")]
cc_exp_date: Secret<String>,
#[serde(rename = "CVVCode")]
cvv_code: Secret<String>,
#[serde(rename = "URLRetour")]
url_retour: String,
#[serde(rename = "URLHttpDirect")]
url_http_direct: String,
email_porteur: common_utils::pii::Email,
first_name: Secret<String>,
last_name: Secret<String>,
address1: Secret<String>,
zip_code: Secret<String>,
city: String,
country_code: String,
total_quantity: i32,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PayboxCaptureRequest {
#[serde(rename = "DATEQ")]
pub date: String,
#[serde(rename = "TYPE")]
pub transaction_type: String,
#[serde(rename = "NUMQUESTION")]
pub paybox_request_number: String,
#[serde(rename = "MONTANT")]
pub amount: MinorUnit,
#[serde(rename = "REFERENCE")]
pub reference: String,
#[serde(rename = "VERSION")]
pub version: String,
#[serde(rename = "DEVISE")]
pub currency: String,
#[serde(rename = "SITE")]
pub site: Secret<String>,
#[serde(rename = "RANG")]
pub rank: Secret<String>,
#[serde(rename = "CLE")]
pub key: Secret<String>,
#[serde(rename = "NUMTRANS")]
pub transaction_number: String,
#[serde(rename = "NUMAPPEL")]
pub paybox_order_id: String,
}
impl TryFrom<&PayboxRouterData<&types::PaymentsCaptureRouterData>> for PayboxCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PayboxRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let auth_data: PayboxAuthType =
PayboxAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let currency = enums::Currency::iso_4217(item.router_data.request.currency).to_string();
let paybox_meta_data: PayboxMeta =
utils::to_connector_meta(item.router_data.request.connector_meta.clone())?;
let format_time = common_utils::date_time::format_date(
common_utils::date_time::now(),
DateFormat::DDMMYYYYHHmmss,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
date: format_time.clone(),
transaction_type: CAPTURE_REQUEST.to_string(),
paybox_request_number: get_paybox_request_number()?,
version: VERSION_PAYBOX.to_string(),
currency,
site: auth_data.site,
rank: auth_data.rang,
key: auth_data.cle,
transaction_number: paybox_meta_data.connector_request_id,
paybox_order_id: item.router_data.request.connector_transaction_id.clone(),
amount: item.amount,
reference: item.router_data.connector_request_reference_id.to_string(),
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PayboxRsyncRequest {
#[serde(rename = "DATEQ")]
pub date: String,
#[serde(rename = "TYPE")]
pub transaction_type: String,
#[serde(rename = "NUMQUESTION")]
pub paybox_request_number: String,
#[serde(rename = "VERSION")]
pub version: String,
#[serde(rename = "SITE")]
pub site: Secret<String>,
#[serde(rename = "RANG")]
pub rank: Secret<String>,
#[serde(rename = "CLE")]
pub key: Secret<String>,
#[serde(rename = "NUMTRANS")]
pub transaction_number: String,
#[serde(rename = "NUMAPPEL")]
pub paybox_order_id: String,
}
impl TryFrom<&types::RefundSyncRouterData> for PayboxRsyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
let auth_data: PayboxAuthType = PayboxAuthType::try_from(&item.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let format_time = common_utils::date_time::format_date(
common_utils::date_time::now(),
DateFormat::DDMMYYYYHHmmss,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
date: format_time.clone(),
transaction_type: SYNC_REQUEST.to_string(),
paybox_request_number: get_paybox_request_number()?,
version: VERSION_PAYBOX.to_string(),
site: auth_data.site,
rank: auth_data.rang,
key: auth_data.cle,
transaction_number: item
.request
.connector_refund_id
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?,
paybox_order_id: item.request.connector_transaction_id.clone(),
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PayboxPSyncRequest {
#[serde(rename = "DATEQ")]
pub date: String,
#[serde(rename = "TYPE")]
pub transaction_type: String,
#[serde(rename = "NUMQUESTION")]
pub paybox_request_number: String,
#[serde(rename = "VERSION")]
pub version: String,
#[serde(rename = "SITE")]
pub site: Secret<String>,
#[serde(rename = "RANG")]
pub rank: Secret<String>,
#[serde(rename = "CLE")]
pub key: Secret<String>,
#[serde(rename = "NUMTRANS")]
pub transaction_number: String,
#[serde(rename = "NUMAPPEL")]
pub paybox_order_id: String,
}
impl TryFrom<&types::PaymentsSyncRouterData> for PayboxPSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let auth_data: PayboxAuthType = PayboxAuthType::try_from(&item.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let format_time = common_utils::date_time::format_date(
common_utils::date_time::now(),
DateFormat::DDMMYYYYHHmmss,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let paybox_meta_data: PayboxMeta =
utils::to_connector_meta(item.request.connector_meta.clone())?;
Ok(Self {
date: format_time.clone(),
transaction_type: SYNC_REQUEST.to_string(),
paybox_request_number: get_paybox_request_number()?,
version: VERSION_PAYBOX.to_string(),
site: auth_data.site,
rank: auth_data.rang,
key: auth_data.cle,
transaction_number: paybox_meta_data.connector_request_id,
paybox_order_id: item
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PayboxMeta {
pub connector_request_id: String,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PayboxRefundRequest {
#[serde(rename = "DATEQ")]
pub date: String,
#[serde(rename = "TYPE")]
pub transaction_type: String,
#[serde(rename = "NUMQUESTION")]
pub paybox_request_number: String,
#[serde(rename = "MONTANT")]
pub amount: MinorUnit,
#[serde(rename = "VERSION")]
pub version: String,
#[serde(rename = "DEVISE")]
pub currency: String,
#[serde(rename = "SITE")]
pub site: Secret<String>,
#[serde(rename = "RANG")]
pub rank: Secret<String>,
#[serde(rename = "CLE")]
pub key: Secret<String>,
#[serde(rename = "NUMTRANS")]
pub transaction_number: String,
#[serde(rename = "NUMAPPEL")]
pub paybox_order_id: String,
}
impl TryFrom<&PayboxRouterData<&types::PaymentsAuthorizeRouterData>> for PayboxPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PayboxRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let auth_data: PayboxAuthType =
PayboxAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let transaction_type = get_transaction_type(
item.router_data.request.capture_method,
item.router_data.request.is_mandate_payment(),
)?;
let currency =
enums::Currency::iso_4217(item.router_data.request.currency).to_string();
let expiration_date =
req_card.get_card_expiry_month_year_2_digit_with_delimiter("".to_owned())?;
let format_time = common_utils::date_time::format_date(
common_utils::date_time::now(),
DateFormat::DDMMYYYYHHmmss,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
if item.router_data.is_three_ds() {
let address = item.router_data.get_billing_address()?;
Ok(Self::CardThreeDs(ThreeDSPaymentsRequest {
id_merchant: auth_data.merchant_id,
id_session: item.router_data.connector_request_reference_id.clone(),
amount: item.amount,
currency,
cc_number: req_card.card_number,
cc_exp_date: expiration_date,
cvv_code: req_card.card_cvc,
url_retour: item.router_data.request.get_complete_authorize_url()?,
url_http_direct: item.router_data.request.get_complete_authorize_url()?,
email_porteur: item.router_data.request.get_email()?,
first_name: address.get_first_name()?.clone(),
last_name: address.get_last_name()?.clone(),
address1: address.get_line1()?.clone(),
zip_code: address.get_zip()?.clone(),
city: address.get_city()?.clone(),
country_code: format!(
"{:03}",
common_enums::Country::from_alpha2(*address.get_country()?)
.to_numeric()
),
total_quantity: 1,
}))
} else {
Ok(Self::Card(PaymentsRequest {
date: format_time.clone(),
transaction_type,
paybox_request_number: get_paybox_request_number()?,
amount: item.amount,
description_reference: item
.router_data
.connector_request_reference_id
.clone(),
version: VERSION_PAYBOX.to_string(),
currency,
card_number: req_card.card_number,
expiration_date,
cvv: req_card.card_cvc,
activity: PAY_ORIGIN_INTERNET.to_string(),
site: auth_data.site,
rank: auth_data.rang,
key: auth_data.cle,
three_ds_data: None,
customer_id: match item.router_data.request.is_mandate_payment() {
true => {
let reference_id = item
.router_data
.connector_mandate_request_reference_id
.clone()
.ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_request_reference_id",
}
})?;
Some(Secret::new(reference_id))
}
false => None,
},
}))
}
}
PaymentMethodData::MandatePayment => {
let mandate_data = item.router_data.request.get_card_mandate_info()?;
Ok(Self::Mandate(MandatePaymentRequest::try_from((
item,
mandate_data,
))?))
}
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
fn get_transaction_type(
capture_method: Option<enums::CaptureMethod>,
is_mandate_request: bool,
) -> Result<String, Error> {
match (capture_method, is_mandate_request) {
(Some(enums::CaptureMethod::Automatic), false)
| (None, false)
| (Some(enums::CaptureMethod::SequentialAutomatic), false) => {
Ok(AUTH_AND_CAPTURE_REQUEST.to_string())
}
(Some(enums::CaptureMethod::Automatic), true) | (None, true) => {
Err(errors::ConnectorError::NotSupported {
message: "Automatic Capture in CIT payments".to_string(),
connector: "Paybox",
})?
}
(Some(enums::CaptureMethod::Manual), false) => Ok(AUTH_REQUEST.to_string()),
(Some(enums::CaptureMethod::Manual), true)
| (Some(enums::CaptureMethod::SequentialAutomatic), true) => {
Ok(MANDATE_REQUEST.to_string())
}
_ => Err(errors::ConnectorError::CaptureMethodNotSupported)?,
}
}
fn get_paybox_request_number() -> Result<String, Error> {
let time_stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.ok()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.as_millis()
.to_string();
// unix time (in milliseconds) has 13 digits.if we consider 8 digits(the number digits to make day deterministic) there is no collision in the paybox_request_number as it will reset the paybox_request_number for each day and paybox accepting maximum length is 10 so we gonna take 9 (13-9)
let request_number = time_stamp
.get(4..)
.ok_or(errors::ConnectorError::ParsingFailed)?;
Ok(request_number.to_string())
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PayboxAuthType {
pub(super) site: Secret<String>,
pub(super) rang: Secret<String>,
pub(super) cle: Secret<String>,
pub(super) merchant_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PayboxAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} = auth_type
{
Ok(Self {
site: api_key.to_owned(),
rang: key1.to_owned(),
cle: api_secret.to_owned(),
merchant_id: key2.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PayboxResponse {
NonThreeDs(TransactionResponse),
ThreeDs(Secret<String>),
Error(String),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransactionResponse {
#[serde(rename = "NUMTRANS")]
pub transaction_number: String,
#[serde(rename = "NUMAPPEL")]
pub paybox_order_id: String,
#[serde(rename = "CODEREPONSE")]
pub response_code: String,
#[serde(rename = "COMMENTAIRE")]
pub response_message: String,
#[serde(rename = "PORTEUR")]
pub carrier_id: Option<Secret<String>>,
#[serde(rename = "REFABONNE")]
pub customer_id: Option<Secret<String>>,
}
pub fn parse_url_encoded_to_struct<T: DeserializeOwned>(
query_bytes: Bytes,
) -> CustomResult<T, errors::ConnectorError> {
let (cow, _, _) = encoding_rs::ISO_8859_15.decode(&query_bytes);
serde_qs::from_str::<T>(cow.as_ref()).change_context(errors::ConnectorError::ParsingFailed)
}
pub fn parse_paybox_response(
query_bytes: Bytes,
is_three_ds: bool,
) -> CustomResult<PayboxResponse, errors::ConnectorError> {
let (cow, _, _) = encoding_rs::ISO_8859_15.decode(&query_bytes);
let response_str = cow.as_ref().trim();
if utils::is_html_response(response_str) && is_three_ds {
let response = response_str.to_string();
return Ok(if response.contains("Erreur 201") {
PayboxResponse::Error(response)
} else {
PayboxResponse::ThreeDs(response.into())
});
}
serde_qs::from_str::<TransactionResponse>(response_str)
.map(PayboxResponse::NonThreeDs)
.change_context(errors::ConnectorError::ParsingFailed)
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum PayboxStatus {
#[serde(rename = "Remboursé")]
Refunded,
#[serde(rename = "Annulé")]
Cancelled,
#[serde(rename = "Autorisé")]
Authorised,
#[serde(rename = "Capturé")]
Captured,
#[serde(rename = "Refusé")]
Rejected,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PayboxSyncResponse {
#[serde(rename = "NUMTRANS")]
pub transaction_number: String,
#[serde(rename = "NUMAPPEL")]
pub paybox_order_id: String,
#[serde(rename = "CODEREPONSE")]
pub response_code: String,
#[serde(rename = "COMMENTAIRE")]
pub response_message: String,
#[serde(rename = "STATUS")]
pub status: PayboxStatus,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PayboxCaptureResponse {
#[serde(rename = "NUMTRANS")]
pub transaction_number: String,
#[serde(rename = "NUMAPPEL")]
pub paybox_order_id: String,
#[serde(rename = "CODEREPONSE")]
pub response_code: String,
#[serde(rename = "COMMENTAIRE")]
pub response_message: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PayboxCaptureResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PayboxCaptureResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response = item.response.clone();
let status = get_status_of_request(response.response_code.clone());
match status {
true => Ok(Self {
status: enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.paybox_order_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(PayboxMeta {
connector_request_id: response.transaction_number.clone()
})),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
amount_captured: None,
..item.data
}),
false => Ok(Self {
response: Err(ErrorResponse {
code: response.response_code.clone(),
message: response.response_message.clone(),
reason: Some(response.response_message),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.transaction_number),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
impl<F> TryFrom<ResponseRouterData<F, PayboxResponse, PaymentsAuthorizeData, PaymentsResponseData>>
for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PayboxResponse, PaymentsAuthorizeData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.clone() {
PayboxResponse::NonThreeDs(response) => {
let status: bool = get_status_of_request(response.response_code.clone());
match status {
true => Ok(Self {
status: match (
item.data.request.is_auto_capture()?,
item.data.request.is_cit_mandate_payment(),
) {
(_, true) | (false, false) => enums::AttemptStatus::Authorized,
(true, false) => enums::AttemptStatus::Charged,
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.paybox_order_id,
),
redirection_data: Box::new(None),
mandate_reference: Box::new(response.carrier_id.as_ref().map(
|pm: &Secret<String>| MandateReference {
connector_mandate_id: Some(pm.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id:
response.customer_id.map(|secret| secret.expose()),
},
)),
connector_metadata: Some(serde_json::json!(PayboxMeta {
connector_request_id: response.transaction_number.clone()
})),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
false => Ok(Self {
response: Err(ErrorResponse {
code: response.response_code.clone(),
message: response.response_message.clone(),
reason: Some(response.response_message),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(response.transaction_number),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
PayboxResponse::ThreeDs(data) => Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::Html {
html_data: data.peek().to_string(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
PayboxResponse::Error(_) => Ok(Self {
response: Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: Some(NO_ERROR_MESSAGE.to_string()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, PayboxSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PayboxSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response = item.response.clone();
let status = get_status_of_request(response.response_code.clone());
let connector_payment_status = item.response.status;
match status {
true => Ok(Self {
status: enums::AttemptStatus::from(connector_payment_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.paybox_order_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(PayboxMeta {
connector_request_id: response.transaction_number.clone()
})),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
false => Ok(Self {
response: Err(ErrorResponse {
code: response.response_code.clone(),
message: response.response_message.clone(),
reason: Some(response.response_message),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.transaction_number),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
impl From<PayboxStatus> for common_enums::RefundStatus {
fn from(item: PayboxStatus) -> Self {
match item {
PayboxStatus::Refunded => Self::Success,
PayboxStatus::Cancelled
| PayboxStatus::Authorised
| PayboxStatus::Captured
| PayboxStatus::Rejected => Self::Failure,
}
}
}
impl From<PayboxStatus> for enums::AttemptStatus {
fn from(item: PayboxStatus) -> Self {
match item {
PayboxStatus::Cancelled => Self::Voided,
PayboxStatus::Authorised => Self::Authorized,
PayboxStatus::Captured | PayboxStatus::Refunded => Self::Charged,
PayboxStatus::Rejected => Self::Failure,
}
}
}
fn get_status_of_request(item: String) -> bool {
item == *SUCCESS_CODE
}
impl<F> TryFrom<&PayboxRouterData<&types::RefundsRouterData<F>>> for PayboxRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PayboxRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let auth_data: PayboxAuthType =
PayboxAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let currency = enums::Currency::iso_4217(item.router_data.request.currency).to_string();
let format_time = common_utils::date_time::format_date(
common_utils::date_time::now(),
DateFormat::DDMMYYYYHHmmss,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let paybox_meta_data: PayboxMeta =
utils::to_connector_meta(item.router_data.request.connector_metadata.clone())?;
Ok(Self {
date: format_time.clone(),
transaction_type: REFUND_REQUEST.to_string(),
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs | crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs | use std::collections::HashMap;
use cards::CardNumber;
use common_enums::{
AttemptStatus, CaptureMethod, CountryAlpha2, CountryAlpha3, Currency, RefundStatus,
};
use common_utils::{
errors::CustomResult,
ext_traits::ValueExt,
request::Method,
types::{MinorUnit, StringMinorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
refunds::{Execute, RSync},
SetupMandate,
},
router_request_types::{
CompleteAuthorizeData, CompleteAuthorizeRedirectResponse, ResponseId,
SetupMandateRequestData,
},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsPostAuthenticateRouterData,
PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{consts::NO_ERROR_CODE, errors};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use strum::Display;
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsPostAuthenticateResponseRouterData, PaymentsPreprocessingResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
ResponseRouterData,
},
utils::{
get_unimplemented_payment_method_error_message, to_connector_meta,
to_connector_meta_from_secret, CardData, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, PaymentsPostAuthenticateRequestData,
PaymentsPreProcessingRequestData, PaymentsSetupMandateRequestData, PaymentsSyncRequestData,
RouterData as _,
},
};
#[derive(Clone, Copy, Debug)]
enum AddressKind {
Billing,
Shipping,
}
trait AddressConstructor {
fn new(
name: Option<Secret<String>>,
street: Option<Secret<String>>,
city: Option<String>,
post_code: Option<Secret<String>>,
country: Option<CountryAlpha3>,
) -> Self;
}
impl AddressConstructor for BillingAddress {
fn new(
name: Option<Secret<String>>,
street: Option<Secret<String>>,
city: Option<String>,
post_code: Option<Secret<String>>,
country: Option<CountryAlpha3>,
) -> Self {
Self {
name,
street,
city,
post_code,
country,
}
}
}
impl AddressConstructor for ShippingAddress {
fn new(
name: Option<Secret<String>>,
street: Option<Secret<String>>,
city: Option<String>,
post_code: Option<Secret<String>>,
country: Option<CountryAlpha3>,
) -> Self {
Self {
name,
street,
city,
post_code,
country,
}
}
}
fn get_validated_address_details_generic<RouterContextDataAlias, AddressOutput>(
data: &RouterContextDataAlias,
address_kind: AddressKind,
) -> Result<Option<AddressOutput>, error_stack::Report<errors::ConnectorError>>
where
RouterContextDataAlias: crate::utils::RouterData,
AddressOutput: AddressConstructor + Sized,
{
let (
opt_line1,
opt_line2,
opt_full_name,
opt_city,
opt_zip,
opt_country,
has_address_details_check,
address_type_str,
max_name_len,
max_street_len,
max_city_len,
max_post_code_len,
max_country_len,
) = match address_kind {
AddressKind::Billing => (
data.get_optional_billing_line1(),
data.get_optional_billing_line2(),
data.get_optional_billing_full_name(),
data.get_optional_billing_city(),
data.get_optional_billing_zip(),
data.get_optional_billing_country()
.map(CountryAlpha2::from_alpha2_to_alpha3),
data.get_optional_billing().is_some(),
"billing",
MAX_BILLING_ADDRESS_NAME_LENGTH,
MAX_BILLING_ADDRESS_STREET_LENGTH,
MAX_BILLING_ADDRESS_CITY_LENGTH,
MAX_BILLING_ADDRESS_POST_CODE_LENGTH,
MAX_BILLING_ADDRESS_COUNTRY_LENGTH,
),
AddressKind::Shipping => (
data.get_optional_shipping_line1(),
data.get_optional_shipping_line2(),
data.get_optional_shipping_full_name(),
data.get_optional_shipping_city(),
data.get_optional_shipping_zip(),
data.get_optional_shipping_country()
.map(CountryAlpha2::from_alpha2_to_alpha3),
data.get_optional_shipping().is_some(),
"shipping",
MAX_BILLING_ADDRESS_NAME_LENGTH,
MAX_BILLING_ADDRESS_STREET_LENGTH,
MAX_BILLING_ADDRESS_CITY_LENGTH,
MAX_BILLING_ADDRESS_POST_CODE_LENGTH,
MAX_BILLING_ADDRESS_COUNTRY_LENGTH,
),
};
let street_val = match (opt_line1.clone(), opt_line2.clone()) {
(Some(l1), Some(l2)) => Some(Secret::new(format!("{}, {}", l1.expose(), l2.expose()))),
(Some(l1), None) => Some(l1),
(None, Some(l2)) => Some(l2),
(None, None) => None,
};
if has_address_details_check {
let name_val = opt_full_name;
if let Some(ref val) = name_val {
let length = val.clone().expose().len();
if length > max_name_len {
return Err(error_stack::Report::from(
errors::ConnectorError::MaxFieldLengthViolated {
field_name: format!(
"{address_type_str}.address.first_name & {address_type_str}.address.last_name",
),
connector: "Nexixpay".to_string(),
max_length: max_name_len,
received_length: length,
},
));
}
}
if let Some(ref val) = street_val {
let length = val.clone().expose().len();
if length > max_street_len {
return Err(error_stack::Report::from(
errors::ConnectorError::MaxFieldLengthViolated {
field_name: format!(
"{address_type_str}.address.line1 & {address_type_str}.address.line2",
),
connector: "Nexixpay".to_string(),
max_length: max_street_len,
received_length: length,
},
));
}
}
let city_val = opt_city;
if let Some(ref val) = city_val {
let length = val.len();
if length > max_city_len {
return Err(error_stack::Report::from(
errors::ConnectorError::MaxFieldLengthViolated {
field_name: format!("{address_type_str}.address.city"),
connector: "Nexixpay".to_string(),
max_length: max_city_len,
received_length: length,
},
));
}
}
let post_code_val = opt_zip;
if let Some(ref val) = post_code_val {
let length = val.clone().expose().len();
if length > max_post_code_len {
return Err(error_stack::Report::from(
errors::ConnectorError::MaxFieldLengthViolated {
field_name: format!("{address_type_str}.address.zip"),
connector: "Nexixpay".to_string(),
max_length: max_post_code_len,
received_length: length,
},
));
}
}
let country_val = opt_country;
if let Some(ref val) = country_val {
let length = val.to_string().len();
if length > max_country_len {
return Err(error_stack::Report::from(
errors::ConnectorError::MaxFieldLengthViolated {
field_name: format!("{address_type_str}.address.country"),
connector: "Nexixpay".to_string(),
max_length: max_country_len,
received_length: length,
},
));
}
}
Ok(Some(AddressOutput::new(
name_val,
street_val,
city_val,
post_code_val,
country_val,
)))
} else {
Ok(None)
}
}
const MAX_ORDER_ID_LENGTH: usize = 18;
const MAX_CARD_HOLDER_LENGTH: usize = 255;
const MAX_BILLING_ADDRESS_NAME_LENGTH: usize = 50;
const MAX_BILLING_ADDRESS_STREET_LENGTH: usize = 50;
const MAX_BILLING_ADDRESS_CITY_LENGTH: usize = 40;
const MAX_BILLING_ADDRESS_POST_CODE_LENGTH: usize = 16;
const MAX_BILLING_ADDRESS_COUNTRY_LENGTH: usize = 3;
pub struct NexixpayRouterData<T> {
pub amount: StringMinorUnit,
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for NexixpayRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexixpayRecurringAction {
NoRecurring,
SubsequentPayment,
ContractCreation,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ContractType {
MitUnscheduled,
MitScheduled,
Cit,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecurrenceRequest {
action: NexixpayRecurringAction,
contract_id: Option<Secret<String>>,
contract_type: Option<ContractType>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayNonMandatePaymentRequest {
card: NexixpayCard,
recurrence: RecurrenceRequest,
action_type: Option<NexixpayPaymentRequestActionType>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum NexixpayPaymentRequestActionType {
Verify,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayMandatePaymentRequest {
contract_id: Secret<String>,
capture_type: Option<NexixpayCaptureType>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum NexixpayPaymentsRequestData {
NexixpayNonMandatePaymentRequest(Box<NexixpayNonMandatePaymentRequest>),
NexixpayMandatePaymentRequest(Box<NexixpayMandatePaymentRequest>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayPaymentsRequest {
order: Order,
#[serde(flatten)]
payment_data: NexixpayPaymentsRequestData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexixpayCaptureType {
Implicit,
Explicit,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayCompleteAuthorizeRequest {
order: Order,
card: NexixpayCard,
operation_id: String,
capture_type: Option<NexixpayCaptureType>,
three_d_s_auth_data: ThreeDSAuthData,
recurrence: RecurrenceRequest,
action_type: Option<NexixpayPaymentRequestActionType>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OperationData {
operation_id: String,
operation_currency: Currency,
operation_result: NexixpayPaymentStatus,
operation_type: NexixpayOperationType,
order_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayCompleteAuthorizeResponse {
operation: OperationData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayRedirectRequest {
operation_id: Option<String>,
three_d_s_auth_response: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Order {
order_id: String,
amount: StringMinorUnit,
currency: Currency,
description: Option<String>,
customer_info: CustomerInfo,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomerInfo {
card_holder_name: Secret<String>,
billing_address: Option<BillingAddress>,
shipping_address: Option<ShippingAddress>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BillingAddress {
name: Option<Secret<String>>,
street: Option<Secret<String>>,
city: Option<String>,
post_code: Option<Secret<String>>,
country: Option<CountryAlpha3>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ShippingAddress {
name: Option<Secret<String>>,
street: Option<Secret<String>>,
city: Option<String>,
post_code: Option<Secret<String>>,
country: Option<CountryAlpha3>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayCard {
pan: CardNumber,
expiry_date: Secret<String>,
cvv: Secret<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentsResponse {
operation: Operation,
three_d_s_auth_request: String,
three_d_s_auth_url: Secret<url::Url>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayMandateResponse {
operation: Operation,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum NexixpayPaymentsResponse {
PaymentResponse(Box<PaymentsResponse>),
MandateResponse(Box<NexixpayMandateResponse>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSAuthResult {
authentication_value: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum NexixpayPaymentIntent {
Capture,
Cancel,
Authorize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayRedirectionRequest {
pub three_d_s_auth_url: String,
pub three_ds_request: String,
pub return_url: String,
pub transaction_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayConnectorMetaData {
pub three_d_s_auth_result: Option<ThreeDSAuthResult>,
pub three_d_s_auth_response: Option<Secret<String>>,
pub authorization_operation_id: Option<String>,
pub capture_operation_id: Option<String>,
pub cancel_operation_id: Option<String>,
pub psync_flow: NexixpayPaymentIntent,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateNexixpayConnectorMetaData {
pub three_d_s_auth_result: Option<ThreeDSAuthResult>,
pub three_d_s_auth_response: Option<Secret<String>>,
pub authorization_operation_id: Option<String>,
pub capture_operation_id: Option<String>,
pub cancel_operation_id: Option<String>,
pub psync_flow: Option<NexixpayPaymentIntent>,
pub meta_data: serde_json::Value,
pub is_auto_capture: bool,
}
fn update_nexi_meta_data(
update_request: UpdateNexixpayConnectorMetaData,
) -> CustomResult<serde_json::Value, errors::ConnectorError> {
let nexixpay_meta_data =
serde_json::from_value::<NexixpayConnectorMetaData>(update_request.meta_data)
.change_context(errors::ConnectorError::ParsingFailed)?;
Ok(serde_json::json!(NexixpayConnectorMetaData {
three_d_s_auth_result: nexixpay_meta_data
.three_d_s_auth_result
.or(update_request.three_d_s_auth_result),
three_d_s_auth_response: nexixpay_meta_data
.three_d_s_auth_response
.or(update_request.three_d_s_auth_response),
authorization_operation_id: nexixpay_meta_data
.authorization_operation_id
.clone()
.or(update_request.authorization_operation_id.clone()),
capture_operation_id: {
nexixpay_meta_data
.capture_operation_id
.or(if update_request.is_auto_capture {
nexixpay_meta_data
.authorization_operation_id
.or(update_request.authorization_operation_id.clone())
} else {
update_request.capture_operation_id
})
},
cancel_operation_id: nexixpay_meta_data
.cancel_operation_id
.or(update_request.cancel_operation_id),
psync_flow: update_request
.psync_flow
.unwrap_or(nexixpay_meta_data.psync_flow)
}))
}
pub fn get_error_response(
operation_result: NexixpayPaymentStatus,
status_code: u16,
) -> ErrorResponse {
ErrorResponse {
status_code,
code: NO_ERROR_CODE.to_string(),
message: operation_result.to_string(),
reason: Some(operation_result.to_string()),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
fn get_nexi_order_id(payment_id: &str) -> CustomResult<String, errors::ConnectorError> {
if payment_id.len() > MAX_ORDER_ID_LENGTH {
if payment_id.starts_with("pay_") {
Ok(payment_id
.chars()
.take(MAX_ORDER_ID_LENGTH)
.collect::<String>())
} else {
Err(error_stack::Report::from(
errors::ConnectorError::MaxFieldLengthViolated {
field_name: "payment_id".to_string(),
connector: "Nexixpay".to_string(),
max_length: MAX_ORDER_ID_LENGTH,
received_length: payment_id.len(),
},
))
}
} else {
Ok(payment_id.to_string())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSAuthData {
three_d_s_auth_response: Option<Secret<String>>,
authentication_value: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NexixpayRedirectionResponse {
operation: Operation,
three_d_s_auth_result: ThreeDSAuthResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Operation {
additional_data: AdditionalData,
channel: Option<Channel>,
customer_info: CustomerInfo,
operation_amount: StringMinorUnit,
operation_currency: Currency,
operation_id: String,
operation_result: NexixpayPaymentStatus,
operation_time: String,
operation_type: NexixpayOperationType,
order_id: String,
payment_method: String,
warnings: Option<Vec<DetailedWarnings>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Channel {
Ecommerce,
Pos,
Backoffice,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DetailedWarnings {
code: Option<String>,
description: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdditionalData {
masked_pan: String,
card_id: Secret<String>,
card_id4: Option<Secret<String>>,
card_expiry_date: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RedirectPayload {
#[serde(rename = "PaRes")]
pa_res: Option<Secret<String>>,
#[serde(rename = "paymentId")]
payment_id: Option<String>,
}
impl TryFrom<&PaymentsPreProcessingRouterData> for NexixpayRedirectRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> {
let redirect_response = item.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let redirect_payload = redirect_response
.payload
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
})?
.expose();
let customer_details_encrypted: RedirectPayload =
serde_json::from_value::<RedirectPayload>(redirect_payload.clone()).change_context(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "redirection_payload",
},
)?;
Ok(Self {
operation_id: customer_details_encrypted.payment_id,
three_d_s_auth_response: customer_details_encrypted.pa_res,
})
}
}
impl TryFrom<&PaymentsPostAuthenticateRouterData> for NexixpayRedirectRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsPostAuthenticateRouterData) -> Result<Self, Self::Error> {
let redirect_response = item.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let redirect_payload = redirect_response
.payload
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
})?
.expose();
let customer_details_encrypted: RedirectPayload =
serde_json::from_value::<RedirectPayload>(redirect_payload.clone()).change_context(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "redirection_payload",
},
)?;
Ok(Self {
operation_id: customer_details_encrypted.payment_id,
three_d_s_auth_response: customer_details_encrypted.pa_res,
})
}
}
// Common function to process the preprocessing response
fn process_nexixpay_preprocessing_response(
response: NexixpayRedirectionResponse,
redirect_response: Option<&CompleteAuthorizeRedirectResponse>,
metadata: Option<Secret<serde_json::Value>>,
is_auto_capture: bool,
http_code: u16,
) -> Result<
(AttemptStatus, Result<PaymentsResponseData, ErrorResponse>),
error_stack::Report<errors::ConnectorError>,
> {
let three_ds_data = response.three_d_s_auth_result;
let customer_details_encrypted: RedirectPayload = redirect_response
.and_then(|res| res.payload.to_owned())
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
})?
.expose()
.parse_value("RedirectPayload")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let meta_data = to_connector_meta_from_secret(metadata)?;
let connector_metadata = Some(update_nexi_meta_data(UpdateNexixpayConnectorMetaData {
three_d_s_auth_result: Some(three_ds_data),
three_d_s_auth_response: customer_details_encrypted.pa_res,
authorization_operation_id: None,
capture_operation_id: None,
cancel_operation_id: None,
psync_flow: None,
meta_data,
is_auto_capture,
})?);
let status = AttemptStatus::from(response.operation.operation_result.clone());
let result = match status {
AttemptStatus::Failure => Err(get_error_response(
response.operation.operation_result.clone(),
http_code,
)),
_ => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.operation.order_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(response.operation.order_id),
incremental_authorization_allowed: None,
charges: None,
}),
};
Ok((status, result))
}
impl TryFrom<PaymentsPreprocessingResponseRouterData<NexixpayRedirectionResponse>>
for PaymentsPreProcessingRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsPreprocessingResponseRouterData<NexixpayRedirectionResponse>,
) -> Result<Self, Self::Error> {
let is_auto_capture = item.data.request.is_auto_capture()?;
let (status, response) = process_nexixpay_preprocessing_response(
item.response,
item.data.request.redirect_response.as_ref(),
item.data.request.metadata.clone(),
is_auto_capture,
item.http_code,
)?;
Ok(Self {
status,
response,
..item.data
})
}
}
impl TryFrom<PaymentsPostAuthenticateResponseRouterData<NexixpayRedirectionResponse>>
for PaymentsPostAuthenticateRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsPostAuthenticateResponseRouterData<NexixpayRedirectionResponse>,
) -> Result<Self, Self::Error> {
let is_auto_capture = item.data.request.is_auto_capture()?;
let (status, response) = process_nexixpay_preprocessing_response(
item.response,
item.data.request.redirect_response.as_ref(),
item.data.request.metadata.clone(),
is_auto_capture,
item.http_code,
)?;
Ok(Self {
status,
response,
..item.data
})
}
}
impl TryFrom<&NexixpayRouterData<&PaymentsAuthorizeRouterData>> for NexixpayPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &NexixpayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let order_id = get_nexi_order_id(&item.router_data.payment_id)?;
let billing_address = get_validated_billing_address(item.router_data)?;
let shipping_address = get_validated_shipping_address(item.router_data)?;
let customer_info = CustomerInfo {
card_holder_name: match item.router_data.get_billing_full_name()? {
name if name.clone().expose().len() <= MAX_CARD_HOLDER_LENGTH => name,
_ => {
return Err(error_stack::Report::from(
errors::ConnectorError::MaxFieldLengthViolated {
field_name: "billing.address.first_name & billing.address.last_name"
.to_string(),
connector: "Nexixpay".to_string(),
max_length: MAX_CARD_HOLDER_LENGTH,
received_length: item
.router_data
.get_billing_full_name()?
.expose()
.len(),
},
))
}
},
billing_address: billing_address.clone(),
shipping_address: shipping_address.clone(),
};
let order = Order {
order_id,
amount: item.amount.clone(),
currency: item.router_data.request.currency,
description: item.router_data.description.clone(),
customer_info,
};
let payment_data = NexixpayPaymentsRequestData::try_from(item)?;
Ok(Self {
order,
payment_data,
})
}
}
impl TryFrom<&NexixpayRouterData<&PaymentsAuthorizeRouterData>> for NexixpayPaymentsRequestData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &NexixpayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item
.router_data
.request
.mandate_id
.clone()
.and_then(|mandate_id| mandate_id.mandate_reference_id)
{
None => {
let recurrence_request_obj = if item.router_data.request.is_mandate_payment() {
let contract_id = item
.router_data
.connector_mandate_request_reference_id
.clone()
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_request_reference_id",
})?;
RecurrenceRequest {
action: NexixpayRecurringAction::ContractCreation,
contract_id: Some(Secret::new(contract_id)),
contract_type: Some(ContractType::MitUnscheduled),
}
} else {
RecurrenceRequest {
action: NexixpayRecurringAction::NoRecurring,
contract_id: None,
contract_type: None,
}
};
match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref req_card) => {
if item.router_data.is_three_ds() {
Ok(Self::NexixpayNonMandatePaymentRequest(Box::new(
NexixpayNonMandatePaymentRequest {
card: NexixpayCard {
pan: req_card.card_number.clone(),
expiry_date: req_card.get_expiry_date_as_mmyy()?,
cvv: req_card.card_cvc.clone(),
},
recurrence: recurrence_request_obj,
action_type: if item.router_data.request.minor_amount
== MinorUnit::zero()
{
Some(NexixpayPaymentRequestActionType::Verify)
} else {
None
},
},
)))
} else {
Err(errors::ConnectorError::NotSupported {
message: "No threeds is not supported".to_string(),
connector: "nexixpay",
}
.into())
}
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("nexixpay"),
))?
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs | crates/hyperswitch_connectors/src/connectors/mifinity/transformers.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::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePay(_)
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Mifinity"),
)
.into()),
},
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
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>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/payjustnowinstore/transformers.rs | crates/hyperswitch_connectors/src/connectors/payjustnowinstore/transformers.rs | use common_enums::enums;
use common_utils::{ext_traits::ValueExt, request::Method, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::Execute,
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils,
};
pub struct PayjustnowinstoreRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for PayjustnowinstoreRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub struct PayjustnowinstoreAuthType {
pub(super) merchant_api_key: Secret<String>,
pub(super) merchant_terminal_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PayjustnowinstoreAuthType {
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_api_key: api_key.to_owned(),
merchant_terminal_id: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct PayjustnowinstorePaymentsRequest {
amount: MinorUnit,
currency: common_enums::Currency,
merchant_reference: String,
callback_url: String,
items: Vec<OrderItem>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct OrderItem {
name: String,
sku: Option<String>,
quantity: u32,
price: MinorUnit,
}
impl TryFrom<&PayjustnowinstoreRouterData<&PaymentsAuthorizeRouterData>>
for PayjustnowinstorePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PayjustnowinstoreRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let items = item
.router_data
.request
.order_details
.as_ref()
.map(|order_details| {
order_details
.iter()
.map(|order| {
let product_name = order.product_name.trim();
if product_name.is_empty() {
return Err(errors::ConnectorError::MissingRequiredField {
field_name: "order_details[].product_name",
});
}
let sku = order.product_id.as_ref().and_then(|id| {
let trimmed = id.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
});
Ok(OrderItem {
name: product_name.to_string(),
sku,
quantity: u32::from(order.quantity),
price: order.amount,
})
})
.collect::<Result<Vec<OrderItem>, errors::ConnectorError>>()
})
.transpose()?
.unwrap_or_default();
Ok(Self {
amount: item.amount,
currency: item.router_data.request.currency,
merchant_reference: item
.router_data
.request
.merchant_order_reference_id
.clone()
.unwrap_or(item.router_data.payment_id.clone()),
// Webhooks are not implemented yet for PJN In-Store, and `callback_url` is a mandatory field.
// Since PJN Instore does not accept null or empty values, a placeholder is used here.
callback_url: "callback_url".to_string(),
items,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PayjustnowinstorePaymentsResponse {
token: String,
amount: MinorUnit,
scan_url: url::Url,
}
impl<F, T>
TryFrom<ResponseRouterData<F, PayjustnowinstorePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PayjustnowinstorePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirection_data = Some(RedirectForm::from((item.response.scan_url, Method::Get)));
Ok(Self {
status: common_enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.token),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayjustnowinstorePaymentStatus {
#[default]
Pending,
Paid,
PaymentFailed,
OrderCancelled,
OrderRefunded,
}
impl From<PayjustnowinstorePaymentStatus> for common_enums::AttemptStatus {
fn from(item: PayjustnowinstorePaymentStatus) -> Self {
match item {
PayjustnowinstorePaymentStatus::Pending => Self::AuthenticationPending,
PayjustnowinstorePaymentStatus::Paid => Self::Charged,
PayjustnowinstorePaymentStatus::PaymentFailed => Self::Failure,
PayjustnowinstorePaymentStatus::OrderCancelled => Self::Voided,
PayjustnowinstorePaymentStatus::OrderRefunded => Self::AutoRefunded,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PayjustnowinstoreSyncResponse {
merchant_reference: String,
token: String,
scan_url: Option<url::Url>,
payment_status: PayjustnowinstorePaymentStatus,
amount: Option<MinorUnit>,
reason: Option<String>,
paid_at: Option<String>,
cancelled_at: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PayjustnowinstorePaymentsResponseMetadata {
merchant_reference: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PayjustnowinstoreSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PayjustnowinstoreSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = enums::AttemptStatus::from(item.response.payment_status);
let redirection_data = item
.response
.scan_url
.map(|url| RedirectForm::from((url, Method::Get)));
let response = if utils::is_payment_failure(status) {
Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: item
.response
.reason
.clone()
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: item.response.reason.clone(),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(item.response.token.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
let connector_metadata = Some(serde_json::json!(
PayjustnowinstorePaymentsResponseMetadata {
merchant_reference: item.response.merchant_reference,
}
));
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.token),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct PayjustnowinstoreRefundRequest {
request_id: String,
merchant_reference: String,
token: String,
amount: MinorUnit,
}
impl<F> TryFrom<&PayjustnowinstoreRouterData<&RefundsRouterData<F>>>
for PayjustnowinstoreRefundRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PayjustnowinstoreRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let metadata: PayjustnowinstorePaymentsResponseMetadata = item
.router_data
.request
.connector_metadata
.as_ref()
.ok_or(errors::ConnectorError::NoConnectorMetaData)?
.clone()
.parse_value("PayjustnowinstorePaymentsResponseMetadata")
.change_context(errors::ConnectorError::ParsingFailed)?;
Ok(Self {
request_id: item.router_data.request.refund_id.clone(),
merchant_reference: metadata.merchant_reference,
token: item.router_data.request.connector_transaction_id.clone(),
amount: item.amount.to_owned(),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayjustnowinstoreRefundStatus {
Refunded,
Failed,
}
impl From<PayjustnowinstoreRefundStatus> for enums::RefundStatus {
fn from(item: PayjustnowinstoreRefundStatus) -> Self {
match item {
PayjustnowinstoreRefundStatus::Refunded => Self::Success,
PayjustnowinstoreRefundStatus::Failed => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PayjustnowinstoreRefundResponse {
status: PayjustnowinstoreRefundStatus,
reason: Option<String>,
refunded_at: Option<String>,
amount_refunded: MinorUnit,
refund_request_id: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, PayjustnowinstoreRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, PayjustnowinstoreRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
let response = if utils::is_refund_failure(refund_status) {
Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: item
.response
.reason
.clone()
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: item.response.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,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.refund_request_id.clone(),
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct PayjustnowinstoreErrorResponse {
pub error: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs | crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs | use common_enums::enums::{self, AuthenticationType};
use common_utils::{pii::IpAddress, types::FloatMajorUnit};
use hyperswitch_domain_models::{
payment_method_data::{Card, PaymentMethodData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::Execute,
router_request_types::{BrowserInformation, PaymentsCancelData, ResponseId},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, 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"];
pub struct PowertranzRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(FloatMajorUnit, T)> for PowertranzRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (FloatMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct PowertranzPaymentsRequest {
transaction_identifier: String,
total_amount: FloatMajorUnit,
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<&PowertranzRouterData<&PaymentsAuthorizeRouterData>> for PowertranzPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PowertranzRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let source = match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(card) => {
let card_holder_name = item.router_data.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(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotSupported {
message: utils::SELECTED_PAYMENT_METHOD.to_string(),
connector: "powertranz",
}
.into())
}
}?;
// let billing_address = get_address_details(&item.router_data.address.billing, &item.router_data.request.email);
// let shipping_address = get_address_details(&item.router_data.address.shipping, &item.router_data.request.email);
let (three_d_secure, extended_data) = match item.router_data.auth_type {
AuthenticationType::ThreeDs => (true, Some(ExtendedData::try_from(item.router_data)?)),
AuthenticationType::NoThreeDs => (false, None),
};
Ok(Self {
transaction_identifier: Uuid::new_v4().to_string(),
total_amount: item.amount,
currency_code: item.router_data.request.currency.iso_4217().to_string(),
three_d_secure,
source,
order_identifier: item.router_data.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<FloatMajorUnit>,
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<&PowertranzRouterData<&PaymentsCaptureRouterData>> for PowertranzBaseRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PowertranzRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
transaction_identifier: item.router_data.request.connector_transaction_id.clone(),
total_amount: Some(item.amount),
refund: None,
})
}
}
impl<F> TryFrom<&PowertranzRouterData<&RefundsRouterData<F>>> for PowertranzBaseRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PowertranzRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
transaction_identifier: item.router_data.request.connector_transaction_id.clone(),
total_amount: Some(item.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,
connector_metadata: 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,
connector_metadata: 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,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs | crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs | use std::collections::HashMap;
use api_models::admin::{AdditionalMerchantData, MerchantAccountData, MerchantRecipientData};
use common_enums::enums;
use common_utils::{id_type::MerchantId, request::Method, types::StringMajorUnit};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self},
};
//TODO: Fill the struct with respective fields
pub struct TokenioRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for TokenioRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenioPaymentsRequest {
pub initiation: PaymentInitiation,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInitiation {
pub ref_id: String,
pub remittance_information_primary: MerchantId,
pub amount: Amount,
pub local_instrument: LocalInstrument,
pub creditor: Creditor,
pub callback_url: Option<String>,
pub flow_type: FlowType,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
pub value: StringMajorUnit,
pub currency: enums::Currency,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LocalInstrument {
Sepa,
SepaInstant,
FasterPayments,
Elixir,
Bankgiro,
Plusgiro,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum Creditor {
FasterPayments {
#[serde(rename = "sortCode")]
sort_code: Secret<String>,
#[serde(rename = "accountNumber")]
account_number: Secret<String>,
name: Secret<String>,
},
Sepa {
iban: Secret<String>,
name: Secret<String>,
},
SepaInstant {
iban: Secret<String>,
name: Secret<String>,
},
ElixirIban {
iban: Secret<String>,
name: Secret<String>,
},
ElixirAccount {
#[serde(rename = "accountNumber")]
account_number: Secret<String>,
name: Secret<String>,
},
Bankgiro {
#[serde(rename = "bankgiroNumber")]
bankgiro_number: Secret<String>,
name: Secret<String>,
},
Plusgiro {
#[serde(rename = "plusgiroNumber")]
plusgiro_number: Secret<String>,
name: Secret<String>,
},
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FlowType {
ApiOnly,
FullHostedPages,
EmbeddedHostedPages,
}
impl TryFrom<&TokenioRouterData<&PaymentsAuthorizeRouterData>> for TokenioPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &TokenioRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::OpenBanking(_) => {
let (local_instrument, creditor) = match item
.router_data
.additional_merchant_data
.as_ref()
.and_then(|data| match data {
AdditionalMerchantData::OpenBankingRecipientData(recipient_data) => {
match recipient_data {
MerchantRecipientData::AccountData(account_data) => {
Some(account_data)
}
_ => None,
}
}
}) {
Some(MerchantAccountData::FasterPayments {
account_number,
sort_code,
name,
..
}) => (
LocalInstrument::FasterPayments,
Creditor::FasterPayments {
sort_code: sort_code.clone(),
account_number: account_number.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::SepaInstant { iban, name, .. }) => (
LocalInstrument::SepaInstant,
Creditor::SepaInstant {
iban: iban.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::Sepa { iban, name, .. }) => (
LocalInstrument::Sepa,
Creditor::Sepa {
iban: iban.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::Iban { iban, name, .. }) => (
LocalInstrument::Sepa, // Assuming IBAN defaults to SEPA
Creditor::Sepa {
iban: iban.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::Elixir {
account_number,
iban,
name,
..
}) => {
if !iban.peek().is_empty() {
(
LocalInstrument::Elixir,
Creditor::ElixirIban {
iban: iban.clone(),
name: name.clone().into(),
},
)
} else {
(
LocalInstrument::Elixir,
Creditor::ElixirAccount {
account_number: account_number.clone(),
name: name.clone().into(),
},
)
}
}
Some(MerchantAccountData::Bacs {
account_number,
sort_code,
name,
..
}) => (
LocalInstrument::FasterPayments,
Creditor::FasterPayments {
sort_code: sort_code.clone(),
account_number: account_number.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::Bankgiro { number, name, .. }) => (
LocalInstrument::Bankgiro,
Creditor::Bankgiro {
bankgiro_number: number.clone(),
name: name.clone().into(),
},
),
Some(MerchantAccountData::Plusgiro { number, name, .. }) => (
LocalInstrument::Plusgiro,
Creditor::Plusgiro {
plusgiro_number: number.clone(),
name: name.clone().into(),
},
),
None => {
return Err(errors::ConnectorError::InvalidConnectorConfig {
config: "No valid payment method found in additional merchant data",
}
.into())
}
};
Ok(Self {
initiation: PaymentInitiation {
ref_id: utils::generate_12_digit_number().to_string(),
remittance_information_primary: item.router_data.merchant_id.clone(),
amount: Amount {
value: item.amount.clone(),
currency: item.router_data.request.currency,
},
local_instrument,
creditor,
callback_url: item.router_data.request.router_return_url.clone(),
flow_type: FlowType::FullHostedPages,
},
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
pub struct TokenioAuthType {
pub(super) merchant_id: Secret<String>,
pub(super) private_key: Secret<String>,
pub(super) key_id: Secret<String>,
pub(super) key_algorithm: CryptoAlgorithm,
}
#[derive(Debug, Deserialize, PartialEq)]
pub enum CryptoAlgorithm {
RS256,
ES256,
#[serde(rename = "EdDSA")]
EDDSA,
}
impl TryFrom<&str> for CryptoAlgorithm {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(s: &str) -> Result<Self, Self::Error> {
match s.to_uppercase().as_str() {
"RS256" | "rs256" => Ok(Self::RS256),
"ES256" | "es256" => Ok(Self::ES256),
"EDDSA" | "eddsa" | "EdDSA" => Ok(Self::EDDSA),
_ => Err(errors::ConnectorError::InvalidConnectorConfig {
config: "Unsupported key algorithm. Select from RS256, ES256, EdDSA",
}
.into()),
}
}
}
impl TryFrom<&ConnectorAuthType> for TokenioAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Ok(Self {
merchant_id: key1.to_owned(),
private_key: api_secret.to_owned(),
key_id: api_key.to_owned(),
key_algorithm: CryptoAlgorithm::try_from(key2.clone().expose().as_str())?,
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenioApiWrapper {
pub payment: PaymentResponse,
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(untagged)]
pub enum TokenioPaymentsResponse {
Success(TokenioApiWrapper),
Error(TokenioErrorResponse),
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentResponse {
pub id: String,
pub status: PaymentStatus,
pub status_reason_information: Option<String>,
pub authentication: Option<Authentication>,
pub error_info: Option<ErrorInfo>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentStatus {
InitiationPending,
InitiationPendingRedirectAuth,
InitiationPendingRedirectAuthVerification,
InitiationPendingRedirectHp,
InitiationPendingRedemption,
InitiationPendingRedemptionVerification,
InitiationProcessing,
InitiationCompleted,
InitiationRejected,
InitiationRejectedInsufficientFunds,
InitiationFailed,
InitiationDeclined,
InitiationExpired,
InitiationNoFinalStatusAvailable,
SettlementInProgress,
SettlementCompleted,
SettlementIncomplete,
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(untagged)]
pub enum Authentication {
RedirectUrl {
#[serde(rename = "redirectUrl")]
redirect_url: String,
},
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorInfo {
pub http_error_code: i32,
pub message: Option<String>,
pub token_external_error: Option<bool>,
pub token_trace_id: Option<String>,
}
impl From<TokenioPaymentsResponse> for common_enums::AttemptStatus {
fn from(response: TokenioPaymentsResponse) -> Self {
match response {
TokenioPaymentsResponse::Success(wrapper) => match wrapper.payment.status {
// Pending statuses - payment is still in progress
PaymentStatus::InitiationPending
| PaymentStatus::InitiationPendingRedirectAuth
| PaymentStatus::InitiationPendingRedirectAuthVerification
| PaymentStatus::InitiationPendingRedirectHp
| PaymentStatus::InitiationPendingRedemption
| PaymentStatus::InitiationPendingRedemptionVerification => {
Self::AuthenticationPending
}
// Success statuses
PaymentStatus::SettlementCompleted => Self::Charged,
// Settlement in progress - could map to different status based on business logic
PaymentStatus::SettlementInProgress => Self::Pending,
// Failure statuses
PaymentStatus::InitiationRejected
| PaymentStatus::InitiationFailed
| PaymentStatus::InitiationExpired
| PaymentStatus::InitiationRejectedInsufficientFunds
| PaymentStatus::InitiationDeclined => Self::Failure,
// Uncertain status
PaymentStatus::InitiationCompleted
| PaymentStatus::InitiationProcessing
| PaymentStatus::InitiationNoFinalStatusAvailable
| PaymentStatus::SettlementIncomplete => Self::Pending,
},
TokenioPaymentsResponse::Error(_) => Self::Failure,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, TokenioPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, TokenioPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = common_enums::AttemptStatus::from(item.response.clone());
let response = match item.response {
TokenioPaymentsResponse::Success(wrapper) => {
let payment = wrapper.payment;
if let common_enums::AttemptStatus::Failure = status {
Err(ErrorResponse {
code: payment
.error_info
.as_ref()
.map(|ei| ei.http_error_code.to_string())
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: payment
.error_info
.as_ref()
.and_then(|ei| ei.message.clone())
.or_else(|| payment.status_reason_information.clone())
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: Some(
payment
.error_info
.as_ref()
.and_then(|ei| ei.message.clone())
.or_else(|| payment.status_reason_information.clone())
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(payment.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(payment.id.clone()),
redirection_data: Box::new(payment.authentication.as_ref().map(|auth| {
match auth {
Authentication::RedirectUrl { redirect_url } => {
RedirectForm::Form {
endpoint: redirect_url.to_string(),
method: Method::Get,
form_fields: HashMap::new(),
}
}
}
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
}
}
TokenioPaymentsResponse::Error(error_response) => Err(ErrorResponse {
code: error_response.get_error_code(),
message: error_response.get_message(),
reason: Some(error_response.get_message()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct TokenioRefundRequest {
pub amount: StringMajorUnit,
}
impl<F> TryFrom<&TokenioRouterData<&RefundsRouterData<F>>> for TokenioRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &TokenioRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(untagged)]
pub enum TokenioErrorResponse {
Json {
#[serde(rename = "errorCode")]
error_code: Option<String>,
message: Option<String>,
},
Text(String),
}
impl TokenioErrorResponse {
pub fn from_bytes(bytes: &[u8]) -> Self {
// First try to parse as JSON
if let Ok(json_response) = serde_json::from_slice::<Self>(bytes) {
json_response
} else {
// If JSON parsing fails, treat as plain text
let text = String::from_utf8_lossy(bytes).to_string();
Self::Text(text)
}
}
pub fn get_message(&self) -> String {
match self {
Self::Json {
message,
error_code,
} => message
.as_deref()
.or(error_code.as_deref())
.unwrap_or(NO_ERROR_MESSAGE)
.to_string(),
Self::Text(text) => text.clone(),
}
}
pub fn get_error_code(&self) -> String {
match self {
Self::Json { error_code, .. } => {
error_code.as_deref().unwrap_or(NO_ERROR_CODE).to_string()
}
Self::Text(_) => NO_ERROR_CODE.to_string(),
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TokenioWebhookEventType {
PaymentStatusChanged,
#[serde(other)]
Unknown,
}
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TokenioWebhookPaymentStatus {
InitiationCompleted,
PaymentCompleted,
PaymentFailed,
PaymentCancelled,
InitiationRejected,
InitiationProcessing,
#[serde(other)]
Unknown,
}
// Base webhook payload structure
#[derive(Debug, Deserialize, Serialize)]
pub struct TokenioWebhookPayload {
#[serde(rename = "eventType", skip_serializing_if = "Option::is_none")]
pub event_type: Option<String>,
pub id: String,
#[serde(flatten)]
pub event_data: TokenioWebhookEventData,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum TokenioWebhookEventData {
PaymentV2 { payment: TokenioPaymentObjectV2 },
}
// Payment v2 structures
#[derive(Debug, Deserialize, Serialize)]
pub struct TokenioPaymentObjectV2 {
pub id: String,
pub status: TokenioPaymentStatus,
}
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TokenioPaymentStatus {
InitiationCompleted,
PaymentCompleted,
PaymentFailed,
PaymentCancelled,
InitiationRejected,
InitiationProcessing,
InitiationPendingRedirectHp,
#[serde(other)]
Other,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs | crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs | use common_enums::{enums, CountryAlpha2, UsStatesAbbreviation};
use common_utils::{
id_type,
pii::{self, IpAddress},
types::MinorUnit,
};
use hyperswitch_domain_models::{
address::AddressDetails,
payment_method_data::{BankDebitData, PaymentMethodData},
router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
router_flow_types::refunds::Execute,
router_request_types::{
ConnectorCustomerData, PaymentMethodTokenizationData, ResponseId, SetupMandateRequestData,
},
router_response_types::{
ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, RefundsResponseData,
},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
ResponseRouterData,
},
utils::{
self, AddressDetailsData, BrowserInformationData, CustomerData, ForeignTryFrom,
PaymentsAuthorizeRequestData, PaymentsSetupMandateRequestData, RouterData as _,
},
};
pub struct GocardlessRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for GocardlessRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct GocardlessCustomerRequest {
customers: GocardlessCustomer,
}
#[derive(Default, Debug, Serialize)]
pub struct GocardlessCustomer {
address_line1: Option<Secret<String>>,
address_line2: Option<Secret<String>>,
address_line3: Option<Secret<String>>,
city: Option<Secret<String>>,
region: Option<Secret<String>>,
country_code: Option<CountryAlpha2>,
email: pii::Email,
given_name: Secret<String>,
family_name: Secret<String>,
metadata: CustomerMetaData,
danish_identity_number: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
swedish_identity_number: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize)]
pub struct CustomerMetaData {
crm_id: Option<Secret<id_type::CustomerId>>,
}
impl TryFrom<&types::ConnectorCustomerRouterData> for GocardlessCustomerRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> {
let email = item.request.get_email()?;
let billing_details_name = item.get_billing_full_name()?.expose();
let (given_name, family_name) = billing_details_name
.trim()
.rsplit_once(' ')
.unwrap_or((&billing_details_name, &billing_details_name));
let billing_address = item.get_billing_address()?;
let metadata = CustomerMetaData {
crm_id: item.customer_id.clone().map(Secret::new),
};
let region = get_region(billing_address)?;
Ok(Self {
customers: GocardlessCustomer {
email,
given_name: Secret::new(given_name.to_string()),
family_name: Secret::new(family_name.to_string()),
metadata,
address_line1: billing_address.line1.to_owned(),
address_line2: billing_address.line2.to_owned(),
address_line3: billing_address.line3.to_owned(),
country_code: billing_address.country,
region,
// Should be populated based on the billing country
danish_identity_number: None,
postal_code: billing_address.zip.to_owned(),
// Should be populated based on the billing country
swedish_identity_number: None,
city: billing_address.city.clone().map(Secret::new),
},
})
}
}
fn get_region(
address_details: &AddressDetails,
) -> Result<Option<Secret<String>>, error_stack::Report<errors::ConnectorError>> {
match address_details.country {
Some(CountryAlpha2::US) => {
let state = address_details.get_state()?.to_owned();
Ok(Some(Secret::new(
UsStatesAbbreviation::foreign_try_from(state.expose())?.to_string(),
)))
}
_ => Ok(None),
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GocardlessCustomerResponse {
customers: Customers,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Customers {
id: Secret<String>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
GocardlessCustomerResponse,
ConnectorCustomerData,
PaymentsResponseData,
>,
> for RouterData<F, ConnectorCustomerData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
GocardlessCustomerResponse,
ConnectorCustomerData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(
item.response.customers.id.expose(),
),
)),
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct GocardlessBankAccountRequest {
customer_bank_accounts: CustomerBankAccounts,
}
#[derive(Debug, Serialize)]
pub struct CustomerBankAccounts {
#[serde(flatten)]
accounts: CustomerBankAccount,
links: CustomerAccountLink,
}
#[derive(Debug, Serialize)]
pub struct CustomerAccountLink {
customer: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum CustomerBankAccount {
InternationalBankAccount(InternationalBankAccount),
AUBankAccount(AUBankAccount),
USBankAccount(USBankAccount),
}
#[derive(Debug, Serialize)]
pub struct InternationalBankAccount {
iban: Secret<String>,
account_holder_name: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct AUBankAccount {
country_code: CountryAlpha2,
account_number: Secret<String>,
branch_code: Secret<String>,
account_holder_name: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub struct USBankAccount {
country_code: CountryAlpha2,
account_number: Secret<String>,
bank_code: Secret<String>,
account_type: AccountType,
account_holder_name: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AccountType {
Checking,
Savings,
}
impl TryFrom<&types::TokenizationRouterData> for GocardlessBankAccountRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
let customer = item.get_connector_customer_id()?;
let accounts = CustomerBankAccount::try_from(item)?;
let links = CustomerAccountLink {
customer: Secret::new(customer),
};
Ok(Self {
customer_bank_accounts: CustomerBankAccounts { accounts, links },
})
}
}
impl TryFrom<&types::TokenizationRouterData> for CustomerBankAccount {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
match &item.request.payment_method_data {
PaymentMethodData::BankDebit(bank_debit_data) => {
Self::try_from((bank_debit_data, item))
}
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Gocardless"),
)
.into())
}
}
}
}
impl TryFrom<(&BankDebitData, &types::TokenizationRouterData)> for CustomerBankAccount {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(bank_debit_data, item): (&BankDebitData, &types::TokenizationRouterData),
) -> Result<Self, Self::Error> {
match bank_debit_data {
BankDebitData::AchBankDebit {
account_number,
routing_number,
bank_type,
..
} => {
let bank_type = bank_type.ok_or_else(utils::missing_field_err("bank_type"))?;
let country_code = item.get_billing_country()?;
let account_holder_name = item.get_billing_full_name()?;
let us_bank_account = USBankAccount {
country_code,
account_number: account_number.clone(),
bank_code: routing_number.clone(),
account_type: AccountType::from(bank_type),
account_holder_name,
};
Ok(Self::USBankAccount(us_bank_account))
}
BankDebitData::BecsBankDebit {
account_number,
bsb_number,
..
} => {
let country_code = item.get_billing_country()?;
let account_holder_name = item.get_billing_full_name()?;
let au_bank_account = AUBankAccount {
country_code,
account_number: account_number.clone(),
branch_code: bsb_number.clone(),
account_holder_name,
};
Ok(Self::AUBankAccount(au_bank_account))
}
BankDebitData::SepaBankDebit { iban, .. } => {
let account_holder_name = item.get_billing_full_name()?;
let international_bank_account = InternationalBankAccount {
iban: iban.clone(),
account_holder_name,
};
Ok(Self::InternationalBankAccount(international_bank_account))
}
BankDebitData::BacsBankDebit { .. } | BankDebitData::SepaGuarenteedBankDebit { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Gocardless"),
)
.into())
}
}
}
}
impl From<common_enums::BankType> for AccountType {
fn from(item: common_enums::BankType) -> Self {
match item {
common_enums::BankType::Checking => Self::Checking,
common_enums::BankType::Savings => Self::Savings,
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GocardlessBankAccountResponse {
customer_bank_accounts: CustomerBankAccountResponse,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CustomerBankAccountResponse {
pub id: Secret<String>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
GocardlessBankAccountResponse,
PaymentMethodTokenizationData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentMethodTokenizationData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
GocardlessBankAccountResponse,
PaymentMethodTokenizationData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.customer_bank_accounts.id.expose(),
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct GocardlessMandateRequest {
mandates: Mandate,
}
#[derive(Debug, Serialize)]
pub struct Mandate {
scheme: GocardlessScheme,
metadata: MandateMetaData,
payer_ip_address: Option<Secret<String, IpAddress>>,
links: MandateLink,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum GocardlessScheme {
Becs,
SepaCore,
Ach,
BecsNz,
}
#[derive(Debug, Serialize)]
pub struct MandateMetaData {
payment_reference: String,
}
#[derive(Debug, Serialize)]
pub struct MandateLink {
customer_bank_account: Secret<String>,
}
impl TryFrom<&types::SetupMandateRouterData> for GocardlessMandateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> {
let (scheme, payer_ip_address) = match &item.request.payment_method_data {
PaymentMethodData::BankDebit(bank_debit_data) => {
let payer_ip_address = get_ip_if_required(bank_debit_data, item)?;
Ok((
GocardlessScheme::try_from(bank_debit_data)?,
payer_ip_address,
))
}
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
"Setup Mandate flow for selected payment method through Gocardless".to_string(),
))
}
}?;
let payment_method_token = item.get_payment_method_token()?;
let customer_bank_account = match payment_method_token {
PaymentMethodToken::Token(token) => Ok(token),
PaymentMethodToken::ApplePayDecrypt(_)
| PaymentMethodToken::PazeDecrypt(_)
| PaymentMethodToken::GooglePayDecrypt(_) => {
Err(errors::ConnectorError::NotImplemented(
"Setup Mandate flow for selected payment method through Gocardless".to_string(),
))
}
}?;
Ok(Self {
mandates: Mandate {
scheme,
metadata: MandateMetaData {
payment_reference: item.connector_request_reference_id.clone(),
},
payer_ip_address,
links: MandateLink {
customer_bank_account,
},
},
})
}
}
fn get_ip_if_required(
bank_debit_data: &BankDebitData,
item: &types::SetupMandateRouterData,
) -> Result<Option<Secret<String, IpAddress>>, error_stack::Report<errors::ConnectorError>> {
let ip_address = item.request.get_browser_info()?.get_ip_address()?;
match bank_debit_data {
BankDebitData::AchBankDebit { .. } => Ok(Some(ip_address)),
BankDebitData::SepaBankDebit { .. }
| BankDebitData::SepaGuarenteedBankDebit { .. }
| BankDebitData::BecsBankDebit { .. }
| BankDebitData::BacsBankDebit { .. } => Ok(None),
}
}
impl TryFrom<&BankDebitData> for GocardlessScheme {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &BankDebitData) -> Result<Self, Self::Error> {
match item {
BankDebitData::AchBankDebit { .. } => Ok(Self::Ach),
BankDebitData::SepaBankDebit { .. } => Ok(Self::SepaCore),
BankDebitData::BecsBankDebit { .. } => Ok(Self::Becs),
BankDebitData::BacsBankDebit { .. } | BankDebitData::SepaGuarenteedBankDebit { .. } => {
Err(errors::ConnectorError::NotImplemented(
"Setup Mandate flow for selected payment method through Gocardless".to_string(),
)
.into())
}
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GocardlessMandateResponse {
mandates: MandateResponse,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MandateResponse {
id: Secret<String>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
GocardlessMandateResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
> for RouterData<F, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
GocardlessMandateResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let mandate_reference = Some(MandateReference {
connector_mandate_id: Some(item.response.mandates.id.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
connector_metadata: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
network_txn_id: None,
charges: None,
}),
status: enums::AttemptStatus::Charged,
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct GocardlessPaymentsRequest {
payments: GocardlessPayment,
}
#[derive(Debug, Serialize)]
pub struct GocardlessPayment {
amount: MinorUnit,
currency: enums::Currency,
description: Option<String>,
metadata: PaymentMetaData,
links: PaymentLink,
}
#[derive(Debug, Serialize)]
pub struct PaymentMetaData {
payment_reference: String,
}
#[derive(Debug, Serialize)]
pub struct PaymentLink {
mandate: Secret<String>,
}
impl TryFrom<&GocardlessRouterData<&types::PaymentsAuthorizeRouterData>>
for GocardlessPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &GocardlessRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let mandate_id = if item.router_data.request.is_mandate_payment() {
item.router_data
.request
.connector_mandate_id()
.ok_or_else(utils::missing_field_err("mandate_id"))
} else {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("gocardless"),
)
.into())
}?;
let payments = GocardlessPayment {
amount: item.router_data.request.minor_amount,
currency: item.router_data.request.currency,
description: item.router_data.description.clone(),
metadata: PaymentMetaData {
payment_reference: item.router_data.connector_request_reference_id.clone(),
},
links: PaymentLink {
mandate: Secret::new(mandate_id),
},
};
Ok(Self { payments })
}
}
// Auth Struct
pub struct GocardlessAuthType {
pub(super) access_token: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for GocardlessAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
access_token: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GocardlessPaymentStatus {
PendingCustomerApproval,
PendingSubmission,
Submitted,
Confirmed,
PaidOut,
Cancelled,
CustomerApprovalDenied,
Failed,
}
impl From<GocardlessPaymentStatus> for enums::AttemptStatus {
fn from(item: GocardlessPaymentStatus) -> Self {
match item {
GocardlessPaymentStatus::PendingCustomerApproval
| GocardlessPaymentStatus::PendingSubmission
| GocardlessPaymentStatus::Submitted => Self::Pending,
GocardlessPaymentStatus::Confirmed | GocardlessPaymentStatus::PaidOut => Self::Charged,
GocardlessPaymentStatus::Cancelled => Self::Voided,
GocardlessPaymentStatus::CustomerApprovalDenied => Self::AuthenticationFailed,
GocardlessPaymentStatus::Failed => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GocardlessPaymentsResponse {
payments: PaymentResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentResponse {
status: GocardlessPaymentStatus,
id: String,
}
impl TryFrom<PaymentsResponseRouterData<GocardlessPaymentsResponse>>
for types::PaymentsAuthorizeRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<GocardlessPaymentsResponse>,
) -> Result<Self, Self::Error> {
let mandate_reference = MandateReference {
connector_mandate_id: Some(item.data.request.get_connector_mandate_id()?),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
};
Ok(Self {
status: enums::AttemptStatus::from(item.response.payments.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.payments.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(Some(mandate_reference)),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<GocardlessPaymentsResponse>>
for types::PaymentsSyncRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<GocardlessPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.payments.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.payments.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
#[derive(Default, Debug, Serialize)]
pub struct GocardlessRefundRequest {
refunds: GocardlessRefund,
}
#[derive(Default, Debug, Serialize)]
pub struct GocardlessRefund {
amount: MinorUnit,
metadata: RefundMetaData,
links: RefundLink,
}
#[derive(Default, Debug, Serialize)]
pub struct RefundMetaData {
refund_reference: String,
}
#[derive(Default, Debug, Serialize)]
pub struct RefundLink {
payment: String,
}
impl<F> TryFrom<&GocardlessRouterData<&types::RefundsRouterData<F>>> for GocardlessRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &GocardlessRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
refunds: GocardlessRefund {
amount: item.amount.to_owned(),
metadata: RefundMetaData {
refund_reference: item.router_data.connector_request_reference_id.clone(),
},
links: RefundLink {
payment: item.router_data.request.connector_transaction_id.clone(),
},
},
})
}
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
id: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::Pending,
}),
..item.data
})
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GocardlessErrorResponse {
pub error: GocardlessError,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GocardlessError {
pub message: String,
pub code: u16,
pub errors: Vec<Error>,
#[serde(rename = "type")]
pub error_type: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Error {
pub field: Option<String>,
pub message: String,
}
#[derive(Debug, Deserialize)]
pub struct GocardlessWebhookEvent {
pub events: Vec<WebhookEvent>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WebhookEvent {
pub resource_type: WebhookResourceType,
pub action: WebhookAction,
pub links: WebhooksLink,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WebhookResourceType {
Payments,
Refunds,
Mandates,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum WebhookAction {
PaymentsAction(PaymentsAction),
RefundsAction(RefundsAction),
MandatesAction(MandatesAction),
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PaymentsAction {
Created,
CustomerApprovalGranted,
CustomerApprovalDenied,
Submitted,
Confirmed,
PaidOut,
LateFailureSettled,
SurchargeFeeDebited,
Failed,
Cancelled,
ResubmissionRequired,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RefundsAction {
Created,
Failed,
Paid,
// Payout statuses
RefundSettled,
FundsReturned,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MandatesAction {
Created,
CustomerApprovalGranted,
CustomerApprovalSkipped,
Active,
Cancelled,
Failed,
Transferred,
Expired,
Submitted,
ResubmissionRequested,
Reinstated,
Replaced,
Consumed,
Blocked,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum WebhooksLink {
PaymentWebhooksLink(PaymentWebhooksLink),
RefundWebhookLink(RefundWebhookLink),
MandateWebhookLink(MandateWebhookLink),
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RefundWebhookLink {
pub refund: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PaymentWebhooksLink {
pub payment: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct MandateWebhookLink {
pub mandate: String,
}
impl TryFrom<&WebhookEvent> for GocardlessPaymentsResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &WebhookEvent) -> Result<Self, Self::Error> {
let id = match &item.links {
WebhooksLink::PaymentWebhooksLink(link) => link.payment.to_owned(),
WebhooksLink::RefundWebhookLink(_) | WebhooksLink::MandateWebhookLink(_) => {
Err(errors::ConnectorError::WebhookEventTypeNotFound)?
}
};
Ok(Self {
payments: PaymentResponse {
status: GocardlessPaymentStatus::try_from(&item.action)?,
id,
},
})
}
}
impl TryFrom<&WebhookAction> for GocardlessPaymentStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &WebhookAction) -> Result<Self, Self::Error> {
match item {
WebhookAction::PaymentsAction(action) => match action {
PaymentsAction::CustomerApprovalGranted | PaymentsAction::Submitted => {
Ok(Self::Submitted)
}
PaymentsAction::CustomerApprovalDenied => Ok(Self::CustomerApprovalDenied),
PaymentsAction::LateFailureSettled => Ok(Self::Failed),
PaymentsAction::Failed => Ok(Self::Failed),
PaymentsAction::Cancelled => Ok(Self::Cancelled),
PaymentsAction::Confirmed => Ok(Self::Confirmed),
PaymentsAction::PaidOut => Ok(Self::PaidOut),
PaymentsAction::SurchargeFeeDebited
| PaymentsAction::ResubmissionRequired
| PaymentsAction::Created => Err(errors::ConnectorError::WebhookEventTypeNotFound)?,
},
WebhookAction::RefundsAction(_) | WebhookAction::MandatesAction(_) => {
Err(errors::ConnectorError::WebhookEventTypeNotFound)?
}
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/breadpay/transformers.rs | crates/hyperswitch_connectors/src/connectors/breadpay/transformers.rs | use common_enums::enums;
use common_utils::{request::Method, types::StringMinorUnit};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, PaymentsAuthorizeRequestData},
};
pub struct BreadpayRouterData<T> {
pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for BreadpayRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BreadpayCartRequest {
custom_total: StringMinorUnit,
options: Option<BreadpayCartOptions>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BreadpayCartOptions {
order_ref: Option<String>,
complete_url: String,
callback_url: String,
// billing_contact: Option<BillingContact>,
}
// #[derive(Debug, Serialize)]
// #[serde(rename_all = "camelCase")]
// pub struct BillingContact {
// first_name: Secret<String>,
// last_name: Secret<String>,
// email: Option<Email>,
// address: Secret<String>,
// city: Secret<String>,
// state: Secret<String>,
// }
impl TryFrom<&BreadpayRouterData<&PaymentsAuthorizeRouterData>> for BreadpayCartRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BreadpayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let request = match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::PayLater(pay_later_data) => match pay_later_data{
hyperswitch_domain_models::payment_method_data::PayLaterData::BreadpayRedirect { } => {
// let billing_contact = BillingContact {
// first_name: item.router_data.get_billing_first_name()?,
// last_name: item.router_data.get_billing_last_name()?,
// email: item.router_data.get_optional_billing_email(),
// address: item.router_data.get_billing_line1()?,
// city: item.router_data.get_billing_city()?.into(),
// state: item.router_data.get_billing_state()?,
// };
let options = Some({
BreadpayCartOptions {
order_ref: item.router_data.request.merchant_order_reference_id.clone(),
complete_url: item.router_data.request.get_complete_authorize_url()?,
callback_url: item.router_data.request.get_router_return_url()?
// billing_contact: Some(billing_contact)
}
});
Self{
custom_total: item.amount.clone(),
options,
}
},
hyperswitch_domain_models::payment_method_data::PayLaterData::KlarnaRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::WalleyRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::KlarnaSdk { .. } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AffirmRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::FlexitiRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AfterpayClearpayRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::PayBrightRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AlmaRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AtomeRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::PayjustnowRedirect { } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("breadpay"),
))
}?,
},
PaymentMethodData::Card(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(
_,
)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::MobilePayment(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("breadpay"),
))
}?
};
Ok(request)
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BreadpayTransactionRequest {
#[serde(rename = "type")]
pub transaction_type: BreadpayTransactionType,
}
#[derive(Debug, Serialize)]
pub enum BreadpayTransactionType {
Authorize,
Settle,
Cancel,
Refund,
}
// Auth Struct
pub struct BreadpayAuthType {
pub(super) api_key: Secret<String>,
pub(super) api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BreadpayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
api_secret: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BreadpayTransactionResponse {
status: TransactionStatus,
bread_transactin_id: String,
merchant_order_id: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionStatus {
Pending,
Canceled,
Refunded,
Expired,
Authorized,
Settled,
}
impl<F, T> TryFrom<ResponseRouterData<F, BreadpayTransactionResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BreadpayTransactionResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.bread_transactin_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl From<TransactionStatus> for enums::AttemptStatus {
fn from(item: TransactionStatus) -> Self {
match item {
TransactionStatus::Pending => Self::Pending,
TransactionStatus::Authorized => Self::Authorized,
TransactionStatus::Canceled => Self::Voided,
TransactionStatus::Refunded => Self::AutoRefunded,
TransactionStatus::Expired => Self::Failure,
TransactionStatus::Settled => Self::Charged,
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BreadpayPaymentsResponse {
url: url::Url,
}
impl<F, T> TryFrom<ResponseRouterData<F, BreadpayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BreadpayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
// As per documentation, the first call is cart creation where we don't get any status only get the customer redirection url.
status: common_enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::from((
item.response.url,
Method::Get,
)))),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CallBackResponse {
pub transaction_id: String,
pub order_ref: String,
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
pub struct BreadpayRefundRequest {
pub amount: StringMinorUnit,
#[serde(rename = "type")]
pub transaction_type: BreadpayTransactionType,
}
impl<F> TryFrom<&BreadpayRouterData<&RefundsRouterData<F>>> for BreadpayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &BreadpayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
transaction_type: BreadpayTransactionType::Refund,
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BreadpayErrorResponse {
/// Human-readable error description
pub description: String,
/// Error type classification
#[serde(rename = "type")]
pub error_type: String,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs | crates/hyperswitch_connectors/src/connectors/silverflow/transformers.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::{
payments::Void,
refunds::{Execute, RSync},
},
router_request_types::{PaymentsCancelData, ResponseId},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, CardData},
};
//TODO: Fill the struct with respective fields
pub struct SilverflowRouterData<T> {
pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for SilverflowRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
}
}
}
// Basic structures for Silverflow API
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Amount {
value: MinorUnit,
currency: String,
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Card {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
holder_name: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MerchantAcceptorResolver {
merchant_acceptor_key: String,
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowPaymentsRequest {
merchant_acceptor_resolver: MerchantAcceptorResolver,
card: Card,
amount: Amount,
#[serde(rename = "type")]
payment_type: PaymentType,
clearing_mode: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentType {
intent: String,
card_entry: String,
order: String,
}
impl TryFrom<&SilverflowRouterData<&PaymentsAuthorizeRouterData>> for SilverflowPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &SilverflowRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
// Check if 3DS is being requested - Silverflow doesn't support 3DS
if matches!(
item.router_data.auth_type,
enums::AuthenticationType::ThreeDs
) {
return Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("silverflow"),
)
.into());
}
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
// Extract merchant acceptor key from connector auth
let auth = SilverflowAuthType::try_from(&item.router_data.connector_auth_type)?;
let card = Card {
number: req_card.card_number.clone(),
expiry_month: req_card.card_exp_month.clone(),
expiry_year: req_card.card_exp_year.clone(),
cvc: req_card.card_cvc.clone(),
holder_name: req_card.get_cardholder_name().ok(),
};
// Determine clearing mode based on capture method
let clearing_mode = match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual) => "manual".to_string(),
Some(enums::CaptureMethod::Automatic) | None => "auto".to_string(),
Some(enums::CaptureMethod::ManualMultiple)
| Some(enums::CaptureMethod::Scheduled)
| Some(enums::CaptureMethod::SequentialAutomatic) => {
return Err(errors::ConnectorError::NotSupported {
message: "Capture method not supported by Silverflow".to_string(),
connector: "Silverflow",
}
.into());
}
};
Ok(Self {
merchant_acceptor_resolver: MerchantAcceptorResolver {
merchant_acceptor_key: auth.merchant_acceptor_key.expose(),
},
card,
amount: Amount {
value: item.amount,
currency: item.router_data.request.currency.to_string(),
},
payment_type: PaymentType {
intent: "purchase".to_string(),
card_entry: "e-commerce".to_string(),
order: "checkout".to_string(),
},
clearing_mode,
})
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("silverflow"),
)
.into()),
}
}
}
// Auth Struct for HTTP Basic Authentication
pub struct SilverflowAuthType {
pub(super) api_key: Secret<String>,
pub(super) api_secret: Secret<String>,
pub(super) merchant_acceptor_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for SilverflowAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
api_key: api_key.clone(),
api_secret: api_secret.clone(),
merchant_acceptor_key: key1.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// Enum for Silverflow payment authorization status
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SilverflowAuthorizationStatus {
Approved,
Declined,
Failed,
#[default]
Pending,
}
// Enum for Silverflow payment clearing status
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SilverflowClearingStatus {
Cleared,
#[default]
Pending,
Failed,
}
// Payment Authorization Response Structures
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PaymentStatus {
pub authentication: String,
pub authorization: SilverflowAuthorizationStatus,
pub clearing: SilverflowClearingStatus,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct MerchantAcceptorRef {
pub key: String,
pub version: i32,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CardResponse {
pub masked_number: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Authentication {
pub sca: SCA,
pub cvc: Secret<String>,
pub avs: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SCA {
pub compliance: String,
pub compliance_reason: String,
pub method: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<SCAResult>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SCAResult {
pub version: String,
pub directory_server_trans_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizationIsoFields {
pub response_code: String,
pub response_code_description: String,
pub authorization_code: String,
pub network_code: String,
pub system_trace_audit_number: Secret<String>,
pub retrieval_reference_number: String,
pub eci: String,
pub network_specific_fields: NetworkSpecificFields,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct NetworkSpecificFields {
pub transaction_identifier: String,
pub cvv2_result_code: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowPaymentsResponse {
pub key: String,
pub merchant_acceptor_ref: MerchantAcceptorRef,
pub card: CardResponse,
pub amount: Amount,
#[serde(rename = "type")]
pub payment_type: PaymentType,
pub clearing_mode: String,
pub status: PaymentStatus,
pub authentication: Authentication,
pub local_transaction_date_time: String,
pub fraud_liability: String,
pub authorization_iso_fields: Option<AuthorizationIsoFields>,
pub created: String,
pub version: i32,
}
impl From<&PaymentStatus> for common_enums::AttemptStatus {
fn from(status: &PaymentStatus) -> Self {
match (&status.authorization, &status.clearing) {
(SilverflowAuthorizationStatus::Approved, SilverflowClearingStatus::Cleared) => {
Self::Charged
}
(SilverflowAuthorizationStatus::Approved, SilverflowClearingStatus::Pending) => {
Self::Authorized
}
(SilverflowAuthorizationStatus::Approved, SilverflowClearingStatus::Failed) => {
Self::Failure
}
(SilverflowAuthorizationStatus::Declined, _) => Self::Failure,
(SilverflowAuthorizationStatus::Failed, _) => Self::Failure,
(SilverflowAuthorizationStatus::Pending, _) => Self::Pending,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, SilverflowPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SilverflowPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(&item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.key.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: item
.response
.authorization_iso_fields
.as_ref()
.map(|fields| {
fields
.network_specific_fields
.transaction_identifier
.clone()
}),
connector_response_reference_id: Some(item.response.key.clone()),
incremental_authorization_allowed: Some(false),
charges: None,
}),
..item.data
})
}
}
// CAPTURE:
// Type definition for CaptureRequest based on Silverflow API documentation
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowCaptureRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub close_charge: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reference: Option<String>,
}
impl TryFrom<&PaymentsCaptureRouterData> for SilverflowCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
// amount_to_capture is directly an i64, representing the amount in minor units
let amount_to_capture = Some(item.request.amount_to_capture);
Ok(Self {
amount: amount_to_capture,
close_charge: Some(true), // Default to closing charge after capture
reference: Some(format!("capture-{}", item.payment_id)),
})
}
}
// Enum for Silverflow capture status
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SilverflowCaptureStatus {
Completed,
#[default]
Pending,
Failed,
}
// Type definition for CaptureResponse based on Silverflow clearing action response
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowCaptureResponse {
#[serde(rename = "type")]
pub action_type: String,
pub key: String,
pub charge_key: String,
pub status: SilverflowCaptureStatus,
#[serde(skip_serializing_if = "Option::is_none")]
pub reference: Option<String>,
pub amount: Amount,
pub created: String,
pub last_modified: String,
pub version: i32,
}
impl From<&SilverflowCaptureResponse> for common_enums::AttemptStatus {
fn from(response: &SilverflowCaptureResponse) -> Self {
match response.status {
SilverflowCaptureStatus::Completed => Self::Charged,
SilverflowCaptureStatus::Pending => Self::Pending,
SilverflowCaptureStatus::Failed => Self::Failure,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, SilverflowCaptureResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SilverflowCaptureResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(&item.response),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.charge_key.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.key.clone()),
incremental_authorization_allowed: Some(false),
charges: None,
}),
..item.data
})
}
}
// VOID/REVERSE:
// Type definition for Reverse Charge Request based on Silverflow API documentation
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowVoidRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub replacement_amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reference: Option<String>,
}
impl TryFrom<&RouterData<Void, PaymentsCancelData, PaymentsResponseData>>
for SilverflowVoidRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
replacement_amount: Some(0), // Default to 0 for full reversal
reference: Some(format!("void-{}", item.payment_id)),
})
}
}
// Enum for Silverflow void authorization status
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SilverflowVoidAuthorizationStatus {
Approved,
Declined,
Failed,
#[default]
Pending,
}
// Type definition for Void Status (only authorization, no clearing)
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct VoidStatus {
pub authorization: SilverflowVoidAuthorizationStatus,
}
// Type definition for Reverse Charge Response based on Silverflow API documentation
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowVoidResponse {
#[serde(rename = "type")]
pub action_type: String,
pub key: String,
pub charge_key: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub reference: Option<String>,
pub replacement_amount: Amount,
pub status: VoidStatus,
pub authorization_response: Option<AuthorizationResponse>,
pub created: String,
pub last_modified: String,
pub version: i32,
}
impl From<&SilverflowVoidResponse> for common_enums::AttemptStatus {
fn from(response: &SilverflowVoidResponse) -> Self {
match response.status.authorization {
SilverflowVoidAuthorizationStatus::Approved => Self::Voided,
SilverflowVoidAuthorizationStatus::Declined
| SilverflowVoidAuthorizationStatus::Failed => Self::VoidFailed,
SilverflowVoidAuthorizationStatus::Pending => Self::Pending,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, SilverflowVoidResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SilverflowVoidResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(&item.response),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.charge_key.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.key.clone()),
incremental_authorization_allowed: Some(false),
charges: None,
}),
..item.data
})
}
}
// REFUND :
// Type definition for DynamicDescriptor
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DynamicDescriptor {
pub merchant_name: String,
pub merchant_city: String,
}
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct SilverflowRefundRequest {
#[serde(rename = "refundAmount")]
pub refund_amount: MinorUnit,
pub reference: String,
}
impl<F> TryFrom<&SilverflowRouterData<&RefundsRouterData<F>>> for SilverflowRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SilverflowRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
refund_amount: item.amount,
reference: format!("refund-{}", item.router_data.request.refund_id),
})
}
}
// Type definition for Authorization Response
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizationResponse {
pub network: String,
pub response_code: String,
pub response_code_description: String,
}
// Enum for Silverflow refund authorization status
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SilverflowRefundAuthorizationStatus {
Approved,
Declined,
Failed,
Pending,
}
// Enum for Silverflow refund status
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SilverflowRefundStatus {
Success,
Failure,
#[default]
Pending,
}
impl From<&SilverflowRefundStatus> for enums::RefundStatus {
fn from(item: &SilverflowRefundStatus) -> Self {
match item {
SilverflowRefundStatus::Success => Self::Success,
SilverflowRefundStatus::Failure => Self::Failure,
SilverflowRefundStatus::Pending => Self::Pending,
}
}
}
// Type definition for Refund Response
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
#[serde(rename = "type")]
pub action_type: String,
pub key: String,
pub charge_key: String,
pub reference: String,
pub amount: Amount,
pub status: SilverflowRefundStatus,
pub clear_after: Option<String>,
pub authorization_response: Option<AuthorizationResponse>,
pub created: String,
pub last_modified: String,
pub version: i32,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.key.clone(),
refund_status: enums::RefundStatus::from(&item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.key.clone(),
refund_status: enums::RefundStatus::from(&item.response.status),
}),
..item.data
})
}
}
// TOKENIZATION:
// Type definition for TokenizationRequest
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowTokenizationRequest {
pub reference: String,
pub card_data: SilverflowCardData,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowCardData {
pub number: String,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
pub cvc: String,
pub holder_name: String,
}
impl TryFrom<&PaymentsAuthorizeRouterData> for SilverflowTokenizationRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card_data = SilverflowCardData {
number: req_card.card_number.peek().to_string(),
expiry_month: req_card.card_exp_month.clone(),
expiry_year: req_card.card_exp_year.clone(),
cvc: req_card.card_cvc.clone().expose(),
holder_name: req_card
.get_cardholder_name()
.unwrap_or(Secret::new("".to_string()))
.expose(),
};
Ok(Self {
reference: format!("CUSTOMER_ID_{}", item.payment_id),
card_data,
})
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("silverflow"),
)
.into()),
}
}
}
// Add TryFrom implementation for direct tokenization router data
impl
TryFrom<
&RouterData<
hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken,
hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData,
PaymentsResponseData,
>,
> for SilverflowTokenizationRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RouterData<
hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken,
hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card_data = SilverflowCardData {
number: req_card.card_number.peek().to_string(),
expiry_month: req_card.card_exp_month.clone(),
expiry_year: req_card.card_exp_year.clone(),
cvc: req_card.card_cvc.clone().expose(),
holder_name: req_card
.get_cardholder_name()
.unwrap_or(Secret::new("".to_string()))
.expose(),
};
Ok(Self {
reference: format!("CUSTOMER_ID_{}", item.payment_id),
card_data,
})
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("silverflow"),
)
.into()),
}
}
}
// Type definition for TokenizationResponse
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SilverflowTokenizationResponse {
pub key: String,
#[serde(rename = "agentKey")]
pub agent_key: String,
pub last4: String,
pub status: String,
pub reference: String,
#[serde(rename = "cardInfo")]
pub card_info: Vec<CardInfo>,
pub created: String,
#[serde(rename = "cvcPresent")]
pub cvc_present: bool,
pub version: i32,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CardInfo {
#[serde(rename = "infoSource")]
pub info_source: String,
pub network: String,
#[serde(rename = "primaryNetwork")]
pub primary_network: bool,
}
impl<F, T> TryFrom<ResponseRouterData<F, SilverflowTokenizationResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SilverflowTokenizationResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.key,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCardDetails {
pub masked_card_number: String,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
pub card_brand: String,
}
// WEBHOOKS:
// Type definition for Webhook Event structures
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowWebhookEvent {
pub event_type: String,
pub event_data: SilverflowWebhookEventData,
pub event_id: String,
pub created: String,
pub version: i32,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SilverflowWebhookEventData {
pub charge_key: Option<String>,
pub refund_key: Option<String>,
pub status: Option<PaymentStatus>,
pub amount: Option<Amount>,
pub transaction_reference: Option<String>,
}
// Error Response Structures based on Silverflow API format
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct ErrorDetails {
pub field: String,
pub issue: String,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct SilverflowErrorResponse {
pub error: SilverflowError,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct SilverflowError {
pub code: String,
pub message: String,
pub details: Option<ErrorDetails>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/envoy/transformers.rs | crates/hyperswitch_connectors/src/connectors/envoy/transformers.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};
//TODO: Fill the struct with respective fields
pub struct EnvoyRouterData<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 EnvoyRouterData<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 EnvoyPaymentsRequest {
amount: StringMinorUnit,
card: EnvoyCard,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct EnvoyCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&EnvoyRouterData<&PaymentsAuthorizeRouterData>> for EnvoyPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &EnvoyRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
"Card payment method not implemented".to_string(),
)
.into()),
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
//TODO: Fill the struct with respective fields
// Auth Struct
pub struct EnvoyAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for EnvoyAuthType {
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, Copy, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum EnvoyPaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<EnvoyPaymentStatus> for common_enums::AttemptStatus {
fn from(item: EnvoyPaymentStatus) -> Self {
match item {
EnvoyPaymentStatus::Succeeded => Self::Charged,
EnvoyPaymentStatus::Failed => Self::Failure,
EnvoyPaymentStatus::Processing => Self::Authorizing,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct EnvoyPaymentsResponse {
status: EnvoyPaymentStatus,
id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, EnvoyPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, EnvoyPaymentsResponse, 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 EnvoyRefundRequest {
pub amount: StringMinorUnit,
}
impl<F> TryFrom<&EnvoyRouterData<&RefundsRouterData<F>>> for EnvoyRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &EnvoyRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct EnvoyErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
pub network_advice_code: Option<String>,
pub network_decline_code: Option<String>,
pub network_error_message: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs | crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.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,
pub payment_intent: String,
pub customer_address: Option<StripebillingInvoiceBillingAddress>,
pub attempt_count: u16,
pub lines: StripebillingWebhookLinesObject,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct StripebillingWebhookLinesObject {
pub data: Vec<StripebillingWebhookLinesData>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct StripebillingWebhookLinesData {
pub period: StripebillingWebhookLineDataPeriod,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct StripebillingWebhookLineDataPeriod {
#[serde(with = "common_utils::custom_serde::timestamp")]
pub end: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::timestamp")]
pub start: PrimitiveDateTime,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct StripebillingInvoiceBillingAddress {
pub country: Option<enums::CountryAlpha2>,
pub city: Option<String>,
pub address_line1: Option<Secret<String>>,
pub address_line2: Option<Secret<String>>,
pub zip_code: Option<Secret<String>>,
pub state: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct StripebillingInvoiceObject {
#[serde(rename = "id")]
pub invoice_id: String,
#[serde(deserialize_with = "convert_uppercase")]
pub currency: enums::Currency,
#[serde(rename = "amount_remaining")]
pub amount: common_utils::types::MinorUnit,
pub attempt_count: Option<u16>,
}
impl StripebillingWebhookBody {
pub fn get_webhook_object_from_body(body: &[u8]) -> CustomResult<Self, errors::ConnectorError> {
let webhook_body: Self = body
.parse_struct::<Self>("StripebillingWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(webhook_body)
}
}
impl StripebillingInvoiceBody {
pub fn get_invoice_webhook_data_from_body(
body: &[u8],
) -> CustomResult<Self, errors::ConnectorError> {
let webhook_body = body
.parse_struct::<Self>("StripebillingInvoiceBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(webhook_body)
}
}
impl From<StripebillingInvoiceBillingAddress> for api_models::payments::Address {
fn from(item: StripebillingInvoiceBillingAddress) -> Self {
Self {
address: Some(api_models::payments::AddressDetails::from(item)),
phone: None,
email: None,
}
}
}
impl From<StripebillingInvoiceBillingAddress> for api_models::payments::AddressDetails {
fn from(item: StripebillingInvoiceBillingAddress) -> Self {
Self {
city: item.city,
state: item.state,
country: item.country,
zip: item.zip_code,
line1: item.address_line1,
line2: item.address_line2,
line3: None,
first_name: None,
last_name: None,
origin_zip: None,
}
}
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
impl TryFrom<StripebillingInvoiceBody> for revenue_recovery::RevenueRecoveryInvoiceData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: StripebillingInvoiceBody) -> Result<Self, Self::Error> {
let merchant_reference_id =
id_type::PaymentReferenceId::from_str(&item.data.object.invoice_id)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let next_billing_at = item
.data
.object
.lines
.data
.first()
.map(|linedata| linedata.period.end);
let billing_started_at = item
.data
.object
.lines
.data
.first()
.map(|linedata| linedata.period.start);
Ok(Self {
amount: item.data.object.amount,
currency: item.data.object.currency,
merchant_reference_id,
billing_address: item
.data
.object
.customer_address
.map(api_models::payments::Address::from),
retry_count: Some(item.data.object.attempt_count),
next_billing_at,
billing_started_at,
metadata: None,
// TODO! This field should be handled for billing connnector integrations
enable_partial_authorization: None,
})
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct StripebillingRecoveryDetailsData {
#[serde(rename = "id")]
pub charge_id: String,
pub status: StripebillingChargeStatus,
pub amount: common_utils::types::MinorUnit,
#[serde(deserialize_with = "convert_uppercase")]
pub currency: enums::Currency,
pub customer: String,
pub payment_method: String,
pub failure_code: Option<String>,
pub failure_message: Option<String>,
#[serde(with = "common_utils::custom_serde::timestamp")]
pub created: PrimitiveDateTime,
pub payment_method_details: StripePaymentMethodDetails,
#[serde(rename = "invoice")]
pub invoice_id: String,
pub payment_intent: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct StripePaymentMethodDetails {
#[serde(rename = "type")]
pub type_of_payment_method: StripebillingPaymentMethod,
#[serde(rename = "card")]
pub card_details: StripeBillingCardDetails,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum StripebillingPaymentMethod {
Card,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct StripeBillingCardDetails {
pub network: StripebillingCardNetwork,
pub funding: StripebillingFundingTypes,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum StripebillingCardNetwork {
Visa,
Mastercard,
AmericanExpress,
JCB,
DinersClub,
Discover,
CartesBancaires,
UnionPay,
Interac,
RuPay,
Maestro,
Star,
Pulse,
Accel,
Nyce,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename = "snake_case")]
pub enum StripebillingFundingTypes {
#[serde(rename = "credit")]
Credit,
#[serde(rename = "debit")]
Debit,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum StripebillingChargeStatus {
Succeeded,
Failed,
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
// This is the default hard coded mca Id to find the stripe account associated with the stripe biliing
// Context : Since we dont have the concept of connector_reference_id in stripebilling because payments always go through stripe.
// While creating stripebilling we will hard code the stripe account id to string "stripebilling" in mca featrue metadata. So we have to pass the same as account_reference_id here in response.
const MCA_ID_IDENTIFIER_FOR_STRIPE_IN_STRIPEBILLING_MCA_FEAATURE_METADATA: &str = "stripebilling";
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl
TryFrom<
ResponseRouterData<
recovery_router_flows::BillingConnectorPaymentsSync,
StripebillingRecoveryDetailsData,
recovery_request_types::BillingConnectorPaymentsSyncRequest,
recovery_response_types::BillingConnectorPaymentsSyncResponse,
>,
> for recovery_router_data_types::BillingConnectorPaymentsSyncRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
recovery_router_flows::BillingConnectorPaymentsSync,
StripebillingRecoveryDetailsData,
recovery_request_types::BillingConnectorPaymentsSyncRequest,
recovery_response_types::BillingConnectorPaymentsSyncResponse,
>,
) -> Result<Self, Self::Error> {
let charge_details = item.response;
let merchant_reference_id =
id_type::PaymentReferenceId::from_str(charge_details.invoice_id.as_str())
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "invoice_id",
})?;
let connector_transaction_id = Some(common_utils::types::ConnectorTransactionId::from(
charge_details.payment_intent,
));
Ok(Self {
response: Ok(
recovery_response_types::BillingConnectorPaymentsSyncResponse {
status: charge_details.status.into(),
amount: charge_details.amount,
currency: charge_details.currency,
merchant_reference_id,
connector_account_reference_id:
MCA_ID_IDENTIFIER_FOR_STRIPE_IN_STRIPEBILLING_MCA_FEAATURE_METADATA
.to_string(),
connector_transaction_id,
error_code: charge_details.failure_code,
error_message: charge_details.failure_message,
processor_payment_method_token: charge_details.payment_method,
connector_customer_id: charge_details.customer,
transaction_created_at: Some(charge_details.created),
payment_method_sub_type: common_enums::PaymentMethodType::from(
charge_details.payment_method_details.card_details.funding,
),
payment_method_type: common_enums::PaymentMethod::from(
charge_details.payment_method_details.type_of_payment_method,
),
// Todo: Fetch Card issuer details. Generally in the other billing connector we are getting card_issuer using the card bin info. But stripe dosent provide any such details. We should find a way for stripe billing case
charge_id: Some(charge_details.charge_id.clone()),
// Need to populate these card info field
card_info: api_models::payments::AdditionalCardInfo {
card_network: Some(common_enums::CardNetwork::from(
charge_details.payment_method_details.card_details.network,
)),
card_isin: None,
card_issuer: None,
card_type: None,
card_issuing_country: None,
card_issuing_country_code: None,
bank_code: None,
last4: None,
card_extended_bin: None,
card_exp_month: None,
card_exp_year: None,
card_holder_name: None,
payment_checks: None,
authentication_data: None,
is_regulated: None,
signature_network: None,
},
},
),
..item.data
})
}
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl From<StripebillingChargeStatus> for enums::AttemptStatus {
fn from(status: StripebillingChargeStatus) -> Self {
match status {
StripebillingChargeStatus::Succeeded => Self::Charged,
StripebillingChargeStatus::Failed => Self::Failure,
}
}
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl From<StripebillingFundingTypes> for common_enums::PaymentMethodType {
fn from(funding: StripebillingFundingTypes) -> Self {
match funding {
StripebillingFundingTypes::Credit => Self::Credit,
StripebillingFundingTypes::Debit => Self::Debit,
}
}
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl From<StripebillingPaymentMethod> for common_enums::PaymentMethod {
fn from(method: StripebillingPaymentMethod) -> Self {
match method {
StripebillingPaymentMethod::Card => Self::Card,
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct StripebillingRecordBackResponse {
pub id: String,
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl
TryFrom<
ResponseRouterData<
recovery_router_flows::InvoiceRecordBack,
StripebillingRecordBackResponse,
recovery_request_types::InvoiceRecordBackRequest,
recovery_response_types::InvoiceRecordBackResponse,
>,
> for recovery_router_data_types::InvoiceRecordBackRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
recovery_router_flows::InvoiceRecordBack,
StripebillingRecordBackResponse,
recovery_request_types::InvoiceRecordBackRequest,
recovery_response_types::InvoiceRecordBackResponse,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(recovery_response_types::InvoiceRecordBackResponse {
merchant_reference_id: id_type::PaymentReferenceId::from_str(
item.response.id.as_str(),
)
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "invoice_id in the response",
})?,
}),
..item.data
})
}
}
impl From<StripebillingCardNetwork> for enums::CardNetwork {
fn from(item: StripebillingCardNetwork) -> Self {
match item {
StripebillingCardNetwork::Visa => Self::Visa,
StripebillingCardNetwork::Mastercard => Self::Mastercard,
StripebillingCardNetwork::AmericanExpress => Self::AmericanExpress,
StripebillingCardNetwork::JCB => Self::JCB,
StripebillingCardNetwork::DinersClub => Self::DinersClub,
StripebillingCardNetwork::Discover => Self::Discover,
StripebillingCardNetwork::CartesBancaires => Self::CartesBancaires,
StripebillingCardNetwork::UnionPay => Self::UnionPay,
StripebillingCardNetwork::Interac => Self::Interac,
StripebillingCardNetwork::RuPay => Self::RuPay,
StripebillingCardNetwork::Maestro => Self::Maestro,
StripebillingCardNetwork::Star => Self::Star,
StripebillingCardNetwork::Pulse => Self::Pulse,
StripebillingCardNetwork::Accel => Self::Accel,
StripebillingCardNetwork::Nyce => Self::Nyce,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/juspaythreedsserver/transformers.rs | crates/hyperswitch_connectors/src/connectors/juspaythreedsserver/transformers.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>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs | crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs | use common_enums::{enums, AttemptStatus, BankNames};
use common_utils::{
errors::ParsingError,
pii::{Email, IpAddress},
request::Method,
types::{FloatMajorUnit, MinorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankRedirectData, PayLaterData, PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{self},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, CardData as _, PaymentsAuthorizeRequestData, RouterData as _,
},
};
#[derive(Debug, Serialize)]
pub struct MultisafepayRouterData<T> {
amount: MinorUnit,
router_data: T,
}
impl<T> From<(MinorUnit, T)> for MultisafepayRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Type {
Direct,
Redirect,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Gateway {
Amex,
CreditCard,
Discover,
Maestro,
MasterCard,
Visa,
Klarna,
Googlepay,
Paypal,
Ideal,
Giropay,
Trustly,
Alipay,
#[serde(rename = "WECHAT")]
WeChatPay,
Eps,
MbWay,
#[serde(rename = "DIRECTBANK")]
Sofort,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Coupons {
pub allow: Option<Vec<Secret<String>>>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Mistercash {
pub mobile_pay_button_position: Option<String>,
pub disable_mobile_pay_button: Option<String>,
pub qr_only: Option<String>,
pub qr_size: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub struct Gateways {
pub mistercash: Option<Mistercash>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Settings {
pub coupons: Option<Coupons>,
pub gateways: Option<Gateways>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct PaymentOptions {
pub notification_url: Option<String>,
pub notification_method: Option<String>,
pub redirect_url: String,
pub cancel_url: String,
pub close_window: Option<bool>,
pub settings: Option<Settings>,
pub template_id: Option<String>,
pub allowed_countries: Option<Vec<String>>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Browser {
pub javascript_enabled: Option<bool>,
pub java_enabled: Option<bool>,
pub cookies_enabled: Option<bool>,
pub language: Option<String>,
pub screen_color_depth: Option<i32>,
pub screen_height: Option<i32>,
pub screen_width: Option<i32>,
pub time_zone: Option<i32>,
pub user_agent: Option<String>,
pub platform: Option<String>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Customer {
pub browser: Option<Browser>,
pub locale: Option<String>,
pub ip_address: Option<Secret<String, IpAddress>>,
pub forward_ip: Option<Secret<String, IpAddress>>,
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub gender: Option<Secret<String>>,
pub birthday: Option<Secret<String>>,
pub address1: Option<Secret<String>>,
pub address2: Option<Secret<String>>,
pub house_number: Option<Secret<String>>,
pub zip_code: Option<Secret<String>>,
pub city: Option<String>,
pub state: Option<String>,
pub country: Option<String>,
pub phone: Option<Secret<String>>,
pub email: Option<Email>,
pub user_agent: Option<String>,
pub referrer: Option<String>,
pub reference: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct CardInfo {
pub card_number: Option<cards::CardNumber>,
pub card_holder_name: Option<Secret<String>>,
pub card_expiry_date: Option<Secret<i32>>,
pub card_cvc: Option<Secret<String>>,
pub flexible_3d: Option<bool>,
pub moto: Option<bool>,
pub term_url: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct GpayInfo {
pub payment_token: Option<Secret<String>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct PayLaterInfo {
pub email: Option<Email>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum GatewayInfo {
Card(CardInfo),
Wallet(WalletInfo),
PayLater(PayLaterInfo),
BankRedirect(BankRedirectInfo),
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum WalletInfo {
GooglePay(GpayInfo),
Alipay(AlipayInfo),
WeChatPay(WeChatPayInfo),
MbWay(MbWayInfo),
}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct MbWayInfo {}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct WeChatPayInfo {}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct AlipayInfo {}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum BankRedirectInfo {
Ideal(IdealInfo),
Trustly(TrustlyInfo),
Eps(EpsInfo),
Sofort(SofortInfo),
}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct SofortInfo {}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct EpsInfo {}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct TrustlyInfo {}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct IdealInfo {
pub issuer_id: MultisafepayBankNames,
}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub enum MultisafepayBankNames {
#[serde(rename = "0031")]
AbnAmro,
#[serde(rename = "0761")]
AsnBank,
#[serde(rename = "4371")]
Bunq,
#[serde(rename = "0721")]
Ing,
#[serde(rename = "0801")]
Knab,
#[serde(rename = "9926")]
N26,
#[serde(rename = "9927")]
NationaleNederlanden,
#[serde(rename = "0021")]
Rabobank,
#[serde(rename = "0771")]
Regiobank,
#[serde(rename = "1099")]
Revolut,
#[serde(rename = "0751")]
SnsBank,
#[serde(rename = "0511")]
TriodosBank,
#[serde(rename = "0161")]
VanLanschot,
#[serde(rename = "0806")]
Yoursafe,
#[serde(rename = "1235")]
Handelsbanken,
}
impl TryFrom<&BankNames> for MultisafepayBankNames {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(bank: &BankNames) -> Result<Self, Self::Error> {
match bank {
BankNames::AbnAmro => Ok(Self::AbnAmro),
BankNames::AsnBank => Ok(Self::AsnBank),
BankNames::Bunq => Ok(Self::Bunq),
BankNames::Ing => Ok(Self::Ing),
BankNames::Knab => Ok(Self::Knab),
BankNames::N26 => Ok(Self::N26),
BankNames::NationaleNederlanden => Ok(Self::NationaleNederlanden),
BankNames::Rabobank => Ok(Self::Rabobank),
BankNames::Regiobank => Ok(Self::Regiobank),
BankNames::Revolut => Ok(Self::Revolut),
BankNames::SnsBank => Ok(Self::SnsBank),
BankNames::TriodosBank => Ok(Self::TriodosBank),
BankNames::VanLanschot => Ok(Self::VanLanschot),
BankNames::Yoursafe => Ok(Self::Yoursafe),
BankNames::Handelsbanken => Ok(Self::Handelsbanken),
BankNames::AmericanExpress
| BankNames::AffinBank
| BankNames::AgroBank
| BankNames::AllianceBank
| BankNames::AmBank
| BankNames::BankOfAmerica
| BankNames::BankOfChina
| BankNames::BankIslam
| BankNames::BankMuamalat
| BankNames::BankRakyat
| BankNames::BankSimpananNasional
| BankNames::Barclays
| BankNames::BlikPSP
| BankNames::CapitalOne
| BankNames::Chase
| BankNames::Citi
| BankNames::CimbBank
| BankNames::Discover
| BankNames::NavyFederalCreditUnion
| BankNames::PentagonFederalCreditUnion
| BankNames::SynchronyBank
| BankNames::WellsFargo
| BankNames::HongLeongBank
| BankNames::HsbcBank
| BankNames::KuwaitFinanceHouse
| BankNames::Moneyou
| BankNames::ArzteUndApothekerBank
| BankNames::AustrianAnadiBankAg
| BankNames::BankAustria
| BankNames::Bank99Ag
| BankNames::BankhausCarlSpangler
| BankNames::BankhausSchelhammerUndSchatteraAg
| BankNames::BankMillennium
| BankNames::BankPEKAOSA
| BankNames::BawagPskAg
| BankNames::BksBankAg
| BankNames::BrullKallmusBankAg
| BankNames::BtvVierLanderBank
| BankNames::CapitalBankGraweGruppeAg
| BankNames::CeskaSporitelna
| BankNames::Dolomitenbank
| BankNames::EasybankAg
| BankNames::EPlatbyVUB
| BankNames::ErsteBankUndSparkassen
| BankNames::FrieslandBank
| BankNames::HypoAlpeadriabankInternationalAg
| BankNames::HypoNoeLbFurNiederosterreichUWien
| BankNames::HypoOberosterreichSalzburgSteiermark
| BankNames::HypoTirolBankAg
| BankNames::HypoVorarlbergBankAg
| BankNames::HypoBankBurgenlandAktiengesellschaft
| BankNames::KomercniBanka
| BankNames::MBank
| BankNames::MarchfelderBank
| BankNames::Maybank
| BankNames::OberbankAg
| BankNames::OsterreichischeArzteUndApothekerbank
| BankNames::OcbcBank
| BankNames::PayWithING
| BankNames::PlaceZIPKO
| BankNames::PlatnoscOnlineKartaPlatnicza
| BankNames::PosojilnicaBankEGen
| BankNames::PostovaBanka
| BankNames::PublicBank
| BankNames::RaiffeisenBankengruppeOsterreich
| BankNames::RhbBank
| BankNames::SchelhammerCapitalBankAg
| BankNames::StandardCharteredBank
| BankNames::SchoellerbankAg
| BankNames::SpardaBankWien
| BankNames::SporoPay
| BankNames::SantanderPrzelew24
| BankNames::TatraPay
| BankNames::Viamo
| BankNames::VolksbankGruppe
| BankNames::VolkskreditbankAg
| BankNames::VrBankBraunau
| BankNames::UobBank
| BankNames::PayWithAliorBank
| BankNames::BankiSpoldzielcze
| BankNames::PayWithInteligo
| BankNames::BNPParibasPoland
| BankNames::BankNowySA
| BankNames::CreditAgricole
| BankNames::PayWithBOS
| BankNames::PayWithCitiHandlowy
| BankNames::PayWithPlusBank
| BankNames::ToyotaBank
| BankNames::VeloBank
| BankNames::ETransferPocztowy24
| BankNames::PlusBank
| BankNames::EtransferPocztowy24
| BankNames::BankiSpbdzielcze
| BankNames::BankNowyBfgSa
| BankNames::GetinBank
| BankNames::Blik
| BankNames::NoblePay
| BankNames::IdeaBank
| BankNames::EnveloBank
| BankNames::NestPrzelew
| BankNames::MbankMtransfer
| BankNames::Inteligo
| BankNames::PbacZIpko
| BankNames::BnpParibas
| BankNames::BankPekaoSa
| BankNames::VolkswagenBank
| BankNames::AliorBank
| BankNames::Boz
| BankNames::BangkokBank
| BankNames::KrungsriBank
| BankNames::KrungThaiBank
| BankNames::TheSiamCommercialBank
| BankNames::KasikornBank
| BankNames::OpenBankSuccess
| BankNames::OpenBankFailure
| BankNames::OpenBankCancelled
| BankNames::Aib
| BankNames::BankOfScotland
| BankNames::DanskeBank
| BankNames::FirstDirect
| BankNames::FirstTrust
| BankNames::Halifax
| BankNames::Lloyds
| BankNames::Monzo
| BankNames::NatWest
| BankNames::NationwideBank
| BankNames::RoyalBankOfScotland
| BankNames::Starling
| BankNames::TsbBank
| BankNames::TescoBank
| BankNames::UlsterBank => Err(Into::into(errors::ConnectorError::NotSupported {
message: String::from("BankRedirect"),
connector: "Multisafepay",
})),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct DeliveryObject {
first_name: Secret<String>,
last_name: Secret<String>,
address1: Secret<String>,
house_number: Secret<String>,
zip_code: Secret<String>,
city: String,
country: api_models::enums::CountryAlpha2,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct DefaultObject {
shipping_taxed: bool,
rate: f64,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct TaxObject {
pub default: DefaultObject,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct CheckoutOptions {
pub validate_cart: Option<bool>,
pub tax_tables: TaxObject,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct Item {
pub name: String,
pub unit_price: FloatMajorUnit,
pub description: Option<String>,
pub quantity: i64,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct ShoppingCart {
pub items: Vec<Item>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct MultisafepayPaymentsRequest {
#[serde(rename = "type")]
pub payment_type: Type,
pub gateway: Option<Gateway>,
pub order_id: String,
pub currency: String,
pub amount: MinorUnit,
pub description: String,
pub payment_options: Option<PaymentOptions>,
pub customer: Option<Customer>,
pub gateway_info: Option<GatewayInfo>,
pub delivery: Option<DeliveryObject>,
pub checkout_options: Option<CheckoutOptions>,
pub shopping_cart: Option<ShoppingCart>,
pub items: Option<String>,
pub recurring_model: Option<MandateType>,
pub recurring_id: Option<Secret<String>>,
pub capture: Option<String>,
pub days_active: Option<i32>,
pub seconds_active: Option<i32>,
pub var1: Option<String>,
pub var2: Option<String>,
pub var3: Option<String>,
}
impl TryFrom<utils::CardIssuer> for Gateway {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(issuer: utils::CardIssuer) -> Result<Self, Self::Error> {
match issuer {
utils::CardIssuer::AmericanExpress => Ok(Self::Amex),
utils::CardIssuer::Master => Ok(Self::MasterCard),
utils::CardIssuer::Maestro => Ok(Self::Maestro),
utils::CardIssuer::Discover => Ok(Self::Discover),
utils::CardIssuer::Visa => Ok(Self::Visa),
utils::CardIssuer::DinersClub
| utils::CardIssuer::JCB
| utils::CardIssuer::CarteBlanche
| utils::CardIssuer::UnionPay
| utils::CardIssuer::CartesBancaires => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Multisafe pay"),
)
.into()),
}
}
}
impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
for MultisafepayPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payment_type = match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref _ccard) => Type::Direct,
PaymentMethodData::MandatePayment => Type::Direct,
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletData::GooglePay(_) => Type::Direct,
WalletData::PaypalRedirect(_) => Type::Redirect,
WalletData::AliPayRedirect(_) => Type::Redirect,
WalletData::WeChatPayRedirect(_) => Type::Redirect,
WalletData::MbWayRedirect(_) => Type::Redirect,
WalletData::AliPayQr(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
},
PaymentMethodData::BankRedirect(ref bank_data) => match bank_data {
BankRedirectData::Giropay { .. } => Type::Redirect,
BankRedirectData::Ideal { .. } => Type::Direct,
BankRedirectData::Trustly { .. } => Type::Redirect,
BankRedirectData::Eps { .. } => Type::Redirect,
BankRedirectData::Sofort { .. } => Type::Redirect,
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Bizum { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {}
| BankRedirectData::OpenBanking { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?
}
},
PaymentMethodData::PayLater(ref _paylater) => Type::Redirect,
_ => Type::Redirect,
};
let gateway = match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => {
Some(Gateway::try_from(ccard.get_card_issuer()?)?)
}
PaymentMethodData::Wallet(ref wallet_data) => Some(match wallet_data {
WalletData::GooglePay(_) => Gateway::Googlepay,
WalletData::PaypalRedirect(_) => Gateway::Paypal,
WalletData::AliPayRedirect(_) => Gateway::Alipay,
WalletData::WeChatPayRedirect(_) => Gateway::WeChatPay,
WalletData::MbWayRedirect(_) => Gateway::MbWay,
WalletData::AliPayQr(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
}),
PaymentMethodData::BankRedirect(ref bank_data) => Some(match bank_data {
BankRedirectData::Giropay { .. } => Gateway::Giropay,
BankRedirectData::Ideal { .. } => Gateway::Ideal,
BankRedirectData::Trustly { .. } => Gateway::Trustly,
BankRedirectData::Eps { .. } => Gateway::Eps,
BankRedirectData::Sofort { .. } => Gateway::Sofort,
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Bizum { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {}
| BankRedirectData::OpenBanking { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?
}
}),
PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect {}) => Some(Gateway::Klarna),
PaymentMethodData::MandatePayment => None,
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?
}
};
let description = item.router_data.get_description()?;
let payment_options = PaymentOptions {
notification_url: None,
redirect_url: item.router_data.request.get_router_return_url()?,
cancel_url: item.router_data.request.get_router_return_url()?,
close_window: None,
notification_method: None,
settings: None,
template_id: None,
allowed_countries: None,
};
let customer = Customer {
browser: None,
locale: None,
ip_address: None,
forward_ip: None,
first_name: None,
last_name: None,
gender: None,
birthday: None,
address1: None,
address2: None,
house_number: None,
zip_code: None,
city: None,
state: None,
country: None,
phone: None,
email: item.router_data.request.email.clone(),
user_agent: None,
referrer: None,
reference: Some(item.router_data.connector_request_reference_id.clone()),
};
let billing_address = item
.router_data
.get_billing()?
.address
.as_ref()
.ok_or_else(utils::missing_field_err("billing.address"))?;
let first_name = billing_address.get_first_name()?;
let delivery = DeliveryObject {
first_name: first_name.clone(),
last_name: billing_address
.get_last_name()
.unwrap_or(first_name)
.clone(),
address1: billing_address.get_line1()?.to_owned(),
house_number: billing_address.get_line2()?.to_owned(),
zip_code: billing_address.get_zip()?.to_owned(),
city: billing_address.get_city()?.to_owned(),
country: billing_address.get_country()?.to_owned(),
};
let gateway_info = match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => Some(GatewayInfo::Card(CardInfo {
card_number: Some(ccard.card_number.clone()),
card_expiry_date: Some(Secret::new(
(format!(
"{}{}",
ccard.get_card_expiry_year_2_digit()?.expose(),
ccard.card_exp_month.clone().expose()
))
.parse::<i32>()
.unwrap_or_default(),
)),
card_cvc: Some(ccard.card_cvc.clone()),
card_holder_name: None,
flexible_3d: None,
moto: None,
term_url: None,
})),
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletData::GooglePay(ref google_pay) => {
Some(GatewayInfo::Wallet(WalletInfo::GooglePay({
GpayInfo {
payment_token: Some(Secret::new(
google_pay
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "google_pay_token",
})?
.clone(),
)),
}
})))
}
WalletData::AliPayRedirect(_) => {
Some(GatewayInfo::Wallet(WalletInfo::Alipay(AlipayInfo {})))
}
WalletData::PaypalRedirect(_) => None,
WalletData::WeChatPayRedirect(_) => {
Some(GatewayInfo::Wallet(WalletInfo::WeChatPay(WeChatPayInfo {})))
}
WalletData::MbWayRedirect(_) => {
Some(GatewayInfo::Wallet(WalletInfo::MbWay(MbWayInfo {})))
}
WalletData::AliPayQr(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
},
PaymentMethodData::PayLater(ref paylater) => {
Some(GatewayInfo::PayLater(PayLaterInfo {
email: Some(match paylater {
PayLaterData::KlarnaRedirect {} => item.router_data.get_billing_email()?,
PayLaterData::KlarnaSdk { token: _ }
| PayLaterData::AffirmRedirect {}
| PayLaterData::FlexitiRedirect {}
| PayLaterData::AfterpayClearpayRedirect {}
| PayLaterData::PayBrightRedirect {}
| PayLaterData::WalleyRedirect {}
| PayLaterData::AlmaRedirect {}
| PayLaterData::AtomeRedirect {}
| PayLaterData::BreadpayRedirect {}
| PayLaterData::PayjustnowRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"multisafepay",
),
))?
}
}),
}))
}
PaymentMethodData::BankRedirect(ref bank_redirect_data) => match bank_redirect_data {
BankRedirectData::Ideal { bank_name, .. } => Some(GatewayInfo::BankRedirect(
BankRedirectInfo::Ideal(IdealInfo {
issuer_id: MultisafepayBankNames::try_from(&bank_name.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "ideal.bank_name",
},
)?)?,
}),
)),
BankRedirectData::Trustly { .. } => Some(GatewayInfo::BankRedirect(
BankRedirectInfo::Trustly(TrustlyInfo {}),
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs | crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs | use std::collections::HashMap;
use api_models::payments::SessionToken;
use cards::NetworkToken;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::OptionExt,
pii::{self, Email},
request::Method,
types::{FloatMajorUnit, 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::{
CreateOrderRouterData, PaymentsAuthorizeRouterData, PaymentsPreProcessingRouterData,
RefreshTokenRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use reqwest::Url;
use serde::{Deserialize, Serialize};
use crate::{
types::{
CreateOrderResponseRouterData, PaymentsPreprocessingResponseRouterData,
RefundsResponseRouterData, ResponseRouterData,
},
utils::{
self, AddressDetailsData, BrowserInformationData, CardData, NetworkTokenData,
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,
InstantBankTransferFI,
InstantBankTransferPL,
}
#[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, PartialEq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct BankPaymentInformationResponse {
pub status: TrustpayBankRedirectPaymentStatus,
pub status_reason_information: Option<StatusReasonInformation>,
pub references: ReferencesResponse,
pub amount: WebhookAmount,
}
#[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>),
NetworkTokenPaymentRequest(Box<PaymentRequestNetworkToken>),
}
#[derive(Debug, Serialize, PartialEq)]
pub struct PaymentRequestNetworkToken {
pub amount: StringMajorUnit,
pub currency: enums::Currency,
pub pan: NetworkToken,
#[serde(rename = "exp")]
pub expiry_date: Secret<String>,
#[serde(rename = "RedirectUrl")]
pub redirect_url: String,
#[serde(rename = "threeDSecureEnrollmentStatus")]
pub enrollment_status: char,
#[serde(rename = "threeDSecureEci")]
pub eci: String,
#[serde(rename = "threeDSecureAuthenticationStatus")]
pub authentication_status: char,
#[serde(rename = "threeDSecureVerificationId")]
pub verification_id: Secret<String>,
}
#[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 {}
| BankRedirectData::OpenBanking { .. } => 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),
BankTransferData::InstantBankTransferFinland {} => Ok(Self::InstantBankTransferFI),
BankTransferData::InstantBankTransferPoland {} => Ok(Self::InstantBankTransferPL),
_ => 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
.billing_descriptor
.as_ref()
.and_then(|descriptor| descriptor.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
| TrustpayBankTransferPaymentMethod::InstantBankTransferFI
| TrustpayBankTransferPaymentMethod::InstantBankTransferPL => 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())),
referer: None,
};
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::NetworkToken(ref token_data) => {
Ok(Self::NetworkTokenPaymentRequest(Box::new(
PaymentRequestNetworkToken {
amount: item.amount.to_owned(),
currency: item.router_data.request.currency,
pan: token_data.get_network_token(),
expiry_date: token_data
.get_token_expiry_month_year_2_digit_with_delimiter("/".to_owned())?,
redirect_url: item.router_data.request.get_router_return_url()?,
enrollment_status: 'Y', // Set to 'Y' as network provider not providing this value in response
eci: token_data.eci.clone().ok_or_else(|| {
errors::ConnectorError::MissingRequiredField { field_name: "eci" }
})?,
authentication_status: 'Y', // Set to 'Y' since presence of token_cryptogram is already validated
verification_id: token_data.get_cryptogram().ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "verification_id",
}
})?,
},
)))
}
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::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
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>
{
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs | crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs | use bytes::Bytes;
use common_enums::{
self, AttemptStatus, AuthorizationStatus, CaptureMethod, Currency, FutureUsage,
PaymentMethodStatus, RefundStatus,
};
use common_utils::{date_time, ext_traits::Encode, pii, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
address::AddressDetails,
payment_method_data::{Card, PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{
AuthenticationData, PaymentsIncrementalAuthorizationData, ResponseId,
SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsIncrementalAuthorizationRouterData, PaymentsSyncRouterData, RefundsRouterData,
SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
ResponseRouterData,
},
unimplemented_payment_method,
utils::{
self, AddressData, AddressDetailsData, CardData, CardIssuer, PaymentsAuthorizeRequestData,
RouterData as _,
},
};
const THREE_DS_MAX_SUPPORTED_VERSION: &str = "2.2.0";
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(transparent)]
pub struct ArchipelTenantId(pub String);
impl From<String> for ArchipelTenantId {
fn from(value: String) -> Self {
Self(value)
}
}
pub struct ArchipelRouterData<T> {
pub amount: MinorUnit,
pub tenant_id: ArchipelTenantId,
pub router_data: T,
}
impl<T> From<(MinorUnit, ArchipelTenantId, T)> for ArchipelRouterData<T> {
fn from((amount, tenant_id, router_data): (MinorUnit, ArchipelTenantId, T)) -> Self {
Self {
amount,
tenant_id,
router_data,
}
}
}
pub struct ArchipelAuthType {
pub(super) ca_certificate: Option<Secret<String>>,
}
impl TryFrom<&ConnectorAuthType> for ArchipelAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
ca_certificate: Some(api_key.to_owned()),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct ArchipelConfigData {
pub tenant_id: ArchipelTenantId,
pub platform_url: String,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for ArchipelConfigData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(connector_metadata: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let config_data = utils::to_connector_meta_from_secret::<Self>(connector_metadata.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata. Required fields: tenant_id, platform_url",
})?;
Ok(config_data)
}
}
#[derive(Debug, Default, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum ArchipelPaymentInitiator {
#[default]
Customer,
Merchant,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ArchipelWalletProvider {
ApplePay,
GooglePay,
SamsungPay,
}
#[derive(Debug, Default, Serialize, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum ArchipelPaymentCertainty {
#[default]
Final,
Estimated,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelOrderRequest {
amount: MinorUnit,
currency: String,
certainty: ArchipelPaymentCertainty,
initiator: ArchipelPaymentInitiator,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
pub struct CardExpiryDate {
month: Secret<String>,
year: Secret<String>,
}
#[derive(Debug, Serialize, Default, Eq, PartialEq, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ApplicationSelectionIndicator {
#[default]
ByDefault,
CustomerChoice,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Archipel3DS {
#[serde(rename = "acsTransID")]
acs_trans_id: Option<Secret<String>>,
#[serde(rename = "dsTransID")]
ds_trans_id: Option<Secret<String>>,
#[serde(rename = "3DSRequestorName")]
three_ds_requestor_name: Option<Secret<String>>,
#[serde(rename = "3DSAuthDate")]
three_ds_auth_date: Option<String>,
#[serde(rename = "3DSAuthAmt")]
three_ds_auth_amt: Option<MinorUnit>,
#[serde(rename = "3DSAuthStatus")]
three_ds_auth_status: Option<String>,
#[serde(rename = "3DSMaxSupportedVersion")]
three_ds_max_supported_version: String,
#[serde(rename = "3DSVersion")]
three_ds_version: Option<common_utils::types::SemanticVersion>,
authentication_value: Secret<String>,
authentication_method: Option<Secret<String>>,
eci: Option<String>,
}
impl From<AuthenticationData> for Archipel3DS {
fn from(three_ds_data: AuthenticationData) -> Self {
let now = date_time::date_as_yyyymmddthhmmssmmmz().ok();
Self {
acs_trans_id: None,
ds_trans_id: three_ds_data.ds_trans_id.map(Secret::new),
three_ds_requestor_name: None,
three_ds_auth_date: now,
three_ds_auth_amt: None,
three_ds_auth_status: None,
three_ds_max_supported_version: THREE_DS_MAX_SUPPORTED_VERSION.into(),
three_ds_version: three_ds_data.message_version,
authentication_value: three_ds_data.cavv,
authentication_method: None,
eci: three_ds_data.eci,
}
}
}
#[derive(Clone, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelCardHolder {
billing_address: Option<ArchipelBillingAddress>,
}
impl From<Option<ArchipelBillingAddress>> for ArchipelCardHolder {
fn from(value: Option<ArchipelBillingAddress>) -> Self {
Self {
billing_address: value,
}
}
}
#[derive(Clone, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelBillingAddress {
address: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
}
pub trait ToArchipelBillingAddress {
fn to_archipel_billing_address(&self) -> Option<ArchipelBillingAddress>;
}
impl ToArchipelBillingAddress for AddressDetails {
fn to_archipel_billing_address(&self) -> Option<ArchipelBillingAddress> {
let address = self.get_combined_address_line().ok();
let postal_code = self.get_optional_zip();
match (address, postal_code) {
(None, None) => None,
(addr, zip) => Some(ArchipelBillingAddress {
address: addr,
postal_code: zip,
}),
}
}
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum ArchipelCredentialIndicatorStatus {
Initial,
Subsequent,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelCredentialIndicator {
status: ArchipelCredentialIndicatorStatus,
recurring: Option<bool>,
transaction_id: Option<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCardData {
card_data: ArchipelTokenizedCard,
wallet_information: ArchipelWalletInformation,
}
impl TryFrom<(&WalletData, &Option<PaymentMethodToken>)> for TokenizedCardData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(wallet_data, pm_token): (&WalletData, &Option<PaymentMethodToken>),
) -> Result<Self, Self::Error> {
let WalletData::ApplePay(apple_pay_data) = wallet_data else {
return Err(error_stack::Report::from(
errors::ConnectorError::NotSupported {
message: "Wallet type used".to_string(),
connector: "Archipel",
},
));
};
let Some(PaymentMethodToken::ApplePayDecrypt(apple_pay_decrypt_data)) = pm_token else {
return Err(error_stack::Report::from(unimplemented_payment_method!(
"Apple Pay",
"Manual",
"Archipel"
)));
};
let card_number = apple_pay_decrypt_data
.application_primary_account_number
.clone();
let expiry_year_2_digit = apple_pay_decrypt_data
.get_two_digit_expiry_year()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay expiry year",
})?;
let expiry_month = apple_pay_decrypt_data.get_expiry_month().change_context(
errors::ConnectorError::InvalidDataFormat {
field_name: "expiration_month",
},
)?;
Ok(Self {
card_data: ArchipelTokenizedCard {
expiry: CardExpiryDate {
year: expiry_year_2_digit,
month: expiry_month,
},
number: card_number,
scheme: ArchipelCardScheme::from(apple_pay_data.payment_method.network.as_str()),
},
wallet_information: {
ArchipelWalletInformation {
wallet_provider: ArchipelWalletProvider::ApplePay,
wallet_indicator: apple_pay_decrypt_data.payment_data.eci_indicator.clone(),
wallet_cryptogram: apple_pay_decrypt_data
.payment_data
.online_payment_cryptogram
.clone(),
}
},
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelTokenizedCard {
number: cards::CardNumber,
expiry: CardExpiryDate,
scheme: ArchipelCardScheme,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelCard {
number: cards::CardNumber,
expiry: CardExpiryDate,
security_code: Option<Secret<String>>,
card_holder_name: Option<Secret<String>>,
application_selection_indicator: ApplicationSelectionIndicator,
scheme: ArchipelCardScheme,
}
impl TryFrom<(Option<Secret<String>>, Option<ArchipelCardHolder>, &Card)> for ArchipelCard {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(card_holder_name, card_holder_billing, ccard): (
Option<Secret<String>>,
Option<ArchipelCardHolder>,
&Card,
),
) -> Result<Self, Self::Error> {
// NOTE: Archipel does not accept `card.card_holder_name` field without `cardholder` field.
// So if `card_holder` is None, `card.card_holder_name` must also be None.
// However, the reverse is allowed — the `cardholder` field can exist without `card.card_holder_name`.
let card_holder_name = card_holder_billing
.as_ref()
.and_then(|_| ccard.card_holder_name.clone().or(card_holder_name.clone()));
let scheme: ArchipelCardScheme = ccard.get_card_issuer().ok().into();
Ok(Self {
number: ccard.card_number.clone(),
expiry: CardExpiryDate {
month: ccard.card_exp_month.clone(),
year: ccard.get_card_expiry_year_2_digit()?,
},
security_code: Some(ccard.card_cvc.clone()),
application_selection_indicator: ApplicationSelectionIndicator::ByDefault,
card_holder_name,
scheme,
})
}
}
impl
TryFrom<(
Option<Secret<String>>,
Option<ArchipelCardHolder>,
&hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId,
)> for ArchipelCard
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(card_holder_name, card_holder_billing, card_details): (
Option<Secret<String>>,
Option<ArchipelCardHolder>,
&hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId,
),
) -> Result<Self, Self::Error> {
// NOTE: Archipel does not accept `card.card_holder_name` field without `cardholder` field.
// So if `card_holder` is None, `card.card_holder_name` must also be None.
// However, the reverse is allowed — the `cardholder` field can exist without `card.card_holder_name`.
let card_holder_name = card_holder_billing.as_ref().and_then(|_| {
card_details
.card_holder_name
.clone()
.or(card_holder_name.clone())
});
let scheme: ArchipelCardScheme = card_details.get_card_issuer().ok().into();
Ok(Self {
number: card_details.card_number.clone(),
expiry: CardExpiryDate {
month: card_details.card_exp_month.clone(),
year: card_details.get_card_expiry_year_2_digit()?,
},
security_code: None,
application_selection_indicator: ApplicationSelectionIndicator::ByDefault,
card_holder_name,
scheme,
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelWalletInformation {
wallet_indicator: Option<String>,
wallet_provider: ArchipelWalletProvider,
wallet_cryptogram: Secret<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelPaymentInformation {
order: ArchipelOrderRequest,
cardholder: Option<ArchipelCardHolder>,
card_holder_name: Option<Secret<String>>,
credential_indicator: Option<ArchipelCredentialIndicator>,
stored_on_file: bool,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelWalletAuthorizationRequest {
order: ArchipelOrderRequest,
card: ArchipelTokenizedCard,
cardholder: Option<ArchipelCardHolder>,
wallet: ArchipelWalletInformation,
#[serde(rename = "3DS")]
three_ds: Option<Archipel3DS>,
credential_indicator: Option<ArchipelCredentialIndicator>,
stored_on_file: bool,
tenant_id: ArchipelTenantId,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelCardAuthorizationRequest {
order: ArchipelOrderRequest,
card: ArchipelCard,
cardholder: Option<ArchipelCardHolder>,
#[serde(rename = "3DS")]
three_ds: Option<Archipel3DS>,
credential_indicator: Option<ArchipelCredentialIndicator>,
stored_on_file: bool,
tenant_id: ArchipelTenantId,
}
// PaymentsResponse
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "UPPERCASE")]
pub enum ArchipelCardScheme {
Amex,
Mastercard,
Visa,
Discover,
Diners,
Unknown,
}
impl From<&str> for ArchipelCardScheme {
fn from(input: &str) -> Self {
match input {
"Visa" => Self::Visa,
"Amex" => Self::Amex,
"Diners" => Self::Diners,
"MasterCard" => Self::Mastercard,
"Discover" => Self::Discover,
_ => Self::Unknown,
}
}
}
impl From<Option<CardIssuer>> for ArchipelCardScheme {
fn from(card_issuer: Option<CardIssuer>) -> Self {
match card_issuer {
Some(CardIssuer::Visa) => Self::Visa,
Some(CardIssuer::Master | CardIssuer::Maestro) => Self::Mastercard,
Some(CardIssuer::AmericanExpress) => Self::Amex,
Some(CardIssuer::Discover) => Self::Discover,
Some(CardIssuer::DinersClub) => Self::Diners,
_ => Self::Unknown,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum ArchipelPaymentStatus {
#[default]
Succeeded,
Failed,
}
impl TryFrom<(AttemptStatus, CaptureMethod)> for ArchipelPaymentFlow {
type Error = errors::ConnectorError;
fn try_from(
(status, capture_method): (AttemptStatus, CaptureMethod),
) -> Result<Self, Self::Error> {
let is_auto_capture = matches!(capture_method, CaptureMethod::Automatic);
match status {
AttemptStatus::AuthenticationFailed => Ok(Self::Verify),
AttemptStatus::Authorizing
| AttemptStatus::Authorized
| AttemptStatus::AuthorizationFailed => Ok(Self::Authorize),
AttemptStatus::Voided | AttemptStatus::VoidInitiated | AttemptStatus::VoidFailed => {
Ok(Self::Cancel)
}
AttemptStatus::CaptureInitiated | AttemptStatus::CaptureFailed => {
if is_auto_capture {
Ok(Self::Pay)
} else {
Ok(Self::Capture)
}
}
AttemptStatus::PaymentMethodAwaited | AttemptStatus::ConfirmationAwaited => {
if is_auto_capture {
Ok(Self::Pay)
} else {
Ok(Self::Authorize)
}
}
_ => Err(errors::ConnectorError::ProcessingStepFailed(Some(
Bytes::from_static(
"Impossible to determine Archipel flow from AttemptStatus".as_bytes(),
),
))),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ArchipelPaymentFlow {
Verify,
Authorize,
Pay,
Capture,
Cancel,
}
struct ArchipelFlowStatus {
status: ArchipelPaymentStatus,
flow: ArchipelPaymentFlow,
}
impl ArchipelFlowStatus {
fn new(status: ArchipelPaymentStatus, flow: ArchipelPaymentFlow) -> Self {
Self { status, flow }
}
}
impl From<ArchipelFlowStatus> for AttemptStatus {
fn from(ArchipelFlowStatus { status, flow }: ArchipelFlowStatus) -> Self {
match status {
ArchipelPaymentStatus::Succeeded => match flow {
ArchipelPaymentFlow::Authorize => Self::Authorized,
ArchipelPaymentFlow::Pay
| ArchipelPaymentFlow::Verify
| ArchipelPaymentFlow::Capture => Self::Charged,
ArchipelPaymentFlow::Cancel => Self::Voided,
},
ArchipelPaymentStatus::Failed => match flow {
ArchipelPaymentFlow::Authorize | ArchipelPaymentFlow::Pay => {
Self::AuthorizationFailed
}
ArchipelPaymentFlow::Verify => Self::AuthenticationFailed,
ArchipelPaymentFlow::Capture => Self::CaptureFailed,
ArchipelPaymentFlow::Cancel => Self::VoidFailed,
},
}
}
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelOrderResponse {
id: String,
amount: Option<i64>,
currency: Option<Currency>,
captured_amount: Option<i64>,
authorized_amount: Option<i64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ArchipelErrorMessage {
pub code: String,
pub description: Option<String>,
}
impl Default for ArchipelErrorMessage {
fn default() -> Self {
Self {
code: consts::NO_ERROR_CODE.to_string(),
description: Some(consts::NO_ERROR_MESSAGE.to_string()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct ArchipelErrorMessageWithHttpCode {
error_message: ArchipelErrorMessage,
http_code: u16,
}
impl ArchipelErrorMessageWithHttpCode {
fn new(error_message: ArchipelErrorMessage, http_code: u16) -> Self {
Self {
error_message,
http_code,
}
}
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelTransactionMetadata {
pub transaction_id: String,
pub transaction_date: String,
pub financial_network_code: Option<String>,
pub issuer_transaction_id: Option<String>,
pub response_code: Option<String>,
pub authorization_code: Option<String>,
pub payment_account_reference: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelPaymentsResponse {
order: ArchipelOrderResponse,
transaction_id: String,
transaction_date: String,
transaction_result: ArchipelPaymentStatus,
error: Option<ArchipelErrorMessage>,
financial_network_code: Option<String>,
issuer_transaction_id: Option<String>,
response_code: Option<String>,
authorization_code: Option<String>,
payment_account_reference: Option<Secret<String>>,
}
impl From<&ArchipelPaymentsResponse> for ArchipelTransactionMetadata {
fn from(payment_response: &ArchipelPaymentsResponse) -> Self {
Self {
transaction_id: payment_response.transaction_id.clone(),
transaction_date: payment_response.transaction_date.clone(),
financial_network_code: payment_response.financial_network_code.clone(),
issuer_transaction_id: payment_response.issuer_transaction_id.clone(),
response_code: payment_response.response_code.clone(),
authorization_code: payment_response.authorization_code.clone(),
payment_account_reference: payment_response.payment_account_reference.clone(),
}
}
}
// AUTHORIZATION FLOW
impl TryFrom<(MinorUnit, &PaymentsAuthorizeRouterData)> for ArchipelPaymentInformation {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(amount, router_data): (MinorUnit, &PaymentsAuthorizeRouterData),
) -> Result<Self, Self::Error> {
let is_recurring_payment = router_data
.request
.mandate_id
.as_ref()
.and_then(|mandate_ids| mandate_ids.mandate_id.as_ref())
.is_some();
let is_subsequent_trx = router_data
.request
.mandate_id
.as_ref()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref())
.is_some();
let is_saved_card_payment = (router_data.request.is_mandate_payment())
| (router_data.request.setup_future_usage == Some(FutureUsage::OnSession))
| (router_data.payment_method_status == Some(PaymentMethodStatus::Active));
let certainty = if router_data.request.request_incremental_authorization {
if is_recurring_payment {
ArchipelPaymentCertainty::Final
} else {
ArchipelPaymentCertainty::Estimated
}
} else {
ArchipelPaymentCertainty::Final
};
let transaction_initiator = if is_recurring_payment {
ArchipelPaymentInitiator::Merchant
} else {
ArchipelPaymentInitiator::Customer
};
let order = ArchipelOrderRequest {
amount,
currency: router_data.request.currency.to_string(),
certainty,
initiator: transaction_initiator.clone(),
};
let cardholder = router_data
.get_billing_address()
.ok()
.and_then(|address| address.to_archipel_billing_address())
.map(|billing_address| ArchipelCardHolder {
billing_address: Some(billing_address),
});
// NOTE: Archipel does not accept `card.card_holder_name` field without `cardholder` field.
// So if `card_holder` is None, `card.card_holder_name` must also be None.
// However, the reverse is allowed — the `cardholder` field can exist without `card.card_holder_name`.
let card_holder_name = cardholder.as_ref().and_then(|_| {
router_data
.get_billing()
.ok()
.and_then(|billing| billing.get_optional_full_name())
});
let indicator_status = if is_subsequent_trx {
ArchipelCredentialIndicatorStatus::Subsequent
} else {
ArchipelCredentialIndicatorStatus::Initial
};
let stored_on_file =
is_saved_card_payment | router_data.request.is_customer_initiated_mandate_payment();
let credential_indicator = stored_on_file.then(|| ArchipelCredentialIndicator {
status: indicator_status.clone(),
recurring: Some(is_recurring_payment),
transaction_id: match indicator_status {
ArchipelCredentialIndicatorStatus::Initial => None,
ArchipelCredentialIndicatorStatus::Subsequent => {
router_data.request.get_optional_network_transaction_id()
}
},
});
Ok(Self {
order,
cardholder,
card_holder_name,
credential_indicator,
stored_on_file,
})
}
}
impl TryFrom<ArchipelRouterData<&PaymentsAuthorizeRouterData>>
for ArchipelCardAuthorizationRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ArchipelRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let ArchipelRouterData {
amount,
tenant_id,
router_data,
} = item;
let payment_information: ArchipelPaymentInformation =
ArchipelPaymentInformation::try_from((amount, router_data))?;
let payment_method_data = match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(ccard) => ArchipelCard::try_from((
payment_information.card_holder_name,
payment_information.cardholder.clone(),
ccard,
))?,
PaymentMethodData::CardDetailsForNetworkTransactionId(card_details) => {
ArchipelCard::try_from((
payment_information.card_holder_name,
payment_information.cardholder.clone(),
card_details,
))?
}
PaymentMethodData::CardRedirect(..)
| PaymentMethodData::Wallet(..)
| PaymentMethodData::PayLater(..)
| PaymentMethodData::BankRedirect(..)
| PaymentMethodData::BankDebit(..)
| PaymentMethodData::BankTransfer(..)
| PaymentMethodData::Crypto(..)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(..)
| PaymentMethodData::Upi(..)
| PaymentMethodData::Voucher(..)
| PaymentMethodData::GiftCard(..)
| PaymentMethodData::CardToken(..)
| PaymentMethodData::OpenBanking(..)
| PaymentMethodData::NetworkToken(..)
| PaymentMethodData::MobilePayment(..)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(..) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Archipel"),
))?
}
};
let three_ds: Option<Archipel3DS> = if item.router_data.is_three_ds() {
let auth_data = item
.router_data
.request
.get_authentication_data()
.change_context(errors::ConnectorError::NotSupported {
message: "Selected 3DS authentication method".to_string(),
connector: "archipel",
})?;
Some(Archipel3DS::from(auth_data))
} else {
None
};
Ok(Self {
order: payment_information.order,
cardholder: payment_information.cardholder,
card: payment_method_data,
three_ds,
credential_indicator: payment_information.credential_indicator,
stored_on_file: payment_information.stored_on_file,
tenant_id,
})
}
}
impl TryFrom<ArchipelRouterData<&PaymentsAuthorizeRouterData>>
for ArchipelWalletAuthorizationRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ArchipelRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let ArchipelRouterData {
amount,
tenant_id,
router_data,
} = item;
let payment_information = ArchipelPaymentInformation::try_from((amount, router_data))?;
let payment_method_data = match &item.router_data.request.payment_method_data {
PaymentMethodData::Wallet(wallet_data) => {
TokenizedCardData::try_from((wallet_data, &item.router_data.payment_method_token))?
}
PaymentMethodData::Card(..)
| PaymentMethodData::CardDetailsForNetworkTransactionId(..)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardRedirect(..)
| PaymentMethodData::PayLater(..)
| PaymentMethodData::BankRedirect(..)
| PaymentMethodData::BankDebit(..)
| PaymentMethodData::BankTransfer(..)
| PaymentMethodData::Crypto(..)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(..)
| PaymentMethodData::Upi(..)
| PaymentMethodData::Voucher(..)
| PaymentMethodData::GiftCard(..)
| PaymentMethodData::CardToken(..)
| PaymentMethodData::OpenBanking(..)
| PaymentMethodData::NetworkToken(..)
| PaymentMethodData::MobilePayment(..) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Archipel"),
))?,
};
Ok(Self {
order: payment_information.order,
cardholder: payment_information.cardholder,
card: payment_method_data.card_data.clone(),
wallet: payment_method_data.wallet_information.clone(),
three_ds: None,
credential_indicator: payment_information.credential_indicator,
stored_on_file: payment_information.stored_on_file,
tenant_id,
})
}
}
// Responses for AUTHORIZATION FLOW
impl TryFrom<PaymentsResponseRouterData<ArchipelPaymentsResponse>> for PaymentsAuthorizeRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<ArchipelPaymentsResponse>,
) -> Result<Self, Self::Error> {
if let Some(error) = item.response.error {
return Ok(Self {
response: Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),
..item.data
});
};
let capture_method = item
.data
.request
.capture_method
.ok_or_else(|| errors::ConnectorError::CaptureMethodNotSupported)?;
let (archipel_flow, is_incremental_allowed) = match capture_method {
CaptureMethod::Automatic => (ArchipelPaymentFlow::Pay, false),
_ => (
ArchipelPaymentFlow::Authorize,
item.data.request.request_incremental_authorization,
),
};
let connector_metadata: Option<serde_json::Value> =
ArchipelTransactionMetadata::from(&item.response)
.encode_to_value()
.ok();
let status: AttemptStatus =
ArchipelFlowStatus::new(item.response.transaction_result, archipel_flow).into();
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order.id),
charges: None,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/calida/transformers.rs | crates/hyperswitch_connectors/src/connectors/calida/transformers.rs | use std::collections::HashMap;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::ByteSliceExt,
pii::{Email, IpAddress},
request::Method,
types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self as connector_utils, PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
pub struct CalidaRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for CalidaRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct CalidaMetadataObject {
pub shop_name: String,
}
impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for CalidaMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
meta_data: &Option<common_utils::pii::SecretSerdeValue>,
) -> Result<Self, Self::Error> {
let metadata = connector_utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CalidaPaymentsRequest {
pub amount: FloatMajorUnit,
pub currency: enums::Currency,
pub payment_provider: String,
pub shop_name: String,
pub reference: String,
pub ip_address: Option<Secret<String, IpAddress>>,
pub first_name: Secret<String>,
pub last_name: Secret<String>,
pub billing_address_country_code_iso: enums::CountryAlpha2,
pub billing_address_city: String,
pub billing_address_line1: Secret<String>,
pub billing_address_postal_code: Secret<String>,
pub webhook_url: String,
pub success_url: String,
pub failure_url: String,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct CalidaCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&CalidaRouterData<&PaymentsAuthorizeRouterData>> for CalidaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CalidaRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual)
| Some(enums::CaptureMethod::ManualMultiple)
| Some(enums::CaptureMethod::Scheduled)
| Some(enums::CaptureMethod::SequentialAutomatic) => {
Err(errors::ConnectorError::FlowNotSupported {
flow: format!("{:?}", item.router_data.request.capture_method),
connector: "Calida".to_string(),
}
.into())
}
Some(enums::CaptureMethod::Automatic) | None => {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Wallet(WalletData::BluecodeRedirect {}) => {
let calida_mca_metadata =
CalidaMetadataObject::try_from(&item.router_data.connector_meta_data)?;
Self::try_from((item, &calida_mca_metadata))
}
_ => Err(
errors::ConnectorError::NotImplemented("Payment method".to_string()).into(),
),
}
}
}
}
}
impl
TryFrom<(
&CalidaRouterData<&PaymentsAuthorizeRouterData>,
&CalidaMetadataObject,
)> for CalidaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (
&CalidaRouterData<&PaymentsAuthorizeRouterData>,
&CalidaMetadataObject,
),
) -> Result<Self, Self::Error> {
let item = value.0;
Ok(Self {
amount: item.amount,
currency: item.router_data.request.currency,
payment_provider: "bluecode_payment".to_string(),
shop_name: value.1.shop_name.clone(),
reference: item.router_data.payment_id.clone(),
ip_address: item.router_data.request.get_ip_address_as_optional(),
first_name: item.router_data.get_billing_first_name()?,
last_name: item.router_data.get_billing_last_name()?,
billing_address_country_code_iso: item.router_data.get_billing_country()?,
billing_address_city: item.router_data.get_billing_city()?,
billing_address_line1: item.router_data.get_billing_line1()?,
billing_address_postal_code: item.router_data.get_billing_zip()?,
webhook_url: item.router_data.request.get_webhook_url()?,
success_url: item.router_data.request.get_router_return_url()?,
failure_url: item.router_data.request.get_router_return_url()?,
})
}
}
pub struct CalidaAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for CalidaAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl From<CalidaPaymentStatus> for common_enums::AttemptStatus {
fn from(item: CalidaPaymentStatus) -> Self {
match item {
CalidaPaymentStatus::ManualProcessing => Self::Pending,
CalidaPaymentStatus::Pending | CalidaPaymentStatus::PaymentInitiated => {
Self::AuthenticationPending
}
CalidaPaymentStatus::Failed => Self::Failure,
CalidaPaymentStatus::Completed => Self::Charged,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CalidaPaymentsResponse {
pub id: i64,
pub order_id: String,
pub amount: FloatMajorUnit,
pub currency: enums::Currency,
pub charged_amount: FloatMajorUnit,
pub charged_currency: enums::Currency,
pub status: CalidaPaymentStatus,
pub payment_link: url::Url,
pub etoken: Secret<String>,
pub payment_request_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CalidaSyncResponse {
pub id: Option<i64>,
pub order_id: String,
pub user_id: Option<i64>,
pub customer_id: Option<String>,
pub customer_email: Option<Email>,
pub customer_phone: Option<String>,
pub status: CalidaPaymentStatus,
pub payment_provider: Option<String>,
pub payment_connector: Option<String>,
pub payment_method: Option<String>,
pub payment_method_type: Option<String>,
pub shop_name: Option<String>,
pub sender_name: Option<String>,
pub sender_email: Option<String>,
pub description: Option<String>,
pub amount: FloatMajorUnit,
pub currency: enums::Currency,
pub charged_amount: Option<FloatMajorUnit>,
pub charged_amount_currency: Option<String>,
pub charged_fx_amount: Option<FloatMajorUnit>,
pub charged_fx_amount_currency: Option<enums::Currency>,
pub is_underpaid: Option<bool>,
pub billing_amount: Option<FloatMajorUnit>,
pub billing_currency: Option<String>,
pub language: Option<String>,
pub ip_address: Option<Secret<String, IpAddress>>,
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub billing_address_line1: Option<Secret<String>>,
pub billing_address_city: Option<Secret<String>>,
pub billing_address_postal_code: Option<Secret<String>>,
pub billing_address_country: Option<String>,
pub billing_address_country_code_iso: Option<enums::CountryAlpha2>,
pub shipping_address_country_code_iso: Option<enums::CountryAlpha2>,
pub success_url: Option<String>,
pub failure_url: Option<String>,
pub source: Option<String>,
pub bonus_code: Option<String>,
pub dob: Option<String>,
pub fees_amount: Option<f64>,
pub fx_margin_amount: Option<f64>,
pub fx_margin_percent: Option<f64>,
pub fees_percent: Option<f64>,
pub reseller_id: Option<String>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CalidaPaymentStatus {
Pending,
PaymentInitiated,
ManualProcessing,
Failed,
Completed,
}
impl<F, T> TryFrom<ResponseRouterData<F, CalidaPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CalidaPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let url = item.response.payment_link.clone();
let redirection_data = Some(RedirectForm::from((url, Method::Get)));
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.payment_request_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, CalidaSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CalidaSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: item.data.response,
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct CalidaRefundRequest {
pub amount: FloatMajorUnit,
}
impl<F> TryFrom<&CalidaRouterData<&RefundsRouterData<F>>> for CalidaRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &CalidaRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct CalidaErrorResponse {
pub message: String,
pub context_data: HashMap<String, Value>,
}
pub(crate) fn get_calida_webhook_event(
status: CalidaPaymentStatus,
) -> api_models::webhooks::IncomingWebhookEvent {
match status {
CalidaPaymentStatus::Completed => {
api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess
}
CalidaPaymentStatus::PaymentInitiated
| CalidaPaymentStatus::ManualProcessing
| CalidaPaymentStatus::Pending => {
api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing
}
CalidaPaymentStatus::Failed => {
api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure
}
}
}
pub(crate) fn get_webhook_object_from_body(
body: &[u8],
) -> CustomResult<CalidaSyncResponse, common_utils::errors::ParsingError> {
let webhook: CalidaSyncResponse = body.parse_struct("CalidaIncomingWebhook")?;
Ok(webhook)
}
pub fn sort_and_minify_json(value: &Value) -> Result<String, errors::ConnectorError> {
fn sort_value(val: &Value) -> Value {
match val {
Value::Object(map) => {
let mut entries: Vec<_> = map.iter().collect();
entries.sort_by_key(|(k, _)| k.to_owned());
let sorted_map: Map<String, Value> = entries
.into_iter()
.map(|(k, v)| (k.clone(), sort_value(v)))
.collect();
Value::Object(sorted_map)
}
Value::Array(arr) => Value::Array(arr.iter().map(sort_value).collect()),
_ => val.clone(),
}
}
let sorted_value = sort_value(value);
serde_json::to_string(&sorted_value)
.map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs | crates/hyperswitch_connectors/src/connectors/zen/transformers.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::InstantBankTransferFinland { .. }
| BankTransferData::InstantBankTransferPoland { .. }
| BankTransferData::IndonesianBankTransfer { .. }
| BankTransferData::MandiriVaBankTransfer { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
))?
}
};
Ok(Self::ApiRequest(Box::new(ApiRequest {
merchant_transaction_id: item.router_data.connector_request_reference_id.clone(),
payment_channel,
currency: item.router_data.request.currency,
payment_specific_data,
customer: get_customer(item.router_data, ip)?,
custom_ipn_url: item.router_data.request.get_webhook_url()?,
items: get_item_object(item.router_data)?,
amount,
})))
}
}
/*
impl TryFrom<(&types::PaymentsAuthorizeRouterData, &GooglePayWalletData)> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, gpay_pay_redirect_data): (&types::PaymentsAuthorizeRouterData, &GooglePayWalletData),
) -> Result<Self, Self::Error> {
let amount = utils::to_currency_base_unit(item.request.amount, item.request.currency)?;
let browser_info = item.request.get_browser_info()?;
let browser_details = get_browser_details(&browser_info)?;
let ip = browser_info.get_ip_address()?;
let payment_specific_data = ZenPaymentData {
browser_details,
//Connector Specific for wallet
payment_type: ZenPaymentTypes::ExternalPaymentToken,
token: Some(Secret::new(
gpay_pay_redirect_data.tokenization_data.token.clone(),
)),
card: None,
descriptor: item.get_description()?.chars().take(24).collect(),
return_verify_url: item.request.router_return_url.clone(),
};
Ok(Self::ApiRequest(Box::new(ApiRequest {
merchant_transaction_id: item.attempt_id.clone(),
payment_channel: ZenPaymentChannels::PclGooglepay,
currency: item.request.currency,
payment_specific_data,
customer: get_customer(item, ip)?,
custom_ipn_url: item.request.get_webhook_url()?,
items: get_item_object(item, amount.clone())?,
amount,
})))
}
}
*/
/*
impl
TryFrom<(
&types::PaymentsAuthorizeRouterData,
&Box<ApplePayRedirectData>,
)> for ZenPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, _apple_pay_redirect_data): (
&types::PaymentsAuthorizeRouterData,
&Box<ApplePayRedirectData>,
),
) -> Result<Self, Self::Error> {
let amount = utils::to_currency_base_unit(item.request.amount, item.request.currency)?;
let connector_meta = item.get_connector_meta()?;
let session: SessionObject = connector_meta
.parse_value("SessionObject")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let applepay_session_data = session
.apple_pay
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
let terminal_uuid = applepay_session_data
.terminal_uuid
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
let mut checkout_request = CheckoutRequest {
merchant_transaction_id: item.attempt_id.clone(),
specified_payment_channel: ZenPaymentChannels::PclApplepay,
currency: item.request.currency,
custom_ipn_url: item.request.get_webhook_url()?,
items: get_item_object(item, amount.clone())?,
amount,
terminal_uuid: Secret::new(terminal_uuid),
signature: None,
url_redirect: item.request.get_return_url()?,
};
checkout_request.signature = Some(get_checkout_signature(
&checkout_request,
&applepay_session_data,
)?);
Ok(Self::CheckoutRequest(Box::new(checkout_request)))
}
}
*/
impl
TryFrom<(
&ZenRouterData<&types::PaymentsAuthorizeRouterData>,
&WalletData,
)> for ZenPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, wallet_data): (
&ZenRouterData<&types::PaymentsAuthorizeRouterData>,
&WalletData,
),
) -> Result<Self, Self::Error> {
let amount = item.amount.to_owned();
let connector_meta = item.router_data.get_connector_meta()?;
let session: SessionObject = connector_meta
.parse_value("SessionObject")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let (specified_payment_channel, session_data) = match wallet_data {
WalletData::ApplePayRedirect(_) => (
ZenPaymentChannels::PclApplepay,
session
.apple_pay
.ok_or(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?,
),
WalletData::GooglePayRedirect(_) => (
ZenPaymentChannels::PclGooglepay,
session
.google_pay
.ok_or(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Google Pay".to_string(),
})?,
),
WalletData::WeChatPayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::ApplePay(_)
| WalletData::GooglePay(_)
| WalletData::BluecodeRedirect {}
| WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::WeChatPayQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
))?,
};
let terminal_uuid = session_data
.terminal_uuid
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.expose();
let mut checkout_request = CheckoutRequest {
merchant_transaction_id: item.router_data.connector_request_reference_id.clone(),
specified_payment_channel,
currency: item.router_data.request.currency,
custom_ipn_url: item.router_data.request.get_webhook_url()?,
items: get_item_object(item.router_data)?,
amount,
terminal_uuid: Secret::new(terminal_uuid),
signature: None,
url_redirect: item.router_data.request.get_router_return_url()?,
};
checkout_request.signature =
Some(get_checkout_signature(&checkout_request, &session_data)?);
Ok(Self::CheckoutRequest(Box::new(checkout_request)))
}
}
fn get_checkout_signature(
checkout_request: &CheckoutRequest,
session: &WalletSessionData,
) -> Result<Secret<String>, error_stack::Report<errors::ConnectorError>> {
let pay_wall_secret = session
.pay_wall_secret
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
let mut signature_data = get_signature_data(checkout_request)?;
signature_data.push_str(&pay_wall_secret.expose());
let payload_digest = digest::digest(&digest::SHA256, signature_data.as_bytes());
let mut signature = hex::encode(payload_digest);
signature.push_str(";sha256");
Ok(Secret::new(signature))
}
/// Fields should be in alphabetical order
fn get_signature_data(
checkout_request: &CheckoutRequest,
) -> Result<String, errors::ConnectorError> {
let specified_payment_channel = match checkout_request.specified_payment_channel {
ZenPaymentChannels::PclCard => "pcl_card",
ZenPaymentChannels::PclGooglepay => "pcl_googlepay",
ZenPaymentChannels::PclApplepay => "pcl_applepay",
ZenPaymentChannels::PclBoacompraBoleto => "pcl_boacompra_boleto",
ZenPaymentChannels::PclBoacompraEfecty => "pcl_boacompra_efecty",
ZenPaymentChannels::PclBoacompraMultibanco => "pcl_boacompra_multibanco",
ZenPaymentChannels::PclBoacompraPagoefectivo => "pcl_boacompra_pagoefectivo",
ZenPaymentChannels::PclBoacompraPix => "pcl_boacompra_pix",
ZenPaymentChannels::PclBoacompraPse => "pcl_boacompra_pse",
ZenPaymentChannels::PclBoacompraRedcompra => "pcl_boacompra_redcompra",
ZenPaymentChannels::PclBoacompraRedpagos => "pcl_boacompra_redpagos",
};
let mut signature_data = vec![
format!("amount={}", checkout_request.amount),
format!("currency={}", checkout_request.currency),
format!("customipnurl={}", checkout_request.custom_ipn_url),
];
for index in 0..checkout_request.items.len() {
let prefix = format!("items[{index}].");
let checkout_request_items = checkout_request
.items
.get(index)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
signature_data.push(format!(
"{prefix}lineamounttotal={}",
checkout_request_items.line_amount_total
));
signature_data.push(format!("{prefix}name={}", checkout_request_items.name));
signature_data.push(format!("{prefix}price={}", checkout_request_items.price));
signature_data.push(format!(
"{prefix}quantity={}",
checkout_request_items.quantity
));
}
signature_data.push(format!(
"merchanttransactionid={}",
checkout_request.merchant_transaction_id
));
signature_data.push(format!(
"specifiedpaymentchannel={specified_payment_channel}"
));
signature_data.push(format!(
"terminaluuid={}",
checkout_request.terminal_uuid.peek()
));
signature_data.push(format!("urlredirect={}", checkout_request.url_redirect));
let signature = signature_data.join("&");
Ok(signature.to_lowercase())
}
fn get_customer(
item: &types::PaymentsAuthorizeRouterData,
ip: Secret<String, pii::IpAddress>,
) -> Result<ZenCustomerDetails, error_stack::Report<errors::ConnectorError>> {
Ok(ZenCustomerDetails {
email: item.request.get_email()?,
ip,
})
}
fn get_item_object(
item: &types::PaymentsAuthorizeRouterData,
) -> Result<Vec<ZenItemObject>, error_stack::Report<errors::ConnectorError>> {
let order_details = item.request.get_order_details()?;
order_details
.iter()
.map(|data| {
Ok(ZenItemObject {
name: data.product_name.clone(),
quantity: data.quantity,
price: utils::to_currency_base_unit_with_zero_decimal_check(
data.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future.
item.request.currency,
)?,
line_amount_total: (f64::from(data.quantity)
* utils::to_currency_base_unit_asf64(
data.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future.
item.request.currency,
)?)
.to_string(),
})
})
.collect::<Result<_, _>>()
}
fn get_browser_details(
browser_info: &BrowserInformation,
) -> CustomResult<ZenBrowserDetails, errors::ConnectorError> {
let screen_height = browser_info
.screen_height
.get_required_value("screen_height")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "screen_height",
})?;
let screen_width = browser_info
.screen_width
.get_required_value("screen_width")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "screen_width",
})?;
let window_size = match (screen_height, screen_width) {
(250, 400) => "01",
(390, 400) => "02",
(500, 600) => "03",
(600, 400) => "04",
_ => "05",
}
.to_string();
Ok(ZenBrowserDetails {
color_depth: browser_info.get_color_depth()?.to_string(),
java_enabled: browser_info.get_java_enabled()?,
lang: browser_info.get_language()?,
screen_height: screen_height.to_string(),
screen_width: screen_width.to_string(),
timezone: browser_info.get_time_zone()?.to_string(),
accept_header: browser_info.get_accept_header()?,
user_agent: browser_info.get_user_agent()?,
window_size,
})
}
impl TryFrom<&ZenRouterData<&types::PaymentsAuthorizeRouterData>> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ZenRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(card) => Self::try_from((item, card)),
PaymentMethodData::Wallet(wallet_data) => Self::try_from((item, wallet_data)),
PaymentMethodData::Voucher(voucher_data) => Self::try_from((item, voucher_data)),
PaymentMethodData::BankTransfer(bank_transfer_data) => {
Self::try_from((item, bank_transfer_data))
}
PaymentMethodData::BankRedirect(bank_redirect_data) => {
Self::try_from(bank_redirect_data)
}
PaymentMethodData::PayLater(paylater_data) => Self::try_from(paylater_data),
PaymentMethodData::BankDebit(bank_debit_data) => Self::try_from(bank_debit_data),
PaymentMethodData::CardRedirect(car_redirect_data) => Self::try_from(car_redirect_data),
PaymentMethodData::GiftCard(gift_card_data) => Self::try_from(gift_card_data.as_ref()),
PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
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 {}
| BankRedirectData::OpenBanking { .. } => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
)
.into()),
}
}
}
impl TryFrom<&PayLaterData> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &PayLaterData) -> Result<Self, Self::Error> {
match value {
PayLaterData::KlarnaRedirect { .. }
| PayLaterData::KlarnaSdk { .. }
| PayLaterData::AffirmRedirect {}
| PayLaterData::AfterpayClearpayRedirect { .. }
| PayLaterData::PayBrightRedirect {}
| PayLaterData::WalleyRedirect {}
| PayLaterData::AlmaRedirect {}
| PayLaterData::FlexitiRedirect {}
| PayLaterData::AtomeRedirect {}
| PayLaterData::BreadpayRedirect {}
| PayLaterData::PayjustnowRedirect {} => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
)
.into()),
}
}
}
impl TryFrom<&BankDebitData> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &BankDebitData) -> Result<Self, Self::Error> {
match value {
BankDebitData::AchBankDebit { .. }
| BankDebitData::SepaBankDebit { .. }
| BankDebitData::BecsBankDebit { .. }
| BankDebitData::BacsBankDebit { .. }
| BankDebitData::SepaGuarenteedBankDebit { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
)
.into())
}
}
}
}
impl TryFrom<&CardRedirectData> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &CardRedirectData) -> Result<Self, Self::Error> {
match value {
CardRedirectData::Knet {}
| CardRedirectData::Benefit {}
| CardRedirectData::MomoAtm {}
| CardRedirectData::CardRedirect {} => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
)
.into()),
}
}
}
impl TryFrom<&GiftCardData> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &GiftCardData) -> Result<Self, Self::Error> {
match value {
GiftCardData::PaySafeCard {}
| GiftCardData::Givex(_)
| GiftCardData::BhnCardNetwork(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
)
.into()),
}
}
}
// PaymentsResponse
#[derive(Debug, Default, Deserialize, Clone, strum::Display, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum ZenPaymentStatus {
Authorized,
Accepted,
#[default]
Pending,
Rejected,
Canceled,
}
impl ForeignTryFrom<(ZenPaymentStatus, Option<ZenActions>)> for enums::AttemptStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(item: (ZenPaymentStatus, Option<ZenActions>)) -> Result<Self, Self::Error> {
let (item_txn_status, item_action_status) = item;
Ok(match item_txn_status {
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs | crates/hyperswitch_connectors/src/connectors/globalpay/response.rs | use common_enums::Currency;
use common_utils::types::StringMinorUnit;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::utils::deserialize_optional_currency;
#[derive(Debug, Serialize, Deserialize)]
pub struct GlobalpayPaymentsResponse {
pub status: GlobalpayPaymentStatus,
pub payment_method: Option<PaymentMethod>,
pub id: String,
pub amount: Option<StringMinorUnit>,
#[serde(deserialize_with = "deserialize_optional_currency")]
pub currency: Option<Currency>,
pub reference: Option<String>,
}
#[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,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentMethod {
pub apm: Option<Apm>,
pub card: Option<Card>,
pub id: Option<Secret<String>>,
pub message: Option<String>,
pub result: Option<String>,
}
/// Data associated with the response of an APM transaction.
#[derive(Debug, Serialize, Deserialize)]
pub struct Apm {
#[serde(alias = "provider_redirect_url")]
pub redirect_url: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Card {
pub brand_reference: Option<Secret<String>>,
}
/// 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,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct GlobalpayPaymentMethodsResponse {
#[serde(rename = "id")]
pub payment_method_token_id: Option<Secret<String>>,
pub card: Card,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs | crates/hyperswitch_connectors/src/connectors/globalpay/transformers.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, PaymentMethodToken, RouterData},
router_flow_types::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefreshTokenRouterData, RefundExecuteRouterData, RefundsRouterData,
TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
consts::{self, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use rand::distributions::DistString;
use serde::{Deserialize, Serialize};
use url::Url;
use super::{
requests::{
self, ApmProvider, GlobalPayRouterData, GlobalpayCancelRouterData,
GlobalpayPaymentsRequest, GlobalpayRefreshTokenRequest, Initiator, PaymentMethodData,
Sequence, StoredCredential,
},
response::{GlobalpayPaymentStatus, GlobalpayPaymentsResponse, GlobalpayRefreshTokenResponse},
};
use crate::{
connectors::globalpay::{
requests::CommonPaymentMethodData, response::GlobalpayPaymentMethodsResponse,
},
types::{PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, construct_captures_response_hashmap, CardData, ForeignTryFrom,
MultipleCaptureSyncResponse, PaymentMethodTokenizationRequestData,
PaymentsAuthorizeRequestData, RouterData as _, WalletData,
},
};
impl<T> From<(StringMinorUnit, T)> for GlobalPayRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
impl<T> From<(Option<StringMinorUnit>, T)> for GlobalpayCancelRouterData<T> {
fn from((amount, item): (Option<StringMinorUnit>, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
type Error = error_stack::Report<errors::ConnectorError>;
#[derive(Debug, Serialize, Deserialize)]
pub struct GlobalPayMeta {
account_name: Secret<String>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for GlobalPayMeta {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
impl TryFrom<&GlobalPayRouterData<&PaymentsAuthorizeRouterData>> for GlobalpayPaymentsRequest {
type Error = Error;
fn try_from(
item: &GlobalPayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let metadata = GlobalPayMeta::try_from(&item.router_data.connector_meta_data)?;
let account_name = metadata.account_name;
let (initiator, stored_credential, connector_mandate_id) =
if item.router_data.request.is_mandate_payment() {
let connector_mandate_id =
item.router_data
.request
.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_ids,
)) => connector_mandate_ids.get_connector_mandate_id(),
_ => None,
});
let initiator = Some(match item.router_data.request.off_session {
Some(true) => Initiator::Merchant,
_ => Initiator::Payer,
});
let stored_credential = Some(StoredCredential {
model: Some(if connector_mandate_id.is_some() {
requests::Model::Recurring
} else {
requests::Model::Unscheduled
}),
sequence: Some(if connector_mandate_id.is_some() {
Sequence::Subsequent
} else {
Sequence::First
}),
});
(initiator, stored_credential, connector_mandate_id)
} else {
(None, None, None)
};
let payment_method = match &item.router_data.request.payment_method_data {
payment_method_data::PaymentMethodData::Card(ccard) => {
if item.router_data.is_three_ds() {
return Err(errors::ConnectorError::NotSupported {
message: "3DS flow".to_string(),
connector: "Globalpay",
}
.into());
}
requests::GlobalPayPaymentMethodData::Common(CommonPaymentMethodData {
payment_method_data: PaymentMethodData::Card(requests::Card {
number: ccard.card_number.clone(),
expiry_month: ccard.card_exp_month.clone(),
expiry_year: ccard.get_card_expiry_year_2_digit()?,
cvv: ccard.card_cvc.clone(),
}),
entry_mode: Default::default(),
})
}
payment_method_data::PaymentMethodData::Wallet(wallet_data) => {
requests::GlobalPayPaymentMethodData::Common(CommonPaymentMethodData {
payment_method_data: get_wallet_data(wallet_data)?,
entry_mode: Default::default(),
})
}
payment_method_data::PaymentMethodData::BankRedirect(bank_redirect) => {
requests::GlobalPayPaymentMethodData::Common(CommonPaymentMethodData {
payment_method_data: PaymentMethodData::try_from(bank_redirect)?,
entry_mode: Default::default(),
})
}
payment_method_data::PaymentMethodData::MandatePayment => {
requests::GlobalPayPaymentMethodData::Mandate(requests::MandatePaymentMethodData {
entry_mode: Default::default(),
id: connector_mandate_id,
})
}
_ => Err(errors::ConnectorError::NotImplemented(
"Payment methods".to_string(),
))?,
};
Ok(Self {
account_name,
amount: Some(item.amount.to_owned()),
currency: item.router_data.request.currency.to_string(),
reference: item.router_data.connector_request_reference_id.to_string(),
country: item.router_data.get_billing_country()?,
capture_mode: Some(requests::CaptureMode::from(
item.router_data.request.capture_method,
)),
payment_method,
notifications: Some(requests::Notifications {
return_url: get_return_url(item.router_data),
status_url: item.router_data.request.webhook_url.clone(),
cancel_url: get_return_url(item.router_data),
}),
stored_credential,
channel: Default::default(),
initiator,
})
}
}
impl TryFrom<&GlobalPayRouterData<&PaymentsCaptureRouterData>>
for requests::GlobalpayCaptureRequest
{
type Error = Error;
fn try_from(
value: &GlobalPayRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: Some(value.amount.to_owned()),
capture_sequence: value
.router_data
.request
.multiple_capture_data
.clone()
.map(|mcd| {
if mcd.capture_sequence == 1 {
Sequence::First
} else {
Sequence::Subsequent
}
}),
reference: value
.router_data
.request
.multiple_capture_data
.as_ref()
.map(|mcd| mcd.capture_reference.clone()),
})
}
}
impl TryFrom<&TokenizationRouterData> for requests::GlobalPayPaymentMethodsRequest {
type Error = Error;
fn try_from(item: &TokenizationRouterData) -> Result<Self, Self::Error> {
if !item.request.is_mandate_payment() {
return Err(errors::ConnectorError::FlowNotSupported {
flow: "Tokenization apart from Mandates".to_string(),
connector: "Globalpay".to_string(),
}
.into());
}
Ok(Self {
reference: item.connector_request_reference_id.clone(),
usage_mode: Some(requests::UsageMode::Multiple),
card: match &item.request.payment_method_data {
payment_method_data::PaymentMethodData::Card(card_data) => Some(requests::Card {
number: card_data.card_number.clone(),
expiry_month: card_data.card_exp_month.clone(),
expiry_year: card_data.get_card_expiry_year_2_digit()?,
cvv: card_data.card_cvc.clone(),
}),
_ => None,
},
})
}
}
impl TryFrom<&GlobalpayCancelRouterData<&PaymentsCancelRouterData>>
for requests::GlobalpayCancelRequest
{
type Error = Error;
fn try_from(
value: &GlobalpayCancelRouterData<&PaymentsCancelRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: value.amount.clone(),
})
}
}
pub struct GlobalpayAuthType {
pub app_id: Secret<String>,
pub key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for GlobalpayAuthType {
type Error = Error;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
app_id: key1.to_owned(),
key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<GlobalpayRefreshTokenResponse> for AccessToken {
type Error = error_stack::Report<ParsingError>;
fn try_from(item: GlobalpayRefreshTokenResponse) -> Result<Self, Self::Error> {
Ok(Self {
token: item.token,
expires: item.seconds_to_expire,
})
}
}
impl TryFrom<&RefreshTokenRouterData> for GlobalpayRefreshTokenRequest {
type Error = Error;
fn try_from(item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
let globalpay_auth = GlobalpayAuthType::try_from(&item.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)
.attach_printable("Could not convert connector_auth to globalpay_auth")?;
let nonce = rand::distributions::Alphanumeric.sample_string(&mut rand::thread_rng(), 12);
let nonce_with_api_key = format!("{}{}", nonce, globalpay_auth.key.peek());
let secret_vec = crypto::Sha512
.generate_digest(nonce_with_api_key.as_bytes())
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("error creating request nonce")?;
let secret = hex::encode(secret_vec);
Ok(Self {
app_id: globalpay_auth.app_id,
nonce: Secret::new(nonce),
secret: Secret::new(secret),
grant_type: "client_credentials".to_string(),
})
}
}
impl From<GlobalpayPaymentStatus> for common_enums::AttemptStatus {
fn from(item: GlobalpayPaymentStatus) -> Self {
match item {
GlobalpayPaymentStatus::Captured | GlobalpayPaymentStatus::Funded => Self::Charged,
GlobalpayPaymentStatus::Declined | GlobalpayPaymentStatus::Rejected => Self::Failure,
GlobalpayPaymentStatus::Preauthorized => Self::Authorized,
GlobalpayPaymentStatus::Reversed => Self::Voided,
GlobalpayPaymentStatus::Initiated => Self::AuthenticationPending,
GlobalpayPaymentStatus::Pending => Self::Pending,
}
}
}
impl From<GlobalpayPaymentStatus> for common_enums::RefundStatus {
fn from(item: GlobalpayPaymentStatus) -> Self {
match item {
GlobalpayPaymentStatus::Captured | GlobalpayPaymentStatus::Funded => Self::Success,
GlobalpayPaymentStatus::Declined | GlobalpayPaymentStatus::Rejected => Self::Failure,
GlobalpayPaymentStatus::Initiated | GlobalpayPaymentStatus::Pending => Self::Pending,
_ => Self::Pending,
}
}
}
impl From<Option<common_enums::CaptureMethod>> for requests::CaptureMode {
fn from(capture_method: Option<common_enums::CaptureMethod>) -> Self {
match capture_method {
Some(common_enums::CaptureMethod::Manual) => Self::Later,
Some(common_enums::CaptureMethod::ManualMultiple) => Self::Multiple,
_ => Self::Auto,
}
}
}
// }
impl<F, T> TryFrom<ResponseRouterData<F, GlobalpayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, GlobalpayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = common_enums::AttemptStatus::from(item.response.status);
let redirect_url = item
.response
.payment_method
.as_ref()
.and_then(|payment_method| {
payment_method
.apm
.as_ref()
.and_then(|apm| apm.redirect_url.as_ref())
})
.filter(|redirect_str| !redirect_str.is_empty())
.map(|url| {
Url::parse(url).change_context(errors::ConnectorError::FailedToObtainIntegrationUrl)
})
.transpose()?;
let redirection_data = redirect_url.map(|url| RedirectForm::from((url, Method::Get)));
let payment_method_token = item.data.get_payment_method_token();
let status_code = item.http_code;
let mandate_reference = payment_method_token.ok().and_then(|token| match token {
PaymentMethodToken::Token(token_string) => Some(MandateReference {
connector_mandate_id: Some(token_string.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}),
_ => None,
});
let response = match status {
common_enums::AttemptStatus::Failure => Err(Box::new(ErrorResponse {
message: item
.response
.payment_method
.as_ref()
.and_then(|payment_method| payment_method.message.clone())
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
code: item
.response
.payment_method
.as_ref()
.and_then(|payment_method| payment_method.result.clone())
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
reason: item
.response
.payment_method
.as_ref()
.and_then(|payment_method| payment_method.message.clone()),
status_code,
attempt_status: Some(status),
connector_transaction_id: Some(item.response.id.clone()),
network_decline_code: item
.response
.payment_method
.as_ref()
.and_then(|payment_method| payment_method.result.clone()),
network_advice_code: None,
network_error_message: item
.response
.payment_method
.as_ref()
.and_then(|payment_method| payment_method.message.clone()),
connector_metadata: None,
})),
_ => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.reference.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
};
Ok(Self {
status,
response: response.map_err(|err| *err),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, GlobalpayPaymentMethodsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, GlobalpayPaymentMethodsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let token = item
.response
.payment_method_token_id
.clone()
.unwrap_or_default();
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: token.expose(),
}),
..item.data
})
}
}
impl
ForeignTryFrom<(
PaymentsSyncResponseRouterData<GlobalpayPaymentsResponse>,
bool,
)> for PaymentsSyncRouterData
{
type Error = Error;
fn foreign_try_from(
(value, is_multiple_capture_sync): (
PaymentsSyncResponseRouterData<GlobalpayPaymentsResponse>,
bool,
),
) -> Result<Self, Self::Error> {
if is_multiple_capture_sync {
let capture_sync_response_list =
construct_captures_response_hashmap(vec![value.response])?;
Ok(Self {
response: Ok(PaymentsResponseData::MultipleCaptureResponse {
capture_sync_response_list,
}),
..value.data
})
} else {
Self::try_from(value)
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, GlobalpayRefreshTokenResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<ParsingError>;
fn try_from(
item: ResponseRouterData<F, GlobalpayRefreshTokenResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.token,
expires: item.response.seconds_to_expire,
}),
..item.data
})
}
}
impl<F> TryFrom<&GlobalPayRouterData<&RefundsRouterData<F>>> for requests::GlobalpayRefundRequest {
type Error = Error;
fn try_from(item: &GlobalPayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
impl TryFrom<RefundsResponseRouterData<Execute, GlobalpayPaymentsResponse>>
for RefundExecuteRouterData
{
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<Execute, GlobalpayPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status: common_enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, GlobalpayPaymentsResponse>>
for RefundsRouterData<RSync>
{
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<RSync, GlobalpayPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status: common_enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct GlobalpayErrorResponse {
pub error_code: String,
pub detailed_error_code: String,
pub detailed_error_description: String,
}
fn get_return_url(item: &PaymentsAuthorizeRouterData) -> Option<String> {
match item.request.payment_method_data.clone() {
payment_method_data::PaymentMethodData::Wallet(
payment_method_data::WalletData::PaypalRedirect(_),
) => {
// Return URL handling for PayPal via Globalpay:
// - PayPal inconsistency: Return URLs work with HTTP, but cancel URLs require HTTPS
// - Local development: When testing locally, expose your server via HTTPS and replace
// the base URL with an HTTPS URL to ensure proper cancellation flow
// - Refer to commit 6499d429da87 for more information
item.request.complete_authorize_url.clone()
}
_ => item.request.router_return_url.clone(),
}
}
fn get_wallet_data(
wallet_data: &payment_method_data::WalletData,
) -> Result<PaymentMethodData, Error> {
match wallet_data {
payment_method_data::WalletData::PaypalRedirect(_) => {
Ok(PaymentMethodData::Apm(requests::Apm {
provider: Some(ApmProvider::Paypal),
}))
}
payment_method_data::WalletData::GooglePay(_) => {
Ok(PaymentMethodData::DigitalWallet(requests::DigitalWallet {
provider: Some(requests::DigitalWalletProvider::PayByGoogle),
payment_token: wallet_data.get_wallet_token_as_json("Google Pay".to_string())?,
}))
}
_ => Err(errors::ConnectorError::NotImplemented(
"Payment method".to_string(),
))?,
}
}
impl TryFrom<&payment_method_data::BankRedirectData> for PaymentMethodData {
type Error = Error;
fn try_from(value: &payment_method_data::BankRedirectData) -> Result<Self, Self::Error> {
match value {
payment_method_data::BankRedirectData::Eps { .. } => Ok(Self::Apm(requests::Apm {
provider: Some(ApmProvider::Eps),
})),
payment_method_data::BankRedirectData::Giropay { .. } => Ok(Self::Apm(requests::Apm {
provider: Some(ApmProvider::Giropay),
})),
payment_method_data::BankRedirectData::Ideal { .. } => Ok(Self::Apm(requests::Apm {
provider: Some(ApmProvider::Ideal),
})),
payment_method_data::BankRedirectData::Sofort { .. } => Ok(Self::Apm(requests::Apm {
provider: Some(ApmProvider::Sofort),
})),
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
impl MultipleCaptureSyncResponse for GlobalpayPaymentsResponse {
fn get_connector_capture_id(&self) -> String {
self.id.clone()
}
fn get_capture_attempt_status(&self) -> common_enums::AttemptStatus {
common_enums::AttemptStatus::from(self.status)
}
fn is_capture_response(&self) -> bool {
true
}
fn get_amount_captured(&self) -> Result<Option<MinorUnit>, error_stack::Report<ParsingError>> {
match self.amount.clone() {
Some(amount) => {
let minor_amount = StringMinorUnitForConnector::convert_back(
&StringMinorUnitForConnector,
amount,
self.currency.unwrap_or_default(), //it is ignored in convert_back function
)?;
Ok(Some(minor_amount))
}
None => Ok(None),
}
}
fn get_connector_reference_id(&self) -> Option<String> {
self.reference.clone()
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs | crates/hyperswitch_connectors/src/connectors/globalpay/requests.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 {
pub account_name: Secret<String>,
pub amount: Option<StringMinorUnit>,
pub currency: String,
pub reference: String,
pub country: api_models::enums::CountryAlpha2,
pub capture_mode: Option<CaptureMode>,
pub notifications: Option<Notifications>,
pub payment_method: GlobalPayPaymentMethodData,
pub channel: Channel,
pub initiator: Option<Initiator>,
pub stored_credential: Option<StoredCredential>,
}
#[derive(Debug, Serialize)]
pub struct GlobalpayRefreshTokenRequest {
pub app_id: Secret<String>,
pub nonce: Secret<String>,
pub secret: Secret<String>,
pub grant_type: String,
}
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Notifications {
pub return_url: Option<String>,
pub status_url: Option<String>,
pub cancel_url: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PaymentMethodData {
Card(Card),
Apm(Apm),
DigitalWallet(DigitalWallet),
Token(TokenizationData),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CommonPaymentMethodData {
#[serde(flatten)]
pub payment_method_data: PaymentMethodData,
pub entry_mode: PaymentMethodEntryMode,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MandatePaymentMethodData {
pub entry_mode: PaymentMethodEntryMode,
pub id: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GlobalPayPaymentMethodData {
Common(CommonPaymentMethodData),
Mandate(MandatePaymentMethodData),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Apm {
/// A string used to identify the payment method provider being used to execute this
/// transaction.
pub provider: Option<ApmProvider>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Card {
pub cvv: Secret<String>,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
pub number: cards::CardNumber,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct TokenizationData {
pub brand_reference: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct DigitalWallet {
/// Identifies who provides the digital wallet for the Payer.
pub provider: Option<DigitalWalletProvider>,
/// A token that represents, or is the payment method, stored with the digital wallet.
pub payment_token: Option<serde_json::Value>,
}
/// Stored data information used to create a transaction.
#[derive(Debug, Serialize, Deserialize)]
pub struct StoredCredential {
/// Indicates the transaction processing model being executed when using stored
/// credentials.
pub model: Option<Model>,
/// Indicates the order of this transaction in the sequence of a planned repeating
/// transaction processing model.
pub sequence: Option<Sequence>,
}
/// Indicates whether the transaction is to be captured automatically, later or later using
/// more than 1 partial capture.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CaptureMode {
/// If a transaction is authorized, funds will exchange between the payer and
/// merchant automatically and as soon as possible.
Auto,
/// If a transaction is authorized, funds will not exchange between the payer and
/// merchant automatically and will require a subsequent separate action to capture that
/// transaction and start the funding process. Only one successful capture is permitted.
Later,
/// If a transaction is authorized, funds will not exchange between the payer
/// and merchant automatically. One or more subsequent separate capture actions are required
/// to capture that transaction in parts and start the funding process for the part captured.
/// One or many successful capture are permitted once the total amount captured is within a
/// range of the original authorized amount.'
Multiple,
}
/// Describes whether the transaction was processed in a face to face(CP) scenario or a
/// Customer Not Present (CNP) scenario.
#[derive(Debug, Default, Serialize, Deserialize)]
pub enum Channel {
#[default]
#[serde(rename = "CNP")]
/// A Customer NOT Present transaction is when the payer and the merchant are not
/// together when exchanging payment method information to fulfill a transaction. e.g. a
/// transaction executed from a merchant's website or over the phone
CustomerNotPresent,
#[serde(rename = "CP")]
/// A Customer Present transaction is when the payer and the merchant are in direct
/// face to face contact when exchanging payment method information to fulfill a transaction.
/// e.g. in a store and paying at the counter that is attended by a clerk.
CustomerPresent,
}
/// Indicates whether the Merchant or the Payer initiated the creation of a transaction.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Initiator {
/// The transaction was initiated by the merchant, who is getting paid by the
/// payer.'
Merchant,
/// The transaction was initiated by the customer who is paying the merchant.
Payer,
}
/// A string used to identify the payment method provider being used to execute this
/// transaction.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApmProvider {
Giropay,
Ideal,
Paypal,
Sofort,
Eps,
Testpay,
}
/// Identifies who provides the digital wallet for the Payer.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DigitalWalletProvider {
Applepay,
PayByGoogle,
}
/// Indicates how the payment method information was obtained by the Merchant for this
/// transaction.
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentMethodEntryMode {
/// A CP channel entry mode where the payment method information was obtained from a
/// chip. E.g. card is inserted into a device to read the chip.
Chip,
/// A CP channel entry mode where the payment method information was
/// obtained by bringing the payment method to close proximity of a device. E.g. tap a cardon
/// or near a device to exchange card information.
ContactlessChip,
/// A CP channel entry mode where the payment method information was
/// obtained by bringing the payment method to close proximity of a device and also swiping
/// the card. E.g. tap a card on or near a device and swipe it through device to exchange
/// card information
ContactlessSwipe,
#[default]
/// A CNP channel entry mode where the payment method was obtained via a browser.
Ecom,
/// A CNP channel entry mode where the payment method was obtained via an
/// application and applies to digital wallets only.
InApp,
/// A CNP channel entry mode where the payment method was obtained via postal mail.
Mail,
/// A CP channel entry mode where the payment method information was obtained by
/// manually keying the payment method information into the device.
Manual,
/// A CNP channel entry mode where the payment method information was obtained over
/// the phone or via postal mail.
Moto,
/// A CNP channel entry mode where the payment method was obtained over the
/// phone.
Phone,
/// A CP channel entry mode where the payment method information was obtained from
/// swiping a magnetic strip. E.g. card's magnetic strip is swiped through a device to read
/// the card information.
Swipe,
}
/// Indicates the transaction processing model being executed when using stored
/// credentials.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Model {
/// The transaction is a repeat transaction initiated by the merchant and
/// taken using the payment method stored with the merchant, as part of an agreed schedule of
/// transactions and where the amount is known and agreed in advanced. For example the
/// payment in full of a good in fixed installments over a defined period of time.'
Installment,
/// The transaction is a repeat transaction initiated by the merchant and taken
/// using the payment method stored with the merchant, as part of an agreed schedule of
/// transactions.
Recurring,
/// The transaction is a repeat transaction initiated by the merchant and
/// taken using the payment method stored with the merchant, as part of an agreed schedule of
/// transactions. The amount taken is based on the usage by the payer of the good or service.
/// for example a monthly mobile phone bill.
Subscription,
/// the transaction is adhoc or unscheduled. For example a payer visiting a
/// merchant to make purchase using the payment method stored with the merchant.
Unscheduled,
}
/// Indicates the order of this transaction in the sequence of a planned repeating
/// transaction processing model.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Sequence {
First,
Last,
Subsequent,
}
#[derive(Default, Debug, Serialize)]
pub struct GlobalpayRefundRequest {
pub amount: StringMinorUnit,
}
#[derive(Default, Debug, Serialize)]
pub struct GlobalpayCaptureRequest {
pub amount: Option<StringMinorUnit>,
pub capture_sequence: Option<Sequence>,
pub reference: Option<String>,
}
#[derive(Default, Debug, Serialize)]
pub struct GlobalpayCancelRequest {
pub amount: Option<StringMinorUnit>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum UsageMode {
/// This value must be used if using the Hosted Fields or the Drop-in UI integration types.
/// When creating the payment method token, this option ensures the payment method token is temporary and will be removed once a transaction is executed or after a short period of time.
#[default]
Single,
/// When creating the payment method token, this indicates it is permanent and can be used to create many transactions.
Multiple,
/// When using the payment method token to transaction process, this indicates to use the card number also known as the PAN or FPAN when both the card number and the network token are available.
UseCardNumber,
/// When using the payment method token to transaction process, this indicates to use the network token instead of the card number if both are available.
UseNetworkToken,
}
#[derive(Default, Debug, Serialize)]
pub struct GlobalPayPaymentMethodsRequest {
pub reference: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub usage_mode: Option<UsageMode>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card: Option<Card>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs | crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs | use base64::Engine;
use common_enums::enums;
use common_utils::{
ext_traits::ValueExt,
pii::{Email, IpAddress},
types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{CompleteAuthorizeData, PaymentsAuthorizeData, ResponseId},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Deserializer, Serialize};
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
},
utils::{
self, AddressDetailsData, BrowserInformationData, CardData as _,
PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
PaymentsSyncRequestData, RouterData as _,
},
};
pub struct BamboraRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(FloatMajorUnit, T)> for BamboraRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (FloatMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct BamboraCard {
name: Secret<String>,
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvd: Secret<String>,
complete: bool,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "3d_secure")]
three_d_secure: Option<ThreeDSecure>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct ThreeDSecure {
browser: Option<BamboraBrowserInfo>, //Needed only in case of 3Ds 2.0. Need to update request for this.
enabled: bool,
version: Option<i64>,
auth_required: Option<bool>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct BamboraBrowserInfo {
accept_header: String,
java_enabled: bool,
language: String,
color_depth: u8,
screen_height: u32,
screen_width: u32,
time_zone: i32,
user_agent: String,
javascript_enabled: bool,
}
#[derive(Default, Debug, Serialize)]
pub struct BamboraPaymentsRequest {
order_number: String,
amount: FloatMajorUnit,
payment_method: PaymentMethod,
customer_ip: Option<Secret<String, IpAddress>>,
term_url: Option<String>,
card: BamboraCard,
billing: AddressData,
}
#[derive(Default, Debug, Serialize)]
pub struct BamboraVoidRequest {
amount: FloatMajorUnit,
}
fn get_browser_info(
item: &types::PaymentsAuthorizeRouterData,
) -> Result<Option<BamboraBrowserInfo>, error_stack::Report<errors::ConnectorError>> {
if matches!(item.auth_type, enums::AuthenticationType::ThreeDs) {
item.request
.browser_info
.as_ref()
.map(|info| {
Ok(BamboraBrowserInfo {
accept_header: info.get_accept_header()?,
java_enabled: info.get_java_enabled()?,
language: info.get_language()?,
screen_height: info.get_screen_height()?,
screen_width: info.get_screen_width()?,
color_depth: info.get_color_depth()?,
user_agent: info.get_user_agent()?,
time_zone: info.get_time_zone()?,
javascript_enabled: info.get_java_script_enabled()?,
})
})
.transpose()
} else {
Ok(None)
}
}
impl TryFrom<&CompleteAuthorizeData> for BamboraThreedsContinueRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &CompleteAuthorizeData) -> Result<Self, Self::Error> {
let card_response: CardResponse = value
.redirect_response
.as_ref()
.and_then(|f| f.payload.to_owned())
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response.payload",
})?
.parse_value("CardResponse")
.change_context(errors::ConnectorError::ParsingFailed)?;
let bambora_req = Self {
payment_method: "credit_card".to_string(),
card_response,
};
Ok(bambora_req)
}
}
impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for BamboraPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: BamboraRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let (three_ds, customer_ip) = match item.router_data.auth_type {
enums::AuthenticationType::ThreeDs => (
Some(ThreeDSecure {
enabled: true,
browser: get_browser_info(item.router_data)?,
version: Some(2),
auth_required: Some(true),
}),
Some(
item.router_data
.request
.get_browser_info()?
.get_ip_address()?,
),
),
enums::AuthenticationType::NoThreeDs => (None, None),
};
let card = BamboraCard {
name: item.router_data.get_billing_address()?.get_full_name()?,
expiry_year: req_card.get_card_expiry_year_2_digit()?,
number: req_card.card_number,
expiry_month: req_card.card_exp_month,
cvd: req_card.card_cvc,
three_d_secure: three_ds,
complete: item.router_data.request.is_auto_capture()?,
};
let (country, province) = match (
item.router_data.get_optional_billing_country(),
item.router_data.get_optional_billing_state_2_digit(),
) {
(Some(billing_country), Some(billing_state)) => {
(Some(billing_country), Some(billing_state))
}
_ => (None, None),
};
let billing = AddressData {
name: item.router_data.get_optional_billing_full_name(),
address_line1: item.router_data.get_optional_billing_line1(),
address_line2: item.router_data.get_optional_billing_line2(),
city: item.router_data.get_optional_billing_city(),
province,
country,
postal_code: item.router_data.get_optional_billing_zip(),
phone_number: item.router_data.get_optional_billing_phone_number(),
email_address: item.router_data.get_optional_billing_email(),
};
Ok(Self {
order_number: item.router_data.connector_request_reference_id.clone(),
amount: item.amount,
payment_method: PaymentMethod::Card,
card,
customer_ip,
term_url: item.router_data.request.complete_authorize_url.clone(),
billing,
})
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("bambora"),
)
.into())
}
}
}
}
impl TryFrom<BamboraRouterData<&types::PaymentsCancelRouterData>> for BamboraVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: BamboraRouterData<&types::PaymentsCancelRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
})
}
}
pub struct BamboraAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BamboraAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
let auth_key = format!("{}:{}", key1.peek(), api_key.peek());
let auth_header = format!(
"Passcode {}",
common_utils::consts::BASE64_ENGINE.encode(auth_key)
);
Ok(Self {
api_key: Secret::new(auth_header),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
fn str_or_i32<'de, D>(deserializer: D) -> Result<String, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum StrOrI32 {
Str(String),
I32(i32),
}
let value = StrOrI32::deserialize(deserializer)?;
let res = match value {
StrOrI32::Str(v) => v,
StrOrI32::I32(v) => v.to_string(),
};
Ok(res)
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BamboraResponse {
NormalTransaction(Box<BamboraPaymentsResponse>),
ThreeDsResponse(Box<Bambora3DsResponse>),
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct BamboraPaymentsResponse {
#[serde(deserialize_with = "str_or_i32")]
id: String,
authorizing_merchant_id: i32,
#[serde(deserialize_with = "str_or_i32")]
approved: String,
#[serde(deserialize_with = "str_or_i32")]
message_id: String,
message: String,
auth_code: String,
created: String,
amount: FloatMajorUnit,
order_number: String,
#[serde(rename = "type")]
payment_type: String,
comments: Option<String>,
batch_number: Option<String>,
total_refunds: Option<f32>,
total_completions: Option<f32>,
payment_method: String,
card: CardData,
billing: Option<AddressData>,
shipping: Option<AddressData>,
custom: CustomData,
adjusted_by: Option<Vec<AdjustedBy>>,
links: Vec<Links>,
risk_score: Option<f32>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Bambora3DsResponse {
#[serde(rename = "3d_session_data")]
three_d_session_data: Secret<String>,
contents: String,
}
#[derive(Debug, Serialize, Default, Deserialize)]
pub struct BamboraMeta {
pub three_d_session_data: String,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct BamboraThreedsContinueRequest {
pub(crate) payment_method: String,
pub card_response: CardResponse,
}
#[derive(Default, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct CardResponse {
pub(crate) cres: Option<common_utils::pii::SecretSerdeValue>,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct CardData {
name: Option<Secret<String>>,
expiry_month: Option<Secret<String>>,
expiry_year: Option<Secret<String>>,
card_type: String,
last_four: Secret<String>,
card_bin: Option<Secret<String>>,
avs_result: String,
cvd_result: String,
cavv_result: Option<String>,
address_match: Option<i32>,
postal_result: Option<i32>,
avs: Option<AvsObject>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AvsObject {
id: String,
message: String,
processed: bool,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AddressData {
name: Option<Secret<String>>,
address_line1: Option<Secret<String>>,
address_line2: Option<Secret<String>>,
city: Option<String>,
province: Option<Secret<String>>,
country: Option<enums::CountryAlpha2>,
postal_code: Option<Secret<String>>,
phone_number: Option<Secret<String>>,
email_address: Option<Email>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CustomData {
ref1: String,
ref2: String,
ref3: String,
ref4: String,
ref5: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AdjustedBy {
id: i32,
#[serde(rename = "type")]
adjusted_by_type: String,
approval: i32,
message: String,
amount: FloatMajorUnit,
created: String,
url: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Links {
rel: String,
href: String,
method: String,
}
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum PaymentMethod {
#[default]
Card,
Token,
PaymentProfile,
Cash,
Cheque,
Interac,
ApplePay,
AndroidPay,
#[serde(rename = "3d_secure")]
ThreeDSecure,
ProcessorToken,
}
// Capture
#[derive(Default, Debug, Clone, Serialize, PartialEq)]
pub struct BamboraPaymentsCaptureRequest {
amount: FloatMajorUnit,
payment_method: PaymentMethod,
}
impl TryFrom<BamboraRouterData<&types::PaymentsCaptureRouterData>>
for BamboraPaymentsCaptureRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: BamboraRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
payment_method: PaymentMethod::Card,
})
}
}
impl<F> TryFrom<ResponseRouterData<F, BamboraResponse, PaymentsAuthorizeData, PaymentsResponseData>>
for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BamboraResponse, PaymentsAuthorizeData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
BamboraResponse::NormalTransaction(pg_response) => Ok(Self {
status: if pg_response.approved.as_str() == "1" {
match item.data.request.is_auto_capture()? {
true => enums::AttemptStatus::Charged,
false => enums::AttemptStatus::Authorized,
}
} else {
match item.data.request.is_auto_capture()? {
true => enums::AttemptStatus::Failure,
false => enums::AttemptStatus::AuthorizationFailed,
}
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(pg_response.id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(pg_response.order_number.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
BamboraResponse::ThreeDsResponse(response) => {
let value = url::form_urlencoded::parse(response.contents.as_bytes())
.map(|(key, val)| [key, val].concat())
.collect();
let redirection_data = Some(RedirectForm::Html { html_data: value });
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(
serde_json::to_value(BamboraMeta {
three_d_session_data: response.three_d_session_data.expose(),
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)?,
),
network_txn_id: None,
connector_response_reference_id: Some(
item.data.connector_request_reference_id.to_string(),
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
}
}
impl<F>
TryFrom<
ResponseRouterData<F, BamboraPaymentsResponse, CompleteAuthorizeData, PaymentsResponseData>,
> for RouterData<F, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BamboraPaymentsResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: if item.response.approved.as_str() == "1" {
match item.data.request.is_auto_capture()? {
true => enums::AttemptStatus::Charged,
false => enums::AttemptStatus::Authorized,
}
} else {
match item.data.request.is_auto_capture()? {
true => enums::AttemptStatus::Failure,
false => enums::AttemptStatus::AuthorizationFailed,
}
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<BamboraPaymentsResponse>>
for types::PaymentsSyncRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<BamboraPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: match item.data.request.is_auto_capture()? {
true => {
if item.response.approved.as_str() == "1" {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Failure
}
}
false => {
if item.response.approved.as_str() == "1" {
enums::AttemptStatus::Authorized
} else {
enums::AttemptStatus::AuthorizationFailed
}
}
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<BamboraPaymentsResponse>>
for types::PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<BamboraPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: if item.response.approved.as_str() == "1" {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Failure
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<PaymentsCancelResponseRouterData<BamboraPaymentsResponse>>
for types::PaymentsCancelRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<BamboraPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: if item.response.approved.as_str() == "1" {
enums::AttemptStatus::Voided
} else {
enums::AttemptStatus::VoidFailed
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct BamboraRefundRequest {
amount: FloatMajorUnit,
}
impl<F> TryFrom<BamboraRouterData<&types::RefundsRouterData<F>>> for BamboraRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: BamboraRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
#[serde(deserialize_with = "str_or_i32")]
pub id: String,
pub authorizing_merchant_id: i32,
#[serde(deserialize_with = "str_or_i32")]
pub approved: String,
#[serde(deserialize_with = "str_or_i32")]
pub message_id: String,
pub message: String,
pub auth_code: String,
pub created: String,
pub amount: FloatMajorUnit,
pub order_number: String,
#[serde(rename = "type")]
pub payment_type: String,
pub comments: Option<String>,
pub batch_number: Option<String>,
pub total_refunds: Option<f32>,
pub total_completions: Option<f32>,
pub payment_method: String,
pub card: CardData,
pub billing: Option<AddressData>,
pub shipping: Option<AddressData>,
pub custom: CustomData,
pub adjusted_by: Option<Vec<AdjustedBy>>,
pub links: Vec<Links>,
pub risk_score: Option<f32>,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = if item.response.approved.as_str() == "1" {
enums::RefundStatus::Success
} else {
enums::RefundStatus::Failure
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = if item.response.approved.as_str() == "1" {
enums::RefundStatus::Success
} else {
enums::RefundStatus::Failure
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status,
}),
..item.data
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct BamboraErrorResponse {
pub code: i32,
pub category: i32,
pub message: String,
pub reference: String,
pub details: Option<Vec<ErrorDetail>>,
pub validation: Option<CardValidation>,
pub card: Option<CardError>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CardError {
pub avs: AVSDetails,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AVSDetails {
pub message: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ErrorDetail {
field: String,
message: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CardValidation {
id: String,
approved: i32,
message_id: i32,
message: String,
auth_code: String,
trans_date: String,
order_number: String,
type_: String,
amount: f64,
cvd_id: i32,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/gpayments/gpayments_types.rs | crates/hyperswitch_connectors/src/connectors/gpayments/gpayments_types.rs | use api_models::payments::ThreeDsCompletionIndicator;
use cards::CardNumber;
use common_utils::types;
use masking::{Deserialize, Secret, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct GpaymentsConnectorMetaData {
pub authentication_url: String,
pub three_ds_requestor_trans_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct GpaymentsPreAuthVersionCallRequest {
pub acct_number: CardNumber,
pub merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct GpaymentsPreAuthVersionCallResponse {
pub enrolment_status: EnrollmentStatus,
pub supported_message_versions: Option<Vec<types::SemanticVersion>>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum EnrollmentStatus {
#[serde(rename = "00")]
NotEnrolled,
#[serde(rename = "01")]
Enrolled,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct TDS2ApiError {
pub error_code: String,
pub error_component: Option<String>,
pub error_description: String,
pub error_detail: Option<String>,
pub error_message_type: Option<String>,
/// Always returns 'Error' to indicate that this message is an error.
///
/// Example: "Error"
pub message_type: String,
pub message_version: Option<String>,
#[serde(rename = "sdkTransID")]
pub sdk_trans_id: Option<String>,
#[serde(rename = "threeDSServerTransID")]
pub three_ds_server_trans_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct GpaymentsPreAuthenticationRequest {
pub acct_number: CardNumber,
pub card_scheme: Option<CardScheme>,
pub challenge_window_size: Option<ChallengeWindowSize>,
/// URL where the 3DS requestor receives events during authentication.
/// ActiveServer calls this URL through the iframe to notify events occurring during authentication.
///
/// Example: "https://example.requestor.com/3ds-notify"
/// Length: Maximum 2000 characters
pub event_callback_url: String,
/// Merchant identifier assigned by the acquirer.
/// This may be the same value used in authorization requests sent on behalf of the 3DS Requestor.
///
/// Example: "1234567890123456789012345678901234"
/// Length: Maximum 35 characters
pub merchant_id: common_utils::id_type::MerchantId,
/// Optional boolean. If set to true, ActiveServer will not collect the browser information automatically.
/// The requestor must have a backend implementation to collect browser information.
pub skip_auto_browser_info_collect: Option<bool>,
/// Universal unique transaction identifier assigned by the 3DS Requestor to identify a single transaction.
///
/// Example: "6afa6072-9412-446b-9673-2f98b3ee98a2"
/// Length: 36 characters
#[serde(rename = "threeDSRequestorTransID")]
pub three_ds_requestor_trans_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum ChallengeWindowSize {
#[serde(rename = "01")]
Size250x400,
#[serde(rename = "02")]
Size390x400,
#[serde(rename = "03")]
Size500x600,
#[serde(rename = "04")]
Size600x400,
#[serde(rename = "05")]
FullScreen,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum CardScheme {
Visa,
MasterCard,
AmericanExpress,
JCB,
Discover,
UnionPay,
Mir,
Eftpos,
BCard,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct GpaymentsPreAuthenticationResponse {
pub auth_url: String,
pub mon_url: Option<String>,
pub resolved_card_scheme: Option<CardScheme>,
#[serde(rename = "threeDSMethodAvailable")]
pub three_ds_method_available: Option<bool>,
#[serde(rename = "threeDSMethodUrl")]
pub three_ds_method_url: Option<String>,
#[serde(rename = "threeDSServerCallbackUrl")]
pub three_ds_server_callback_url: Option<String>,
#[serde(rename = "threeDSServerTransID")]
pub three_ds_server_trans_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct GpaymentsAuthenticationRequest {
pub acct_number: CardNumber,
pub authentication_ind: String,
pub browser_info_collected: BrowserInfoCollected,
pub card_expiry_date: String,
#[serde(rename = "notificationURL")]
pub notification_url: String,
pub merchant_id: common_utils::id_type::MerchantId,
#[serde(rename = "threeDSCompInd")]
pub three_ds_comp_ind: ThreeDsCompletionIndicator,
pub message_category: String,
pub purchase_amount: String,
pub purchase_date: String,
#[serde(rename = "threeDSServerTransID")]
pub three_ds_server_trans_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct BrowserInfoCollected {
pub browser_accept_header: Option<String>,
pub browser_color_depth: Option<String>,
#[serde(rename = "browserIP")]
pub browser_ip: Option<Secret<String, common_utils::pii::IpAddress>>,
pub browser_javascript_enabled: Option<bool>,
pub browser_java_enabled: Option<bool>,
pub browser_language: Option<String>,
pub browser_screen_height: Option<String>,
pub browser_screen_width: Option<String>,
#[serde(rename = "browserTZ")]
pub browser_tz: Option<String>,
pub browser_user_agent: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum AuthenticationInd {
#[serde(rename = "01")]
PaymentTransaction,
#[serde(rename = "02")]
RecurringTransaction,
#[serde(rename = "03")]
InstalmentTransaction,
#[serde(rename = "04")]
AddCard,
#[serde(rename = "05")]
MaintainCard,
#[serde(rename = "06")]
CardholderVerification,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct GpaymentsAuthenticationSuccessResponse {
#[serde(rename = "dsReferenceNumber")]
pub ds_reference_number: String,
#[serde(rename = "dsTransID")]
pub ds_trans_id: String,
#[serde(rename = "threeDSServerTransID")]
pub three_ds_server_trans_id: String,
#[serde(rename = "messageVersion")]
pub message_version: String,
#[serde(rename = "transStatus")]
pub trans_status: AuthStatus,
#[serde(rename = "acsTransID")]
pub acs_trans_id: String,
#[serde(rename = "challengeUrl")]
pub acs_url: Option<url::Url>,
#[serde(rename = "acsReferenceNumber")]
pub acs_reference_number: String,
pub authentication_value: Option<Secret<String>>,
}
#[derive(Deserialize, Debug, Clone, Serialize, PartialEq)]
pub enum AuthStatus {
/// Authentication/ Account Verification Successful
Y,
/// Not Authenticated /Account Not Verified; Transaction denied
N,
/// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in ARes or RReq
U,
/// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided
A,
/// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted.
R,
/// Challenge required
C,
}
impl From<AuthStatus> for common_enums::TransactionStatus {
fn from(value: AuthStatus) -> Self {
match value {
AuthStatus::Y => Self::Success,
AuthStatus::N => Self::Failure,
AuthStatus::U => Self::VerificationNotPerformed,
AuthStatus::A => Self::NotVerified,
AuthStatus::R => Self::Rejected,
AuthStatus::C => Self::ChallengeRequired,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GpaymentsPostAuthenticationResponse {
pub authentication_value: Option<Secret<String>>,
pub trans_status: AuthStatus,
pub eci: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/gpayments/transformers.rs | crates/hyperswitch_connectors/src/connectors/gpayments/transformers.rs | use api_models::payments::DeviceChannel;
use base64::Engine;
use common_utils::{consts::BASE64_ENGINE, date_time, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, ErrorResponse},
router_flow_types::authentication::{
Authentication, PreAuthentication, PreAuthenticationVersionCall,
},
router_request_types::{
authentication::{
AuthNFlowType, ChallengeParams, ConnectorAuthenticationRequestData, MessageCategory,
PreAuthNRequestData,
},
BrowserInformation,
},
router_response_types::AuthenticationResponseData,
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::{ExposeInterface, Secret};
use serde::Deserialize;
use serde_json::to_string;
use super::gpayments_types::{
self, AuthStatus, BrowserInfoCollected, GpaymentsAuthenticationSuccessResponse,
GpaymentsPreAuthVersionCallResponse,
};
use crate::{
types::{
ConnectorAuthenticationRouterData, PreAuthNRouterData, PreAuthNVersionCallRouterData,
ResponseRouterData,
},
utils::{get_card_details, to_connector_meta_from_secret, CardData as _},
};
pub struct GpaymentsRouterData<T> {
pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for GpaymentsRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
// Auth Struct
pub struct GpaymentsAuthType {
/// base64 encoded certificate
pub certificate: Secret<String>,
/// base64 encoded private_key
pub private_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for GpaymentsAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type.to_owned() {
ConnectorAuthType::CertificateAuth {
certificate,
private_key,
} => Ok(Self {
certificate,
private_key,
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<&GpaymentsRouterData<&PreAuthNVersionCallRouterData>>
for gpayments_types::GpaymentsPreAuthVersionCallRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
value: &GpaymentsRouterData<&PreAuthNVersionCallRouterData>,
) -> Result<Self, Self::Error> {
let router_data = value.router_data;
let metadata = GpaymentsMetaData::try_from(&router_data.connector_meta_data)?;
Ok(Self {
acct_number: router_data.request.card.card_number.clone(),
merchant_id: metadata.merchant_id,
})
}
}
#[derive(Deserialize, PartialEq)]
pub struct GpaymentsMetaData {
pub endpoint_prefix: String,
pub merchant_id: common_utils::id_type::MerchantId,
}
impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for GpaymentsMetaData {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
meta_data: &Option<common_utils::pii::SecretSerdeValue>,
) -> Result<Self, Self::Error> {
let metadata: Self = to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(ConnectorError::InvalidConnectorConfig { config: "metadata" })?;
Ok(metadata)
}
}
impl
TryFrom<
ResponseRouterData<
PreAuthenticationVersionCall,
GpaymentsPreAuthVersionCallResponse,
PreAuthNRequestData,
AuthenticationResponseData,
>,
> for PreAuthNVersionCallRouterData
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
PreAuthenticationVersionCall,
GpaymentsPreAuthVersionCallResponse,
PreAuthNRequestData,
AuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
let version_response = item.response;
let response = Ok(AuthenticationResponseData::PreAuthVersionCallResponse {
maximum_supported_3ds_version: version_response
.supported_message_versions
.and_then(|supported_version| supported_version.iter().max().cloned()) // if no version is returned for the card number, then
.unwrap_or(common_utils::types::SemanticVersion::new(0, 0, 0)),
});
Ok(Self {
response,
..item.data.clone()
})
}
}
impl TryFrom<&GpaymentsRouterData<&PreAuthNRouterData>>
for gpayments_types::GpaymentsPreAuthenticationRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(value: &GpaymentsRouterData<&PreAuthNRouterData>) -> Result<Self, Self::Error> {
let router_data = value.router_data;
let metadata = GpaymentsMetaData::try_from(&router_data.connector_meta_data)?;
Ok(Self {
acct_number: router_data.request.card.card_number.clone(),
card_scheme: None,
challenge_window_size: Some(gpayments_types::ChallengeWindowSize::FullScreen),
event_callback_url: "https://webhook.site/55e3db24-7c4e-4432-9941-d806f68d210b"
.to_string(),
merchant_id: metadata.merchant_id,
skip_auto_browser_info_collect: Some(true),
// should auto generate this id.
three_ds_requestor_trans_id: uuid::Uuid::new_v4().hyphenated().to_string(),
})
}
}
impl TryFrom<&GpaymentsRouterData<&ConnectorAuthenticationRouterData>>
for gpayments_types::GpaymentsAuthenticationRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &GpaymentsRouterData<&ConnectorAuthenticationRouterData>,
) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
let browser_details = match request.browser_details.clone() {
Some(details) => Ok::<Option<BrowserInformation>, Self::Error>(Some(details)),
None => {
if request.device_channel == DeviceChannel::Browser {
Err(ConnectorError::MissingRequiredField {
field_name: "browser_info",
})?
} else {
Ok(None)
}
}
}?;
let card_details = get_card_details(request.payment_method_data.clone(), "gpayments")?;
let metadata = GpaymentsMetaData::try_from(&item.router_data.connector_meta_data)?;
Ok(Self {
acct_number: card_details.card_number.clone(),
authentication_ind: "01".into(),
card_expiry_date: card_details.get_expiry_date_as_yymm()?.expose(),
merchant_id: metadata.merchant_id,
message_category: match item.router_data.request.message_category.clone() {
MessageCategory::Payment => "01".into(),
MessageCategory::NonPayment => "02".into(),
},
notification_url: request
.return_url
.clone()
.ok_or(ConnectorError::RequestEncodingFailed)
.attach_printable("missing return_url")?,
three_ds_comp_ind: request.threeds_method_comp_ind.clone(),
purchase_amount: item.amount.to_string(),
purchase_date: date_time::DateTime::<date_time::YYYYMMDDHHmmss>::from(date_time::now())
.to_string(),
three_ds_server_trans_id: request
.pre_authentication_data
.threeds_server_transaction_id
.clone(),
browser_info_collected: BrowserInfoCollected {
browser_javascript_enabled: browser_details
.as_ref()
.and_then(|details| details.java_script_enabled),
browser_accept_header: browser_details
.as_ref()
.and_then(|details| details.accept_header.clone()),
browser_ip: browser_details
.clone()
.and_then(|details| details.ip_address.map(|ip| Secret::new(ip.to_string()))),
browser_java_enabled: browser_details
.as_ref()
.and_then(|details| details.java_enabled),
browser_language: browser_details
.as_ref()
.and_then(|details| details.language.clone()),
browser_color_depth: browser_details
.as_ref()
.and_then(|details| details.color_depth.map(|a| a.to_string())),
browser_screen_height: browser_details
.as_ref()
.and_then(|details| details.screen_height.map(|a| a.to_string())),
browser_screen_width: browser_details
.as_ref()
.and_then(|details| details.screen_width.map(|a| a.to_string())),
browser_tz: browser_details
.as_ref()
.and_then(|details| details.time_zone.map(|a| a.to_string())),
browser_user_agent: browser_details
.as_ref()
.and_then(|details| details.user_agent.clone().map(|a| a.to_string())),
},
})
}
}
impl
TryFrom<
ResponseRouterData<
Authentication,
GpaymentsAuthenticationSuccessResponse,
ConnectorAuthenticationRequestData,
AuthenticationResponseData,
>,
> for ConnectorAuthenticationRouterData
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
Authentication,
GpaymentsAuthenticationSuccessResponse,
ConnectorAuthenticationRequestData,
AuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
let response_auth = item.response;
let creq = serde_json::json!({
"threeDSServerTransID": response_auth.three_ds_server_trans_id,
"acsTransID": response_auth.acs_trans_id,
"messageVersion": response_auth.message_version,
"messageType": "CReq",
"challengeWindowSize": "01",
});
let creq_str = to_string(&creq)
.change_context(ConnectorError::ResponseDeserializationFailed)
.attach_printable("error while constructing creq_str")?;
let creq_base64 = Engine::encode(&BASE64_ENGINE, creq_str)
.trim_end_matches('=')
.to_owned();
let response: Result<AuthenticationResponseData, ErrorResponse> =
Ok(AuthenticationResponseData::AuthNResponse {
trans_status: response_auth.trans_status.clone().into(),
authn_flow_type: if response_auth.trans_status == AuthStatus::C {
AuthNFlowType::Challenge(Box::new(ChallengeParams {
acs_url: response_auth.acs_url,
challenge_request: Some(creq_base64),
acs_reference_number: Some(response_auth.acs_reference_number.clone()),
acs_trans_id: Some(response_auth.acs_trans_id.clone()),
three_dsserver_trans_id: Some(response_auth.three_ds_server_trans_id),
acs_signed_content: None,
challenge_request_key: None,
}))
} else {
AuthNFlowType::Frictionless
},
authentication_value: response_auth.authentication_value,
ds_trans_id: Some(response_auth.ds_trans_id),
connector_metadata: None,
eci: None,
challenge_code: None,
challenge_cancel: None,
challenge_code_reason: None,
message_extension: None,
});
Ok(Self {
response,
..item.data.clone()
})
}
}
impl
TryFrom<
ResponseRouterData<
PreAuthentication,
gpayments_types::GpaymentsPreAuthenticationResponse,
PreAuthNRequestData,
AuthenticationResponseData,
>,
> for PreAuthNRouterData
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
PreAuthentication,
gpayments_types::GpaymentsPreAuthenticationResponse,
PreAuthNRequestData,
AuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
let threeds_method_response = item.response;
let three_ds_method_data = threeds_method_response
.three_ds_method_url
.as_ref()
.map(|_| {
let three_ds_method_data_json = serde_json::json!({
"threeDSServerTransID": threeds_method_response.three_ds_server_trans_id,
"threeDSMethodNotificationURL": "https://webhook.site/bd06863d-82c2-42ea-b35b-5ffd5ecece71"
});
to_string(&three_ds_method_data_json)
.change_context(ConnectorError::ResponseDeserializationFailed)
.attach_printable("error while constructing three_ds_method_data_str")
.map(|three_ds_method_data_string| {
Engine::encode(&BASE64_ENGINE, three_ds_method_data_string)
})
})
.transpose()?;
let connector_metadata = Some(serde_json::json!(
gpayments_types::GpaymentsConnectorMetaData {
authentication_url: threeds_method_response.auth_url,
three_ds_requestor_trans_id: None,
}
));
let response: Result<AuthenticationResponseData, ErrorResponse> = Ok(
AuthenticationResponseData::PreAuthThreeDsMethodCallResponse {
threeds_server_transaction_id: threeds_method_response
.three_ds_server_trans_id
.clone(),
three_ds_method_data,
three_ds_method_url: threeds_method_response.three_ds_method_url,
connector_metadata,
},
);
Ok(Self {
response,
..item.data.clone()
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs | crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs | use std::str::FromStr;
use cards::{CardNumber, NetworkToken};
use common_enums::enums as storage_enums;
use common_utils::{errors::CustomResult, pii, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{Card, NetworkTokenData, PaymentMethodData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{RefundsData, ResponseId},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use crate::{
types::ResponseRouterData,
utils::{self, CardData, NetworkTokenData as _, RouterData as OtherRouterData},
};
pub struct PeachpaymentsRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for PeachpaymentsRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for PeachPaymentsConnectorMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
const CHARGE_METHOD: &str = "ecommerce_card_payment_only";
const COF_DATA_TYPE: &str = "adhoc";
const COF_DATA_SOURCE: &str = "cit";
const COF_DATA_MODE: &str = "initial";
// Card Gateway API Transaction Request
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsPaymentsCardRequest {
pub charge_method: String,
pub reference_id: String,
pub ecommerce_card_payment_only_transaction_data: EcommercePaymentOnlyTransactionData,
#[serde(skip_serializing_if = "Option::is_none")]
pub pos_data: Option<serde_json::Value>,
pub send_date_time: String,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsPaymentsNTRequest {
pub payment_method: String,
pub reference_id: String,
pub ecommerce_card_payment_only_transaction_data: EcommercePaymentOnlyTransactionData,
pub send_date_time: String,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(untagged)]
pub enum PeachpaymentsPaymentsRequest {
Card(PeachpaymentsPaymentsCardRequest),
NetworkToken(PeachpaymentsPaymentsNTRequest),
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CardOnFileData {
#[serde(rename = "type")]
pub _type: String,
pub source: String,
pub mode: String,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EcommerceCardPaymentOnlyTransactionData {
pub merchant_information: MerchantInformation,
pub routing_reference: RoutingReference,
pub card: CardDetails,
pub amount: AmountDetails,
pub rrn: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub pre_auth_inc_ext_capture_flow: Option<PreAuthIncExtCaptureFlow>,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EcommerceNetworkTokenPaymentOnlyTransactionData {
pub merchant_information: MerchantInformation,
pub routing_reference: RoutingReference,
pub network_token_data: NetworkTokenDetails,
pub amount: AmountDetails,
pub cof_data: CardOnFileData,
pub rrn: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub pre_auth_inc_ext_capture_flow: Option<PreAuthIncExtCaptureFlow>,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PreAuthIncExtCaptureFlow {
pub dcc_mode: DccMode,
pub txn_ref_nr: String,
}
#[derive(Debug, Default, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum DccMode {
#[default]
NoDcc,
OptInDcc,
OptOutDcc,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(untagged)]
pub enum EcommercePaymentOnlyTransactionData {
Card(EcommerceCardPaymentOnlyTransactionData),
NetworkToken(EcommerceNetworkTokenPaymentOnlyTransactionData),
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MerchantInformation {
pub client_merchant_reference_id: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum MerchantType {
Standard,
Sub,
Iso,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RoutingReference {
pub merchant_payment_method_route_id: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CardDetails {
pub pan: CardNumber,
#[serde(skip_serializing_if = "Option::is_none")]
pub cardholder_name: Option<Secret<String>>,
pub expiry_year: Secret<String>,
pub expiry_month: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cvv: Option<Secret<String>>,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct NetworkTokenDetails {
pub token: NetworkToken,
pub expiry_year: Secret<String>,
pub expiry_month: Secret<String>,
pub cryptogram: Option<Secret<String>>,
pub eci: Option<String>,
pub scheme: Option<CardNetworkLowercase>,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CardNetworkLowercase {
Visa,
Mastercard,
Amex,
Discover,
Jcb,
Diners,
CartesBancaires,
UnionPay,
Interac,
RuPay,
Maestro,
Star,
Pulse,
Accel,
Nyce,
}
impl From<common_enums::CardNetwork> for CardNetworkLowercase {
fn from(value: common_enums::CardNetwork) -> Self {
match value {
common_enums::CardNetwork::Visa => Self::Visa,
common_enums::CardNetwork::Mastercard => Self::Mastercard,
common_enums::CardNetwork::AmericanExpress => Self::Amex,
common_enums::CardNetwork::Discover => Self::Discover,
common_enums::CardNetwork::JCB => Self::Jcb,
common_enums::CardNetwork::DinersClub => Self::Diners,
common_enums::CardNetwork::CartesBancaires => Self::CartesBancaires,
common_enums::CardNetwork::UnionPay => Self::UnionPay,
common_enums::CardNetwork::Interac => Self::Interac,
common_enums::CardNetwork::RuPay => Self::RuPay,
common_enums::CardNetwork::Maestro => Self::Maestro,
common_enums::CardNetwork::Star => Self::Star,
common_enums::CardNetwork::Pulse => Self::Pulse,
common_enums::CardNetwork::Accel => Self::Accel,
common_enums::CardNetwork::Nyce => Self::Nyce,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmountDetails {
pub amount: MinorUnit,
pub currency_code: common_enums::Currency,
#[serde(skip_serializing_if = "Option::is_none")]
pub display_amount: Option<String>,
}
// Confirm Transaction Request (for capture)
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsCaptureRequest {
pub amount: AmountDetails,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsRefundRequest {
pub reference_id: String,
pub ecommerce_card_payment_only_transaction_data: PeachpaymentsRefundTransactionData,
#[serde(skip_serializing_if = "Option::is_none")]
pub pos_data: Option<PosData>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PosData {
pub referral: String,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsRefundTransactionData {
pub amount: AmountDetails,
}
impl TryFrom<&RefundsRouterData<Execute>> for PeachpaymentsRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundsRouterData<Execute>) -> Result<Self, Self::Error> {
let amount = AmountDetails {
amount: item.request.minor_refund_amount,
currency_code: item.request.currency,
display_amount: None,
};
let ecommerce_card_payment_only_transaction_data =
PeachpaymentsRefundTransactionData { amount };
Ok(Self {
reference_id: item.request.refund_id.clone(),
ecommerce_card_payment_only_transaction_data,
pos_data: None,
})
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct EcommerceCardPaymentOnlyConfirmationData {
pub amount: AmountDetails,
}
// Void Transaction Request
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsVoidRequest {
pub amount: AmountDetails,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum PaymentMethod {
EcommerceCardPaymentOnly,
}
impl TryFrom<&PeachpaymentsRouterData<&PaymentsCaptureRouterData>> for PeachpaymentsCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PeachpaymentsRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: AmountDetails {
amount: item.amount,
currency_code: item.router_data.request.currency,
display_amount: None,
},
})
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum FailureReason {
UnableToSend,
#[default]
Timeout,
SecurityError,
IssuerUnavailable,
TooLateResponse,
Malfunction,
UnableToComplete,
OnlineDeclined,
SuspectedFraud,
CardDeclined,
Partial,
OfflineDeclined,
CustomerCancel,
}
impl FromStr for FailureReason {
type Err = error_stack::Report<errors::ConnectorError>;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value.to_lowercase().as_str() {
"unable_to_send" => Ok(Self::UnableToSend),
"timeout" => Ok(Self::Timeout),
"security_error" => Ok(Self::SecurityError),
"issuer_unavailable" => Ok(Self::IssuerUnavailable),
"too_late_response" => Ok(Self::TooLateResponse),
"malfunction" => Ok(Self::Malfunction),
"unable_to_complete" => Ok(Self::UnableToComplete),
"online_declined" => Ok(Self::OnlineDeclined),
"suspected_fraud" => Ok(Self::SuspectedFraud),
"card_declined" => Ok(Self::CardDeclined),
"partial" => Ok(Self::Partial),
"offline_declined" => Ok(Self::OfflineDeclined),
"customer_cancel" => Ok(Self::CustomerCancel),
_ => Ok(Self::Timeout),
}
}
}
impl TryFrom<&PeachpaymentsRouterData<&PaymentsCancelRouterData>> for PeachpaymentsVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PeachpaymentsRouterData<&PaymentsCancelRouterData>,
) -> Result<Self, Self::Error> {
let amount = AmountDetails {
amount: item.amount,
currency_code: item.router_data.request.currency.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "Currency",
},
)?,
display_amount: None,
};
Ok(Self { amount })
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PeachPaymentsConnectorMetadataObject {
pub client_merchant_reference_id: Secret<String>,
pub merchant_payment_method_route_id: Secret<String>,
}
impl TryFrom<&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>>
for PeachpaymentsPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => Self::try_from((item, req_card)),
PaymentMethodData::NetworkToken(token_data) => Self::try_from((item, token_data)),
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
impl
TryFrom<(
&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>,
NetworkTokenData,
)> for PeachpaymentsPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, token_data): (
&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>,
NetworkTokenData,
),
) -> Result<Self, Self::Error> {
let amount_in_cents = item.amount;
let connector_merchant_config =
PeachPaymentsConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?;
let merchant_information = MerchantInformation {
client_merchant_reference_id: connector_merchant_config.client_merchant_reference_id,
};
let routing_reference = RoutingReference {
merchant_payment_method_route_id: connector_merchant_config
.merchant_payment_method_route_id,
};
let network_token_data = NetworkTokenDetails {
token: token_data.get_network_token(),
expiry_year: token_data.get_token_expiry_year_2_digit()?,
expiry_month: token_data.get_network_token_expiry_month(),
cryptogram: token_data.get_cryptogram(),
eci: token_data.eci.clone(),
scheme: Some(CardNetworkLowercase::from(
token_data.card_network.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "card_network",
},
)?,
)),
};
let amount = AmountDetails {
amount: amount_in_cents,
currency_code: item.router_data.request.currency,
display_amount: None,
};
let pre_auth_inc_ext_capture_flow = if matches!(
item.router_data.request.capture_method,
Some(common_enums::CaptureMethod::Manual)
) {
Some(PreAuthIncExtCaptureFlow {
dcc_mode: DccMode::NoDcc,
txn_ref_nr: item.router_data.connector_request_reference_id.clone(),
})
} else {
None
};
let ecommerce_data = EcommercePaymentOnlyTransactionData::NetworkToken(
EcommerceNetworkTokenPaymentOnlyTransactionData {
merchant_information,
routing_reference,
network_token_data,
amount,
cof_data: CardOnFileData {
_type: COF_DATA_TYPE.to_string(),
source: COF_DATA_SOURCE.to_string(),
mode: COF_DATA_MODE.to_string(),
},
rrn: item.router_data.request.merchant_order_reference_id.clone(),
pre_auth_inc_ext_capture_flow,
},
);
// Generate current timestamp for sendDateTime (ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ)
let send_date_time = OffsetDateTime::now_utc()
.format(&time::format_description::well_known::Iso8601::DEFAULT)
.map_err(|_| errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self::NetworkToken(PeachpaymentsPaymentsNTRequest {
payment_method: "ecommerce_card_payment_only".to_string(),
reference_id: item.router_data.connector_request_reference_id.clone(),
ecommerce_card_payment_only_transaction_data: ecommerce_data,
send_date_time: send_date_time.clone(),
}))
}
}
impl TryFrom<(&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>, Card)>
for PeachpaymentsPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, req_card): (&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>, Card),
) -> Result<Self, Self::Error> {
if item.router_data.is_three_ds() {
return Err(errors::ConnectorError::NotSupported {
message: "3DS flow".to_string(),
connector: "Peachpayments",
}
.into());
}
let amount_in_cents = item.amount;
let connector_merchant_config =
PeachPaymentsConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?;
let merchant_information = MerchantInformation {
client_merchant_reference_id: connector_merchant_config.client_merchant_reference_id,
};
let routing_reference = RoutingReference {
merchant_payment_method_route_id: connector_merchant_config
.merchant_payment_method_route_id,
};
let card = CardDetails {
pan: req_card.card_number.clone(),
cardholder_name: req_card.card_holder_name.clone(),
expiry_year: req_card.get_card_expiry_year_2_digit()?,
expiry_month: req_card.card_exp_month.clone(),
cvv: Some(req_card.card_cvc.clone()),
};
let amount = AmountDetails {
amount: amount_in_cents,
currency_code: item.router_data.request.currency,
display_amount: None,
};
let pre_auth_inc_ext_capture_flow = if matches!(
item.router_data.request.capture_method,
Some(common_enums::CaptureMethod::Manual)
) {
Some(PreAuthIncExtCaptureFlow {
dcc_mode: DccMode::NoDcc,
txn_ref_nr: item.router_data.connector_request_reference_id.clone(),
})
} else {
None
};
let ecommerce_data =
EcommercePaymentOnlyTransactionData::Card(EcommerceCardPaymentOnlyTransactionData {
merchant_information,
routing_reference,
card,
amount,
rrn: item.router_data.request.merchant_order_reference_id.clone(),
pre_auth_inc_ext_capture_flow,
});
// Generate current timestamp for sendDateTime (ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ)
let send_date_time = OffsetDateTime::now_utc()
.format(&time::format_description::well_known::Iso8601::DEFAULT)
.map_err(|_| errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self::Card(PeachpaymentsPaymentsCardRequest {
charge_method: CHARGE_METHOD.to_string(),
reference_id: item.router_data.connector_request_reference_id.clone(),
ecommerce_card_payment_only_transaction_data: ecommerce_data,
pos_data: None,
send_date_time,
}))
}
}
// Auth Struct for Card Gateway API
pub struct PeachpaymentsAuthType {
pub(crate) api_key: Secret<String>,
pub(crate) tenant_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PeachpaymentsAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
api_key: api_key.clone(),
tenant_id: key1.clone(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
// Card Gateway API Response
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum PeachpaymentsPaymentStatus {
Successful,
Pending,
Authorized,
Approved,
ApprovedConfirmed,
Declined,
Failed,
Reversed,
ThreedsRequired,
Voided,
}
impl From<PeachpaymentsPaymentStatus> for common_enums::AttemptStatus {
fn from(item: PeachpaymentsPaymentStatus) -> Self {
match item {
// PENDING means authorized but not yet captured - requires confirmation
PeachpaymentsPaymentStatus::Pending
| PeachpaymentsPaymentStatus::Authorized
| PeachpaymentsPaymentStatus::Approved => Self::Authorized,
PeachpaymentsPaymentStatus::Declined | PeachpaymentsPaymentStatus::Failed => {
Self::Failure
}
PeachpaymentsPaymentStatus::Voided | PeachpaymentsPaymentStatus::Reversed => {
Self::Voided
}
PeachpaymentsPaymentStatus::ThreedsRequired => Self::AuthenticationPending,
PeachpaymentsPaymentStatus::ApprovedConfirmed
| PeachpaymentsPaymentStatus::Successful => Self::Charged,
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum PeachpaymentsPaymentsResponse {
Response(Box<PeachpaymentsPaymentsData>),
WebhookResponse(Box<PeachpaymentsIncomingWebhook>),
}
impl From<PeachpaymentsRefundStatus> for common_enums::RefundStatus {
fn from(item: PeachpaymentsRefundStatus) -> Self {
match item {
PeachpaymentsRefundStatus::ApprovedConfirmed => Self::Success,
PeachpaymentsRefundStatus::Failed | PeachpaymentsRefundStatus::Declined => {
Self::Failure
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsPaymentsData {
pub transaction_id: String,
pub response_code: Option<ResponseCode>,
pub transaction_result: PeachpaymentsPaymentStatus,
pub ecommerce_card_payment_only_transaction_data: Option<EcommerceCardPaymentOnlyResponseData>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsRsyncResponse {
pub transaction_id: String,
pub transaction_result: PeachpaymentsRefundStatus,
pub response_code: Option<ResponseCode>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsRefundResponse {
pub transaction_id: String,
pub original_transaction_id: Option<String>,
pub reference_id: String,
pub transaction_result: PeachpaymentsRefundStatus,
pub response_code: Option<ResponseCode>,
pub refund_balance_data: Option<RefundBalanceData>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum PeachpaymentsRefundStatus {
ApprovedConfirmed,
Declined,
Failed,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundBalanceData {
pub amount: AmountDetails,
pub balance: AmountDetails,
pub refund_history: Vec<RefundHistory>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundHistory {
pub transaction_id: String,
pub reference_id: String,
pub amount: AmountDetails,
}
impl<F>
TryFrom<ResponseRouterData<F, PeachpaymentsRefundResponse, RefundsData, RefundsResponseData>>
for RouterData<F, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PeachpaymentsRefundResponse, RefundsData, RefundsResponseData>,
) -> Result<Self, Self::Error> {
let refund_status = common_enums::RefundStatus::from(item.response.transaction_result);
let response = if refund_status == storage_enums::RefundStatus::Failure {
Err(ErrorResponse {
code: get_error_code(item.response.response_code.as_ref()),
message: get_error_message(item.response.response_code.as_ref()),
reason: None,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.transaction_id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
impl
TryFrom<ResponseRouterData<RSync, PeachpaymentsRsyncResponse, RefundsData, RefundsResponseData>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
RSync,
PeachpaymentsRsyncResponse,
RefundsData,
RefundsResponseData,
>,
) -> Result<Self, Self::Error> {
let refund_status = item.response.transaction_result.into();
let response = if refund_status == storage_enums::RefundStatus::Failure {
Err(ErrorResponse {
code: get_error_code(item.response.response_code.as_ref()),
message: get_error_message(item.response.response_code.as_ref()),
reason: None,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.transaction_id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
// Confirm Transaction Response
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsCaptureResponse {
pub transaction_id: String,
pub response_code: Option<ResponseCode>,
pub transaction_result: PeachpaymentsPaymentStatus,
pub authorization_code: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum ResponseCode {
Text(String),
Structured {
value: String,
description: String,
terminal_outcome_string: Option<String>,
receipt_string: Option<String>,
},
}
impl ResponseCode {
pub fn value(&self) -> Option<&String> {
match self {
Self::Structured { value, .. } => Some(value),
_ => None,
}
}
pub fn description(&self) -> Option<&String> {
match self {
Self::Structured { description, .. } => Some(description),
_ => None,
}
}
pub fn as_text(&self) -> Option<&String> {
match self {
Self::Text(s) => Some(s),
_ => None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EcommerceCardPaymentOnlyResponseData {
pub amount: Option<AmountDetails>,
pub stan: Option<Secret<String>>,
pub rrn: Option<Secret<String>>,
pub approval_code: Option<String>,
pub merchant_advice_code: Option<String>,
pub description: Option<String>,
pub trace_id: Option<String>,
}
fn is_payment_success(value: Option<&String>) -> bool {
if let Some(val) = value {
val == "00" || val == "08" || val == "X94"
} else {
false
}
}
fn get_error_code(response_code: Option<&ResponseCode>) -> String {
response_code
.and_then(|code| code.value())
.map(|val| val.to_string())
.unwrap_or(
response_code
.and_then(|code| code.as_text())
.map(|text| text.to_string())
.unwrap_or(NO_ERROR_CODE.to_string()),
)
}
fn get_error_message(response_code: Option<&ResponseCode>) -> String {
response_code
.and_then(|code| code.description())
.map(|desc| desc.to_string())
.unwrap_or(
response_code
.and_then(|code| code.as_text())
.map(|text| text.to_string())
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
)
}
pub fn get_peachpayments_response(
response: PeachpaymentsPaymentsData,
status_code: u16,
) -> CustomResult<
(
storage_enums::AttemptStatus,
Result<PaymentsResponseData, ErrorResponse>,
),
errors::ConnectorError,
> {
let status = common_enums::AttemptStatus::from(response.transaction_result);
let payments_response = if !is_payment_success(
response
.response_code
.as_ref()
.and_then(|code| code.value()),
) {
Err(ErrorResponse {
code: get_error_code(response.response_code.as_ref()),
message: get_error_message(response.response_code.as_ref()),
reason: response
.ecommerce_card_payment_only_transaction_data
.and_then(|data| data.description),
status_code,
attempt_status: Some(status),
connector_transaction_id: Some(response.transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.transaction_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(response.transaction_id),
incremental_authorization_allowed: None,
charges: None,
})
};
Ok((status, payments_response))
}
pub fn get_webhook_response(
response: PeachpaymentsIncomingWebhook,
status_code: u16,
) -> CustomResult<
(
storage_enums::AttemptStatus,
Result<PaymentsResponseData, ErrorResponse>,
),
errors::ConnectorError,
> {
let transaction = response
.transaction
.ok_or(errors::ConnectorError::WebhookResourceObjectNotFound)?;
let status = common_enums::AttemptStatus::from(transaction.transaction_result);
let webhook_response = if !is_payment_success(
transaction
.response_code
.as_ref()
.and_then(|code| code.value()),
) {
Err(ErrorResponse {
code: get_error_code(transaction.response_code.as_ref()),
message: get_error_message(transaction.response_code.as_ref()),
reason: transaction
.ecommerce_card_payment_only_transaction_data
.and_then(|data| data.description),
status_code,
attempt_status: Some(status),
connector_transaction_id: Some(transaction.transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
transaction
.original_transaction_id
.unwrap_or(transaction.transaction_id.clone()),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(transaction.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
})
};
Ok((status, webhook_response))
}
impl<F, T> TryFrom<ResponseRouterData<F, PeachpaymentsPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PeachpaymentsPaymentsResponse, T, PaymentsResponseData>,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/authipay/transformers.rs | crates/hyperswitch_connectors/src/connectors/authipay/transformers.rs | use common_enums::enums;
use common_utils::types::FloatMajorUnit;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, CardData},
};
// Type definition for router data with amount
pub struct AuthipayRouterData<T> {
pub amount: FloatMajorUnit, // Amount in major units (e.g., dollars instead of cents)
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for AuthipayRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
// Basic request/response structs used across multiple operations
#[derive(Default, Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
total: FloatMajorUnit,
currency: String,
#[serde(skip_serializing_if = "Option::is_none")]
components: Option<AmountComponents>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmountComponents {
subtotal: FloatMajorUnit,
}
#[derive(Default, Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ExpiryDate {
month: Secret<String>,
year: Secret<String>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Card {
number: cards::CardNumber,
security_code: Secret<String>,
expiry_date: ExpiryDate,
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethod {
payment_card: Card,
}
#[derive(Default, Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SplitShipment {
total_count: i32,
final_shipment: bool,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayPaymentsRequest {
request_type: &'static str,
transaction_amount: Amount,
payment_method: PaymentMethod,
// split_shipment: Option<SplitShipment>,
// incremental_flag: Option<bool>,
}
impl TryFrom<&AuthipayRouterData<&PaymentsAuthorizeRouterData>> for AuthipayPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthipayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
// Check if 3DS is being requested - Authipay doesn't support 3DS
if matches!(
item.router_data.auth_type,
enums::AuthenticationType::ThreeDs
) {
return Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authipay"),
)
.into());
}
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let expiry_date = ExpiryDate {
month: req_card.card_exp_month.clone(),
year: req_card.get_card_expiry_year_2_digit()?,
};
let card = Card {
number: req_card.card_number.clone(),
security_code: req_card.card_cvc.clone(),
expiry_date,
};
let payment_method = PaymentMethod { payment_card: card };
let transaction_amount = Amount {
total: item.amount,
currency: item.router_data.request.currency.to_string(),
components: None,
};
// Determine request type based on capture method
let request_type = match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual) => "PaymentCardPreAuthTransaction",
Some(enums::CaptureMethod::Automatic) => "PaymentCardSaleTransaction",
Some(enums::CaptureMethod::SequentialAutomatic) => "PaymentCardSaleTransaction",
Some(enums::CaptureMethod::ManualMultiple)
| Some(enums::CaptureMethod::Scheduled) => {
return Err(errors::ConnectorError::NotSupported {
message: "Capture method not supported by Authipay".to_string(),
connector: "Authipay",
}
.into());
}
None => "PaymentCardSaleTransaction", // Default when not specified
};
let request = Self {
request_type,
transaction_amount,
payment_method,
};
Ok(request)
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authipay"),
)
.into()),
}
}
}
//TODO: Fill the struct with respective fields
// Auth Struct
pub struct AuthipayAuthType {
pub(super) api_key: Secret<String>,
pub(super) api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AuthipayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
api_secret: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// Transaction Status enum (like Fiserv's FiservPaymentStatus)
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum AuthipayTransactionStatus {
Authorized,
Captured,
Voided,
Declined,
Failed,
#[default]
Processing,
}
impl From<AuthipayTransactionStatus> for enums::AttemptStatus {
fn from(item: AuthipayTransactionStatus) -> Self {
match item {
AuthipayTransactionStatus::Captured => Self::Charged,
AuthipayTransactionStatus::Declined | AuthipayTransactionStatus::Failed => {
Self::Failure
}
AuthipayTransactionStatus::Processing => Self::Pending,
AuthipayTransactionStatus::Authorized => Self::Authorized,
AuthipayTransactionStatus::Voided => Self::Voided,
}
}
}
// Transaction Processing Details (like Fiserv's TransactionProcessingDetails)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayTransactionProcessingDetails {
pub order_id: String,
pub transaction_id: String,
}
// Gateway Response (like Fiserv's GatewayResponse)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayGatewayResponse {
pub transaction_state: AuthipayTransactionStatus,
pub transaction_processing_details: AuthipayTransactionProcessingDetails,
}
// Payment Receipt (like Fiserv's PaymentReceipt)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayPaymentReceipt {
pub approved_amount: Amount,
pub processor_response_details: Option<Processor>,
}
// Main Response (like Fiserv's FiservPaymentsResponse) - but flat for JSON deserialization
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayPaymentsResponse {
#[serde(rename = "type")]
response_type: Option<String>,
client_request_id: String,
api_trace_id: String,
ipg_transaction_id: String,
order_id: String,
transaction_type: String,
payment_token: Option<PaymentToken>,
transaction_origin: Option<String>,
payment_method_details: Option<PaymentMethodDetails>,
country: Option<String>,
terminal_id: Option<String>,
merchant_id: Option<String>,
transaction_time: i64,
approved_amount: Amount,
transaction_amount: Amount,
// For payment transactions (SALE)
transaction_status: Option<String>,
// For refund transactions (RETURN)
transaction_result: Option<String>,
transaction_state: Option<String>,
approval_code: String,
scheme_transaction_id: Option<String>,
processor: Processor,
}
impl AuthipayPaymentsResponse {
/// Get gateway response (like Fiserv's gateway_response)
pub fn gateway_response(&self) -> AuthipayGatewayResponse {
AuthipayGatewayResponse {
transaction_state: self.get_transaction_status(),
transaction_processing_details: AuthipayTransactionProcessingDetails {
order_id: self.order_id.clone(),
transaction_id: self.ipg_transaction_id.clone(),
},
}
}
/// Get payment receipt (like Fiserv's payment_receipt)
pub fn payment_receipt(&self) -> AuthipayPaymentReceipt {
AuthipayPaymentReceipt {
approved_amount: self.approved_amount.clone(),
processor_response_details: Some(self.processor.clone()),
}
}
/// Determine the transaction status based on transaction type and various status fields (like Fiserv)
fn get_transaction_status(&self) -> AuthipayTransactionStatus {
match self.transaction_type.as_str() {
"RETURN" => {
// Refund transaction - use transaction_result
match self.transaction_result.as_deref() {
Some("APPROVED") => AuthipayTransactionStatus::Captured,
Some("DECLINED") | Some("FAILED") => AuthipayTransactionStatus::Failed,
_ => AuthipayTransactionStatus::Processing,
}
}
"VOID" => {
// Void transaction - use transaction_result, fallback to transaction_state
match self.transaction_result.as_deref() {
Some("APPROVED") => AuthipayTransactionStatus::Voided,
Some("DECLINED") | Some("FAILED") => AuthipayTransactionStatus::Failed,
Some("PENDING") | Some("PROCESSING") => AuthipayTransactionStatus::Processing,
_ => {
// Fallback to transaction_state for void operations
match self.transaction_state.as_deref() {
Some("VOIDED") => AuthipayTransactionStatus::Voided,
Some("FAILED") | Some("DECLINED") => AuthipayTransactionStatus::Failed,
_ => AuthipayTransactionStatus::Voided, // Default assumption for void requests
}
}
}
}
_ => {
// Payment transaction - prioritize transaction_state over transaction_status
match self.transaction_state.as_deref() {
Some("AUTHORIZED") => AuthipayTransactionStatus::Authorized,
Some("CAPTURED") => AuthipayTransactionStatus::Captured,
Some("VOIDED") => AuthipayTransactionStatus::Voided,
Some("DECLINED") | Some("FAILED") => AuthipayTransactionStatus::Failed,
_ => {
// Fallback to transaction_status with transaction_type context
match (
self.transaction_type.as_str(),
self.transaction_status.as_deref(),
) {
// For PREAUTH transactions, "APPROVED" means authorized and awaiting capture
("PREAUTH", Some("APPROVED")) => AuthipayTransactionStatus::Authorized,
// For POSTAUTH transactions, "APPROVED" means successfully captured
("POSTAUTH", Some("APPROVED")) => AuthipayTransactionStatus::Captured,
// For SALE transactions, "APPROVED" means completed payment
("SALE", Some("APPROVED")) => AuthipayTransactionStatus::Captured,
// For VOID transactions, "APPROVED" means successfully voided
("VOID", Some("APPROVED")) => AuthipayTransactionStatus::Voided,
// Generic status mappings for other cases
(_, Some("APPROVED")) => AuthipayTransactionStatus::Captured,
(_, Some("AUTHORIZED")) => AuthipayTransactionStatus::Authorized,
(_, Some("DECLINED") | Some("FAILED")) => {
AuthipayTransactionStatus::Failed
}
_ => AuthipayTransactionStatus::Processing,
}
}
}
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentToken {
reusable: Option<bool>,
decline_duplicates: Option<bool>,
brand: Option<String>,
#[serde(rename = "type")]
token_type: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethodDetails {
payment_card: Option<PaymentCardDetails>,
payment_method_type: Option<String>,
payment_method_brand: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentCardDetails {
expiry_date: ExpiryDate,
bin: String,
last4: String,
brand: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Processor {
reference_number: Option<String>,
authorization_code: Option<String>,
response_code: String,
response_message: String,
avs_response: Option<AvsResponse>,
security_code_response: Option<String>,
tax_refund_data: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AvsResponse {
street_match: Option<String>,
postal_code_match: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, AuthipayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AuthipayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
// Get gateway response (like Fiserv pattern)
let gateway_resp = item.response.gateway_response();
// Store order_id in connector_metadata for void operations (like Fiserv)
let mut metadata = std::collections::HashMap::new();
metadata.insert(
"order_id".to_string(),
serde_json::Value::String(gateway_resp.transaction_processing_details.order_id.clone()),
);
let connector_metadata = Some(serde_json::Value::Object(serde_json::Map::from_iter(
metadata,
)));
Ok(Self {
status: enums::AttemptStatus::from(gateway_resp.transaction_state.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
gateway_resp
.transaction_processing_details
.transaction_id
.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(
gateway_resp.transaction_processing_details.order_id.clone(),
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// Type definition for CaptureRequest
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayCaptureRequest {
request_type: &'static str,
transaction_amount: Amount,
}
impl TryFrom<&AuthipayRouterData<&PaymentsCaptureRouterData>> for AuthipayCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthipayRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
request_type: "PostAuthTransaction",
transaction_amount: Amount {
total: item.amount,
currency: item.router_data.request.currency.to_string(),
components: None,
},
})
}
}
// Type definition for VoidRequest
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayVoidRequest {
request_type: &'static str,
}
impl TryFrom<&AuthipayRouterData<&PaymentsCancelRouterData>> for AuthipayVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
_item: &AuthipayRouterData<&PaymentsCancelRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
request_type: "VoidTransaction",
})
}
}
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayRefundRequest {
request_type: &'static str,
transaction_amount: Amount,
}
impl<F> TryFrom<&AuthipayRouterData<&RefundsRouterData<F>>> for AuthipayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AuthipayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
request_type: "ReturnTransaction",
transaction_amount: Amount {
total: item.amount.to_owned(),
currency: item.router_data.request.currency.to_string(),
components: None,
},
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
// Reusing the payments response structure for refunds
// because Authipay uses the same endpoint and response format
pub type RefundResponse = AuthipayPaymentsResponse;
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = if item.response.transaction_type == "RETURN" {
match item.response.transaction_result.as_deref() {
Some("APPROVED") => RefundStatus::Succeeded,
Some("DECLINED") | Some("FAILED") => RefundStatus::Failed,
_ => RefundStatus::Processing,
}
} else {
RefundStatus::Processing
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.ipg_transaction_id.to_string(),
refund_status: enums::RefundStatus::from(refund_status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = if item.response.transaction_type == "RETURN" {
match item.response.transaction_result.as_deref() {
Some("APPROVED") => RefundStatus::Succeeded,
Some("DECLINED") | Some("FAILED") => RefundStatus::Failed,
_ => RefundStatus::Processing,
}
} else {
RefundStatus::Processing
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.ipg_transaction_id.to_string(),
refund_status: enums::RefundStatus::from(refund_status),
}),
..item.data
})
}
}
// Error Response structs
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorDetailItem {
pub field: String,
pub message: String,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorDetails {
pub code: Option<String>,
pub message: String,
pub details: Option<Vec<ErrorDetailItem>>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthipayErrorResponse {
pub client_request_id: Option<String>,
pub api_trace_id: Option<String>,
pub response_type: Option<String>,
#[serde(rename = "type")]
pub response_object_type: Option<String>,
pub error: ErrorDetails,
pub decline_reason_code: Option<String>,
}
impl From<&AuthipayErrorResponse> for ErrorResponse {
fn from(item: &AuthipayErrorResponse) -> Self {
Self {
status_code: 500, // Default to Internal Server Error, will be overridden by actual HTTP status
code: item.error.code.clone().unwrap_or_default(),
message: item.error.message.clone(),
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs | crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs | use std::collections::HashMap;
use common_enums::{enums, CaptureMethod};
use common_utils::{errors::CustomResult, pii, types::StringMajorUnit};
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::{consts, errors};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{is_refund_failure, RouterData as _},
};
pub struct AmazonpayRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for AmazonpayRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmazonpayFinalizeRequest {
charge_amount: ChargeAmount,
shipping_address: AddressDetails,
payment_intent: PaymentIntent,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ChargeAmount {
amount: StringMajorUnit,
currency_code: common_enums::Currency,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AddressDetails {
name: Secret<String>,
address_line_1: Secret<String>,
address_line_2: Option<Secret<String>>,
address_line_3: Option<Secret<String>>,
city: String,
state_or_region: Secret<String>,
postal_code: Secret<String>,
country_code: Option<common_enums::CountryAlpha2>,
phone_number: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq)]
pub enum PaymentIntent {
AuthorizeWithCapture,
}
fn get_amazonpay_capture_type(
item: Option<CaptureMethod>,
) -> CustomResult<PaymentIntent, errors::ConnectorError> {
match item {
Some(CaptureMethod::Automatic) | None => Ok(PaymentIntent::AuthorizeWithCapture),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
impl TryFrom<&AmazonpayRouterData<&PaymentsAuthorizeRouterData>> for AmazonpayFinalizeRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AmazonpayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let charge_amount = ChargeAmount {
amount: item.amount.clone(),
currency_code: item.router_data.request.currency,
};
let shipping_address = AddressDetails {
name: item.router_data.get_required_shipping_full_name()?,
address_line_1: item.router_data.get_required_shipping_line1()?,
address_line_2: item.router_data.get_optional_shipping_line2(),
address_line_3: item.router_data.get_optional_shipping_line3(),
city: item.router_data.get_required_shipping_city()?,
state_or_region: item.router_data.get_required_shipping_state()?,
postal_code: item.router_data.get_required_shipping_zip()?,
country_code: item.router_data.get_optional_shipping_country(),
phone_number: item.router_data.get_required_shipping_phone_number()?,
};
let payment_intent = get_amazonpay_capture_type(item.router_data.request.capture_method)?;
Ok(Self {
charge_amount,
shipping_address,
payment_intent,
})
}
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmazonpayFinalizeResponse {
checkout_session_id: String,
web_checkout_details: WebCheckoutDetails,
product_type: Option<String>,
payment_details: Option<PaymentDetails>,
cart_details: CartDetails,
charge_permission_type: String,
order_type: Option<String>,
recurring_metadata: Option<RecurringMetadata>,
payment_method_on_file_metadata: Option<String>,
processor_specifications: Option<String>,
merchant_details: Option<String>,
merchant_metadata: Option<MerchantMetadata>,
supplementary_data: Option<String>,
buyer: Option<BuyerDetails>,
billing_address: Option<AddressDetails>,
payment_preferences: Option<String>,
status_details: FinalizeStatusDetails,
shipping_address: Option<AddressDetails>,
platform_id: Option<String>,
charge_permission_id: String,
charge_id: String,
constraints: Option<String>,
creation_timestamp: String,
expiration_timestamp: Option<String>,
store_id: Option<String>,
provider_metadata: Option<ProviderMetadata>,
release_environment: Option<ReleaseEnvironment>,
checkout_button_text: Option<String>,
delivery_specifications: Option<DeliverySpecifications>,
tokens: Option<String>,
disbursement_details: Option<String>,
channel_type: Option<String>,
payment_processing_meta_data: PaymentProcessingMetaData,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct WebCheckoutDetails {
checkout_review_return_url: Option<String>,
checkout_result_return_url: Option<String>,
amazon_pay_redirect_url: Option<String>,
authorize_result_return_url: Option<String>,
sign_in_return_url: Option<String>,
sign_in_cancel_url: Option<String>,
checkout_error_url: Option<String>,
sign_in_error_url: Option<String>,
amazon_pay_decline_url: Option<String>,
checkout_cancel_url: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentDetails {
payment_intent: String,
can_handle_pending_authorization: bool,
charge_amount: ChargeAmount,
total_order_amount: ChargeAmount,
presentment_currency: String,
soft_descriptor: String,
allow_overcharge: bool,
extend_expiration: bool,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CartDetails {
line_items: Vec<String>,
delivery_options: Vec<DeliveryOptions>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DeliveryOptions {
id: String,
price: ChargeAmount,
shipping_method: ShippingMethod,
is_default: bool,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ShippingMethod {
shipping_method_name: String,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RecurringMetadata {
frequency: Frequency,
amount: ChargeAmount,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Frequency {
unit: String,
value: String,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct BuyerDetails {
buyer_id: Secret<String>,
name: Secret<String>,
email: pii::Email,
phone_number: Secret<String>,
prime_membership_types: Vec<String>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FinalizeStatusDetails {
state: FinalizeState,
reason_code: Option<String>,
reason_description: Option<String>,
last_updated_timestamp: String,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub enum FinalizeState {
Open,
Completed,
Canceled,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DeliverySpecifications {
special_restrictions: Vec<String>,
address_restrictions: AddressRestrictions,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AddressRestrictions {
r#type: String,
restrictions: HashMap<String, Restriction>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Restriction {
pub states_or_regions: Vec<Secret<String>>,
pub zip_codes: Vec<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentProcessingMetaData {
payment_processing_model: String,
}
impl From<FinalizeState> for common_enums::AttemptStatus {
fn from(item: FinalizeState) -> Self {
match item {
FinalizeState::Open => Self::Pending,
FinalizeState::Completed => Self::Charged,
FinalizeState::Canceled => Self::Failure,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AmazonpayFinalizeResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AmazonpayFinalizeResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.status_details.state {
FinalizeState::Canceled => {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "Checkout was not successfully completed".to_owned(),
reason: Some("Checkout was not successfully completed due to buyer abandoment, payment decline, or because checkout wasn't confirmed with Finalize Checkout Session.".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.checkout_session_id),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
FinalizeState::Open
| FinalizeState::Completed => {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status_details.state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.charge_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.checkout_session_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
}
}
pub struct AmazonpayAuthType {
pub(super) public_key: Secret<String>,
pub(super) private_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AmazonpayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
public_key: api_key.to_owned(),
private_key: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub enum AmazonpayPaymentStatus {
AuthorizationInitiated,
Authorized,
Canceled,
Captured,
CaptureInitiated,
Declined,
}
impl From<AmazonpayPaymentStatus> for common_enums::AttemptStatus {
fn from(item: AmazonpayPaymentStatus) -> Self {
match item {
AmazonpayPaymentStatus::AuthorizationInitiated => Self::Pending,
AmazonpayPaymentStatus::Authorized => Self::Authorized,
AmazonpayPaymentStatus::Canceled => Self::Voided,
AmazonpayPaymentStatus::Captured => Self::Charged,
AmazonpayPaymentStatus::CaptureInitiated => Self::CaptureInitiated,
AmazonpayPaymentStatus::Declined => Self::CaptureFailed,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmazonpayPaymentsResponse {
charge_id: String,
charge_amount: ChargeAmount,
charge_permission_id: String,
capture_amount: Option<ChargeAmount>,
refunded_amount: Option<ChargeAmount>,
soft_descriptor: Option<String>,
provider_metadata: Option<ProviderMetadata>,
converted_amount: Option<ChargeAmount>,
conversion_rate: Option<f64>,
channel: Option<String>,
charge_initiator: Option<String>,
status_details: PaymentsStatusDetails,
creation_timestamp: String,
expiration_timestamp: String,
release_environment: Option<ReleaseEnvironment>,
merchant_metadata: Option<MerchantMetadata>,
platform_id: Option<String>,
web_checkout_details: Option<WebCheckoutDetails>,
disbursement_details: Option<String>,
payment_method: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ProviderMetadata {
provider_reference_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentsStatusDetails {
state: AmazonpayPaymentStatus,
reason_code: Option<String>,
reason_description: Option<String>,
last_updated_timestamp: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ReleaseEnvironment {
Sandbox,
Live,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MerchantMetadata {
merchant_reference_id: Option<String>,
merchant_store_name: Option<String>,
note_to_buyer: Option<String>,
custom_information: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, AmazonpayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AmazonpayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.status_details.state {
AmazonpayPaymentStatus::Canceled => {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "Charge was canceled by Amazon or by the merchant".to_owned(),
reason: Some("Charge was canceled due to expiration, Amazon, buyer, merchant action, or charge permission cancellation.".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.charge_id),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
AmazonpayPaymentStatus::Declined => {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "The authorization or capture was declined".to_owned(),
reason: Some("Charge was declined due to soft/hard decline, Amazon rejection, or internal processing failure.".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.charge_id),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
_ => {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status_details.state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.charge_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AmazonpayRefundRequest {
pub refund_amount: ChargeAmount,
pub charge_id: String,
}
impl<F> TryFrom<&AmazonpayRouterData<&RefundsRouterData<F>>> for AmazonpayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AmazonpayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let refund_amount = ChargeAmount {
amount: item.amount.clone(),
currency_code: item.router_data.request.currency,
};
let charge_id = item.router_data.request.connector_transaction_id.clone();
Ok(Self {
refund_amount,
charge_id,
})
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum RefundStatus {
RefundInitiated,
Refunded,
Declined,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::RefundInitiated => Self::Pending,
RefundStatus::Refunded => Self::Success,
RefundStatus::Declined => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
refund_id: String,
charge_id: String,
creation_timestamp: String,
refund_amount: ChargeAmount,
status_details: RefundStatusDetails,
soft_descriptor: String,
release_environment: ReleaseEnvironment,
disbursement_details: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundStatusDetails {
state: RefundStatus,
reason_code: Option<String>,
reason_description: Option<String>,
last_updated_timestamp: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
match item.response.status_details.state {
RefundStatus::Declined => {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "Amazon has declined the refund.".to_owned(),
reason: Some("Amazon has declined the refund because maximum amount has been refunded or there was some other issue.".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.charge_id),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
_ => {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund_id,
refund_status: enums::RefundStatus::from(item.response.status_details.state),
}),
..item.data
})
}
}
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status_details.state);
let response = if is_refund_failure(refund_status) {
Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "Amazon has declined the refund.".to_owned(),
reason: Some("Amazon has declined the refund because maximum amount has been refunded or there was some other issue.".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.refund_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.refund_id.to_string(),
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmazonpayErrorResponse {
pub reason_code: String,
pub message: String,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs | crates/hyperswitch_connectors/src/connectors/noon/transformers.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::try_from(google_pay_data)
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "google_pay_data",
})?,
}))
}
WalletData::ApplePay(apple_pay_data) => {
let payment_token_data = NoonApplePayTokenData {
token: NoonApplePayData {
payment_data: wallet_data
.get_wallet_token_as_json("Apple Pay".to_string())?,
payment_method: NoonApplePayPaymentMethod {
display_name: apple_pay_data.payment_method.display_name,
network: apple_pay_data.payment_method.network,
pm_type: apple_pay_data.payment_method.pm_type,
},
transaction_identifier: Secret::new(
apple_pay_data.transaction_identifier,
),
},
};
let payment_token = payment_token_data
.encode_to_string_of_json()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(NoonPaymentData::ApplePay(NoonApplePay {
payment_info: Secret::new(payment_token),
}))
}
WalletData::PaypalRedirect(_) => Ok(NoonPaymentData::PayPal(NoonPayPal {
return_url: item.request.get_router_return_url()?,
})),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Noon"),
)),
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Noon"),
))
}
}?,
Some(item.request.currency),
Some(item.request.order_category.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "order_category",
},
)?),
),
};
let ip_address = item.request.get_ip_address_as_optional();
let channel = NoonChannels::Web;
let billing = item
.get_optional_billing()
.and_then(|billing_address| billing_address.address.as_ref())
.map(|address| NoonBilling {
address: NoonBillingAddress {
street: address.line1.clone(),
street2: address.line2.clone(),
city: address.city.clone(),
// If state is passed in request, country becomes mandatory, keep a check while debugging failed payments
state_province: address.state.clone(),
country: address.country,
postal_code: address.zip.clone(),
},
});
// The description should not have leading or trailing whitespaces, also it should not have double whitespaces and a max 50 chars according to Noon's Docs
let name: String = item
.get_description()?
.trim()
.replace(" ", " ")
.chars()
.take(50)
.collect();
let subscription = mandate_amount
.as_ref()
.map(|mandate_max_amount| NoonSubscriptionData {
subscription_type: NoonSubscriptionType::Unscheduled,
name: name.clone(),
max_amount: mandate_max_amount.to_owned(),
});
let tokenize_c_c = subscription.is_some().then_some(true);
let order = NoonOrder {
amount: amount.to_owned(),
currency,
channel,
category,
reference: item.connector_request_reference_id.clone(),
name,
nvp: item.request.metadata.as_ref().map(NoonOrderNvp::new),
ip_address,
};
let payment_action = if item.request.is_auto_capture()? {
NoonPaymentActions::Sale
} else {
NoonPaymentActions::Authorize
};
Ok(Self {
api_operation: NoonApiOperations::Initiate,
order,
billing,
configuration: NoonConfiguration {
payment_action,
return_url: item.request.router_return_url.clone(),
tokenize_c_c,
},
payment_data,
subscription,
})
}
}
// Auth Struct
pub struct NoonAuthType {
pub(super) api_key: Secret<String>,
pub(super) application_identifier: Secret<String>,
pub(super) business_identifier: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for NoonAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
api_key: api_key.to_owned(),
application_identifier: api_secret.to_owned(),
business_identifier: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Default, Debug, Deserialize, Serialize, strum::Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[strum(serialize_all = "UPPERCASE")]
pub enum NoonPaymentStatus {
Initiated,
Authorized,
Captured,
PartiallyCaptured,
PartiallyRefunded,
PaymentInfoAdded,
#[serde(rename = "3DS_ENROLL_INITIATED")]
ThreeDsEnrollInitiated,
#[serde(rename = "3DS_ENROLL_CHECKED")]
ThreeDsEnrollChecked,
#[serde(rename = "3DS_RESULT_VERIFIED")]
ThreeDsResultVerified,
MarkedForReview,
Authenticated,
PartiallyReversed,
#[default]
Pending,
Cancelled,
Failed,
Refunded,
Expired,
Reversed,
Rejected,
Locked,
}
fn get_payment_status(data: (NoonPaymentStatus, AttemptStatus)) -> AttemptStatus {
let (item, current_status) = data;
match item {
NoonPaymentStatus::Authorized => AttemptStatus::Authorized,
NoonPaymentStatus::Captured
| NoonPaymentStatus::PartiallyCaptured
| NoonPaymentStatus::PartiallyRefunded
| NoonPaymentStatus::Refunded => AttemptStatus::Charged,
NoonPaymentStatus::Reversed | NoonPaymentStatus::PartiallyReversed => AttemptStatus::Voided,
NoonPaymentStatus::Cancelled | NoonPaymentStatus::Expired => {
AttemptStatus::AuthenticationFailed
}
NoonPaymentStatus::ThreeDsEnrollInitiated | NoonPaymentStatus::ThreeDsEnrollChecked => {
AttemptStatus::AuthenticationPending
}
NoonPaymentStatus::ThreeDsResultVerified => AttemptStatus::AuthenticationSuccessful,
NoonPaymentStatus::Failed | NoonPaymentStatus::Rejected => AttemptStatus::Failure,
NoonPaymentStatus::Pending | NoonPaymentStatus::MarkedForReview => AttemptStatus::Pending,
NoonPaymentStatus::Initiated
| NoonPaymentStatus::PaymentInfoAdded
| NoonPaymentStatus::Authenticated => AttemptStatus::Started,
NoonPaymentStatus::Locked => current_status,
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NoonSubscriptionObject {
identifier: Secret<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsOrderResponse {
status: NoonPaymentStatus,
id: u64,
error_code: u64,
error_message: Option<String>,
reference: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonCheckoutData {
post_url: url::Url,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsResponseResult {
order: NoonPaymentsOrderResponse,
checkout_data: Option<NoonCheckoutData>,
subscription: Option<NoonSubscriptionObject>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NoonPaymentsResponse {
result: NoonPaymentsResponseResult,
}
impl<F, T> TryFrom<ResponseRouterData<F, NoonPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, NoonPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let order = item.response.result.order;
let status = get_payment_status((order.status, item.data.status));
let redirection_data =
item.response
.result
.checkout_data
.map(|redirection_data| RedirectForm::Form {
endpoint: redirection_data.post_url.to_string(),
method: Method::Post,
form_fields: std::collections::HashMap::new(),
});
let mandate_reference =
item.response
.result
.subscription
.map(|subscription_data| MandateReference {
connector_mandate_id: Some(subscription_data.identifier.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
Ok(Self {
status,
response: match order.error_message {
Some(error_message) => Err(ErrorResponse {
code: order.error_code.to_string(),
message: error_message.clone(),
reason: Some(error_message),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(order.id.to_string()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
_ => {
let connector_response_reference_id =
order.reference.or(Some(order.id.to_string()));
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(order.id.to_string()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id,
incremental_authorization_allowed: None,
charges: None,
})
}
},
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonActionTransaction {
amount: StringMajorUnit,
currency: enums::Currency,
transaction_reference: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonActionOrder {
id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsActionRequest {
api_operation: NoonApiOperations,
order: NoonActionOrder,
transaction: NoonActionTransaction,
}
impl TryFrom<&NoonRouterData<&PaymentsCaptureRouterData>> for NoonPaymentsActionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(data: &NoonRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let item = data.router_data;
let amount = &data.amount;
let order = NoonActionOrder {
id: item.request.connector_transaction_id.clone(),
};
let transaction = NoonActionTransaction {
amount: amount.to_owned(),
currency: item.request.currency,
transaction_reference: None,
};
Ok(Self {
api_operation: NoonApiOperations::Capture,
order,
transaction,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsCancelRequest {
api_operation: NoonApiOperations,
order: NoonActionOrder,
}
impl TryFrom<&PaymentsCancelRouterData> for NoonPaymentsCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let order = NoonActionOrder {
id: item.request.connector_transaction_id.clone(),
};
Ok(Self {
api_operation: NoonApiOperations::Reverse,
order,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonRevokeMandateRequest {
api_operation: NoonApiOperations,
subscription: NoonSubscriptionObject,
}
impl TryFrom<&MandateRevokeRouterData> for NoonRevokeMandateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &MandateRevokeRouterData) -> Result<Self, Self::Error> {
Ok(Self {
api_operation: NoonApiOperations::CancelSubscription,
subscription: NoonSubscriptionObject {
identifier: Secret::new(item.request.get_connector_mandate_id()?),
},
})
}
}
impl<F> TryFrom<&NoonRouterData<&RefundsRouterData<F>>> for NoonPaymentsActionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(data: &NoonRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let item = data.router_data;
let refund_amount = &data.amount;
let order = NoonActionOrder {
id: item.request.connector_transaction_id.clone(),
};
let transaction = NoonActionTransaction {
amount: refund_amount.to_owned(),
currency: item.request.currency,
transaction_reference: Some(item.request.refund_id.clone()),
};
Ok(Self {
api_operation: NoonApiOperations::Refund,
order,
transaction,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub enum NoonRevokeStatus {
Cancelled,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NoonCancelSubscriptionObject {
status: NoonRevokeStatus,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NoonRevokeMandateResult {
subscription: NoonCancelSubscriptionObject,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NoonRevokeMandateResponse {
result: NoonRevokeMandateResult,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
NoonRevokeMandateResponse,
MandateRevokeRequestData,
MandateRevokeResponseData,
>,
> for RouterData<F, MandateRevokeRequestData, MandateRevokeResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
NoonRevokeMandateResponse,
MandateRevokeRequestData,
MandateRevokeResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.result.subscription.status {
NoonRevokeStatus::Cancelled => Ok(Self {
response: Ok(MandateRevokeResponseData {
mandate_status: common_enums::MandateStatus::Revoked,
}),
..item.data
}),
}
}
}
#[derive(Debug, Default, Deserialize, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Success,
Failed,
#[default]
Pending,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Success => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Pending => Self::Pending,
}
}
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsTransactionResponse {
id: String,
status: RefundStatus,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonRefundResponseResult {
transaction: NoonPaymentsTransactionResponse,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
result: NoonRefundResponseResult,
result_code: u32,
class_description: String,
message: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let response = &item.response;
let refund_status =
enums::RefundStatus::from(response.result.transaction.status.to_owned());
let response = if utils::is_refund_failure(refund_status) {
Err(ErrorResponse {
status_code: item.http_code,
code: response.result_code.to_string(),
message: response.message.clone(),
reason: Some(response.message.clone()),
attempt_status: None,
connector_transaction_id: Some(response.result.transaction.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.result.transaction.id,
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonRefundResponseTransactions {
id: String,
status: RefundStatus,
transaction_reference: Option<String>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonRefundSyncResponseResult {
transactions: Vec<NoonRefundResponseTransactions>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundSyncResponse {
result: NoonRefundSyncResponseResult,
result_code: u32,
class_description: String,
message: String,
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundSyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundSyncResponse>,
) -> Result<Self, Self::Error> {
let noon_transaction: &NoonRefundResponseTransactions = item
.response
.result
.transactions
.iter()
.find(|transaction| {
transaction
.transaction_reference
.clone()
.is_some_and(|transaction_instance| {
transaction_instance == item.data.request.refund_id
})
})
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let refund_status = enums::RefundStatus::from(noon_transaction.status.to_owned());
let response = if utils::is_refund_failure(refund_status) {
let response = &item.response;
Err(ErrorResponse {
status_code: item.http_code,
code: response.result_code.to_string(),
message: response.message.clone(),
reason: Some(response.message.clone()),
attempt_status: None,
connector_transaction_id: Some(noon_transaction.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: noon_transaction.id.to_owned(),
refund_status,
})
};
Ok(Self {
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/hyperwallet/transformers.rs | crates/hyperswitch_connectors/src/connectors/hyperwallet/transformers.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};
//TODO: Fill the struct with respective fields
pub struct HyperwalletRouterData<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 HyperwalletRouterData<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 HyperwalletPaymentsRequest {
amount: StringMinorUnit,
card: HyperwalletCard,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct HyperwalletCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&HyperwalletRouterData<&PaymentsAuthorizeRouterData>> for HyperwalletPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &HyperwalletRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
"Card payment method not implemented".to_string(),
)
.into()),
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
//TODO: Fill the struct with respective fields
// Auth Struct
pub struct HyperwalletAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for HyperwalletAuthType {
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, Copy, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum HyperwalletPaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<HyperwalletPaymentStatus> for common_enums::AttemptStatus {
fn from(item: HyperwalletPaymentStatus) -> Self {
match item {
HyperwalletPaymentStatus::Succeeded => Self::Charged,
HyperwalletPaymentStatus::Failed => Self::Failure,
HyperwalletPaymentStatus::Processing => Self::Authorizing,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct HyperwalletPaymentsResponse {
status: HyperwalletPaymentStatus,
id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, HyperwalletPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, HyperwalletPaymentsResponse, 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 HyperwalletRefundRequest {
pub amount: StringMinorUnit,
}
impl<F> TryFrom<&HyperwalletRouterData<&RefundsRouterData<F>>> for HyperwalletRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &HyperwalletRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct HyperwalletErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
pub network_advice_code: Option<String>,
pub network_decline_code: Option<String>,
pub network_error_message: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs | crates/hyperswitch_connectors/src/connectors/forte/transformers.rs | use cards::CardNumber;
use common_enums::enums;
use common_utils::types::FloatMajorUnit;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{PaymentsCaptureResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, CardData as _PaymentsAuthorizeRequestData,
PaymentsAuthorizeRequestData, RouterData as _,
},
};
#[derive(Debug, Serialize)]
pub struct ForteRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for ForteRouterData<T> {
fn from((amount, router_data): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Serialize)]
pub struct FortePaymentsRequest {
action: ForteAction,
authorization_amount: FloatMajorUnit,
billing_address: BillingAddress,
card: Card,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BillingAddress {
first_name: Secret<String>,
last_name: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct Card {
card_type: ForteCardType,
name_on_card: Secret<String>,
account_number: CardNumber,
expire_month: Secret<String>,
expire_year: Secret<String>,
card_verification_value: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ForteCardType {
Visa,
MasterCard,
Amex,
Discover,
DinersClub,
Jcb,
}
impl TryFrom<utils::CardIssuer> for ForteCardType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(issuer: utils::CardIssuer) -> Result<Self, Self::Error> {
match issuer {
utils::CardIssuer::AmericanExpress => Ok(Self::Amex),
utils::CardIssuer::Master => Ok(Self::MasterCard),
utils::CardIssuer::Discover => Ok(Self::Discover),
utils::CardIssuer::Visa => Ok(Self::Visa),
utils::CardIssuer::DinersClub => Ok(Self::DinersClub),
utils::CardIssuer::JCB => Ok(Self::Jcb),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Forte"),
)
.into()),
}
}
}
impl TryFrom<&ForteRouterData<&types::PaymentsAuthorizeRouterData>> for FortePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item_data: &ForteRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let item = item_data.router_data;
match item.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => {
if item.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Cards 3DS".to_string(),
connector: "Forte",
})?
}
let action = match item.request.is_auto_capture()? {
true => ForteAction::Sale,
false => ForteAction::Authorize,
};
let card_type = ForteCardType::try_from(ccard.get_card_issuer()?)?;
let address = item.get_billing_address()?;
let card = Card {
card_type,
name_on_card: item
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string())),
account_number: ccard.card_number.clone(),
expire_month: ccard.card_exp_month.clone(),
expire_year: ccard.card_exp_year.clone(),
card_verification_value: ccard.card_cvc.clone(),
};
let first_name = address.get_first_name()?;
let billing_address = BillingAddress {
first_name: first_name.clone(),
last_name: address.get_last_name().unwrap_or(first_name).clone(),
};
let authorization_amount = item_data.amount;
Ok(Self {
action,
authorization_amount,
billing_address,
card,
})
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Forte"),
))?
}
}
}
}
// Auth Struct
pub struct ForteAuthType {
pub(super) api_access_id: Secret<String>,
pub(super) organization_id: Secret<String>,
pub(super) location_id: Secret<String>,
pub(super) api_secret_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for ForteAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Ok(Self {
api_access_id: api_key.to_owned(),
organization_id: Secret::new(format!("org_{}", key1.peek())),
location_id: Secret::new(format!("loc_{}", key2.peek())),
api_secret_key: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
}
// PaymentsResponse
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum FortePaymentStatus {
Complete,
Failed,
Authorized,
Ready,
Voided,
Settled,
}
impl From<FortePaymentStatus> for enums::AttemptStatus {
fn from(item: FortePaymentStatus) -> Self {
match item {
FortePaymentStatus::Complete | FortePaymentStatus::Settled => Self::Charged,
FortePaymentStatus::Failed => Self::Failure,
FortePaymentStatus::Ready => Self::Pending,
FortePaymentStatus::Authorized => Self::Authorized,
FortePaymentStatus::Voided => Self::Voided,
}
}
}
fn get_status(response_code: ForteResponseCode, action: ForteAction) -> enums::AttemptStatus {
match response_code {
ForteResponseCode::A01 => match action {
ForteAction::Authorize => enums::AttemptStatus::Authorized,
ForteAction::Sale => enums::AttemptStatus::Pending,
ForteAction::Verify | ForteAction::Capture => enums::AttemptStatus::Charged,
},
ForteResponseCode::A05 | ForteResponseCode::A06 => enums::AttemptStatus::Authorizing,
_ => enums::AttemptStatus::Failure,
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CardResponse {
pub name_on_card: Option<Secret<String>>,
pub last_4_account_number: String,
pub masked_account_number: String,
pub card_type: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub enum ForteResponseCode {
A01,
A05,
A06,
U13,
U14,
U18,
U20,
}
impl From<ForteResponseCode> for enums::AttemptStatus {
fn from(item: ForteResponseCode) -> Self {
match item {
ForteResponseCode::A01 | ForteResponseCode::A05 | ForteResponseCode::A06 => {
Self::Pending
}
_ => Self::Failure,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ResponseStatus {
pub environment: String,
pub response_type: String,
pub response_code: ForteResponseCode,
pub response_desc: String,
pub authorization_code: String,
pub avs_result: Option<String>,
pub cvv_result: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ForteAction {
Sale,
Authorize,
Verify,
Capture,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct FortePaymentsResponse {
pub transaction_id: String,
pub location_id: Secret<String>,
pub action: ForteAction,
pub authorization_amount: Option<FloatMajorUnit>,
pub authorization_code: String,
pub entered_by: String,
pub billing_address: Option<BillingAddress>,
pub card: Option<CardResponse>,
pub response: ResponseStatus,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ForteMeta {
pub auth_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, FortePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FortePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response_code = item.response.response.response_code;
let action = item.response.action;
let transaction_id = &item.response.transaction_id;
Ok(Self {
status: get_status(response_code, action),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(ForteMeta {
auth_id: item.response.authorization_code,
})),
network_txn_id: None,
connector_response_reference_id: Some(transaction_id.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
//PsyncResponse
#[derive(Debug, Deserialize, Serialize)]
pub struct FortePaymentsSyncResponse {
pub transaction_id: String,
pub organization_id: Secret<String>,
pub location_id: Secret<String>,
pub original_transaction_id: Option<String>,
pub status: FortePaymentStatus,
pub action: ForteAction,
pub authorization_code: String,
pub authorization_amount: Option<FloatMajorUnit>,
pub billing_address: Option<BillingAddress>,
pub entered_by: String,
pub received_date: String,
pub origination_date: Option<String>,
pub card: Option<CardResponse>,
pub attempt_number: i64,
pub response: ResponseStatus,
pub links: ForteLink,
pub biller_name: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ForteLink {
pub disputes: String,
pub settlements: String,
#[serde(rename = "self")]
pub self_url: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, FortePaymentsSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FortePaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction_id = &item.response.transaction_id;
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(ForteMeta {
auth_id: item.response.authorization_code,
})),
network_txn_id: None,
connector_response_reference_id: Some(transaction_id.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// Capture
#[derive(Debug, Serialize)]
pub struct ForteCaptureRequest {
action: String,
transaction_id: String,
authorization_code: String,
}
impl TryFrom<&types::PaymentsCaptureRouterData> for ForteCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
let trn_id = item.request.connector_transaction_id.clone();
let connector_auth_id: ForteMeta =
utils::to_connector_meta(item.request.connector_meta.clone())?;
let auth_code = connector_auth_id.auth_id;
Ok(Self {
action: "capture".to_string(),
transaction_id: trn_id,
authorization_code: auth_code,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CaptureResponseStatus {
pub environment: String,
pub response_type: String,
pub response_code: ForteResponseCode,
pub response_desc: String,
pub authorization_code: String,
}
// Capture Response
#[derive(Debug, Deserialize, Serialize)]
pub struct ForteCaptureResponse {
pub transaction_id: String,
pub original_transaction_id: String,
pub entered_by: String,
pub authorization_code: String,
pub response: CaptureResponseStatus,
}
impl TryFrom<PaymentsCaptureResponseRouterData<ForteCaptureResponse>>
for types::PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<ForteCaptureResponse>,
) -> Result<Self, Self::Error> {
let transaction_id = &item.response.transaction_id;
Ok(Self {
status: enums::AttemptStatus::from(item.response.response.response_code),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(ForteMeta {
auth_id: item.response.authorization_code,
})),
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
amount_captured: None,
..item.data
})
}
}
//Cancel
#[derive(Debug, Serialize)]
pub struct ForteCancelRequest {
action: String,
authorization_code: String,
}
impl TryFrom<&types::PaymentsCancelRouterData> for ForteCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let action = "void".to_string();
let connector_auth_id: ForteMeta =
utils::to_connector_meta(item.request.connector_meta.clone())?;
let authorization_code = connector_auth_id.auth_id;
Ok(Self {
action,
authorization_code,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CancelResponseStatus {
pub response_type: String,
pub response_code: ForteResponseCode,
pub response_desc: String,
pub authorization_code: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ForteCancelResponse {
pub transaction_id: String,
pub location_id: Secret<String>,
pub action: String,
pub authorization_code: String,
pub entered_by: String,
pub response: CancelResponseStatus,
}
impl<F, T> TryFrom<ResponseRouterData<F, ForteCancelResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ForteCancelResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction_id = &item.response.transaction_id;
Ok(Self {
status: enums::AttemptStatus::from(item.response.response.response_code),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(ForteMeta {
auth_id: item.response.authorization_code,
})),
network_txn_id: None,
connector_response_reference_id: Some(transaction_id.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
#[derive(Default, Debug, Serialize)]
pub struct ForteRefundRequest {
action: String,
authorization_amount: FloatMajorUnit,
original_transaction_id: String,
authorization_code: String,
}
impl<F> TryFrom<&ForteRouterData<&types::RefundsRouterData<F>>> for ForteRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item_data: &ForteRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let item = item_data.router_data;
let trn_id = item.request.connector_transaction_id.clone();
let connector_auth_id: ForteMeta =
utils::to_connector_meta(item.request.connector_metadata.clone())?;
let auth_code = connector_auth_id.auth_id;
let authorization_amount = item_data.amount;
Ok(Self {
action: "reverse".to_string(),
authorization_amount,
original_transaction_id: trn_id,
authorization_code: auth_code,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum RefundStatus {
Complete,
Ready,
Failed,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Complete => Self::Success,
RefundStatus::Ready => Self::Pending,
RefundStatus::Failed => Self::Failure,
}
}
}
impl From<ForteResponseCode> for enums::RefundStatus {
fn from(item: ForteResponseCode) -> Self {
match item {
ForteResponseCode::A01 | ForteResponseCode::A05 | ForteResponseCode::A06 => {
Self::Pending
}
_ => Self::Failure,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RefundResponse {
pub transaction_id: String,
pub original_transaction_id: String,
pub action: String,
pub authorization_amount: Option<FloatMajorUnit>,
pub authorization_code: String,
pub response: ResponseStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.response.response_code),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RefundSyncResponse {
status: RefundStatus,
transaction_id: String,
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundSyncResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ErrorResponseStatus {
pub environment: String,
pub response_type: Option<String>,
pub response_code: Option<String>,
pub response_desc: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ForteErrorResponse {
pub response: ErrorResponseStatus,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs | crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs | use common_enums::enums;
use common_utils::types::MinorUnit;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::{RefundsData, ResponseId, SetupMandateRequestData},
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsCaptureResponseRouterData, PaymentsResponseRouterData,
PaymentsSyncResponseRouterData, ResponseRouterData,
},
utils::{self, CardData as _, PaymentsAuthorizeRequestData, RouterData as _},
};
type Error = error_stack::Report<errors::ConnectorError>;
pub struct BamboraapacRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for BamboraapacRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BamboraapacMeta {
pub authorize_id: String,
}
// request body in soap format
pub fn get_payment_body(
req: &BamboraapacRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Vec<u8>, Error> {
let transaction_data = get_transaction_body(req)?;
let body = format!(
r#"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Body>
<dts:SubmitSinglePayment>
<dts:trnXML>
<![CDATA[
{transaction_data}
]]>
</dts:trnXML>
</dts:SubmitSinglePayment>
</soapenv:Body>
</soapenv:Envelope>
"#,
);
Ok(body.as_bytes().to_vec())
}
fn get_transaction_body(
req: &BamboraapacRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<String, Error> {
let auth_details = BamboraapacAuthType::try_from(&req.router_data.connector_auth_type)?;
let transaction_type = get_transaction_type(req.router_data.request.capture_method)?;
let card_info = get_card_data(req.router_data)?;
let transaction_data = format!(
r#"
<Transaction>
<CustRef>{}</CustRef>
<Amount>{}</Amount>
<TrnType>{}</TrnType>
<AccountNumber>{}</AccountNumber>
{}
<Security>
<UserName>{}</UserName>
<Password>{}</Password>
</Security>
</Transaction>
"#,
req.router_data.connector_request_reference_id.to_owned(),
req.amount,
transaction_type,
auth_details.account_number.peek(),
card_info,
auth_details.username.peek(),
auth_details.password.peek(),
);
Ok(transaction_data)
}
fn get_card_data(req: &types::PaymentsAuthorizeRouterData) -> Result<String, Error> {
let card_data = match &req.request.payment_method_data {
PaymentMethodData::Card(card) => {
if req.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Cards 3DS".to_string(),
connector: "Bamboraapac",
})?
}
let card_holder_name = req.get_billing_full_name()?;
if req.request.setup_future_usage == Some(enums::FutureUsage::OffSession) {
format!(
r#"
<CreditCard Registered="False">
<TokeniseAlgorithmID>2</TokeniseAlgorithmID>
<CardNumber>{}</CardNumber>
<ExpM>{}</ExpM>
<ExpY>{}</ExpY>
<CVN>{}</CVN>
<CardHolderName>{}</CardHolderName>
</CreditCard>
"#,
card.card_number.get_card_no(),
card.card_exp_month.peek(),
card.get_expiry_year_4_digit().peek(),
card.card_cvc.peek(),
card_holder_name.peek(),
)
} else {
format!(
r#"
<CreditCard Registered="False">
<CardNumber>{}</CardNumber>
<ExpM>{}</ExpM>
<ExpY>{}</ExpY>
<CVN>{}</CVN>
<CardHolderName>{}</CardHolderName>
</CreditCard>
"#,
card.card_number.get_card_no(),
card.card_exp_month.peek(),
card.get_expiry_year_4_digit().peek(),
card.card_cvc.peek(),
card_holder_name.peek(),
)
}
}
PaymentMethodData::MandatePayment => {
format!(
r#"
<CreditCard>
<TokeniseAlgorithmID>2</TokeniseAlgorithmID>
<CardNumber>{}</CardNumber>
</CreditCard>
"#,
req.request.get_connector_mandate_id()?
)
}
_ => {
return Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Bambora APAC"),
))?
}
};
Ok(card_data)
}
fn get_transaction_type(capture_method: Option<enums::CaptureMethod>) -> Result<u8, Error> {
match capture_method {
Some(enums::CaptureMethod::Automatic) | None => Ok(1),
Some(enums::CaptureMethod::Manual) => Ok(2),
_ => Err(errors::ConnectorError::CaptureMethodNotSupported)?,
}
}
pub struct BamboraapacAuthType {
username: Secret<String>,
password: Secret<String>,
account_number: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BamboraapacAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
username: api_key.to_owned(),
password: api_secret.to_owned(),
account_number: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Envelope")]
#[serde(rename_all = "PascalCase")]
pub struct BamboraapacPaymentsResponse {
body: BodyResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct BodyResponse {
submit_single_payment_response: SubmitSinglePaymentResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSinglePaymentResponse {
submit_single_payment_result: SubmitSinglePaymentResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSinglePaymentResult {
response: PaymentResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PaymentResponse {
response_code: u8,
receipt: String,
credit_card_token: Option<String>,
declined_code: Option<String>,
declined_message: Option<String>,
}
fn get_attempt_status(
response_code: u8,
capture_method: Option<enums::CaptureMethod>,
) -> enums::AttemptStatus {
match response_code {
0 => match capture_method {
Some(enums::CaptureMethod::Automatic) | None => enums::AttemptStatus::Charged,
Some(enums::CaptureMethod::Manual) => enums::AttemptStatus::Authorized,
_ => enums::AttemptStatus::Pending,
},
1 => enums::AttemptStatus::Failure,
_ => enums::AttemptStatus::Pending,
}
}
impl TryFrom<PaymentsResponseRouterData<BamboraapacPaymentsResponse>>
for types::PaymentsAuthorizeRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<BamboraapacPaymentsResponse>,
) -> Result<Self, Self::Error> {
let response_code = item
.response
.body
.submit_single_payment_response
.submit_single_payment_result
.response
.response_code;
let connector_transaction_id = item
.response
.body
.submit_single_payment_response
.submit_single_payment_result
.response
.receipt;
let mandate_reference =
if item.data.request.setup_future_usage == Some(enums::FutureUsage::OffSession) {
let connector_mandate_id = item
.response
.body
.submit_single_payment_response
.submit_single_payment_result
.response
.credit_card_token;
Some(MandateReference {
connector_mandate_id,
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})
} else {
None
};
// transaction approved
if response_code == 0 {
Ok(Self {
status: get_attempt_status(response_code, item.data.request.capture_method),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
connector_transaction_id.to_owned(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(connector_transaction_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
// transaction failed
else {
let code = item
.response
.body
.submit_single_payment_response
.submit_single_payment_result
.response
.declined_code
.unwrap_or(NO_ERROR_CODE.to_string());
let declined_message = item
.response
.body
.submit_single_payment_response
.submit_single_payment_result
.response
.declined_message
.unwrap_or(NO_ERROR_MESSAGE.to_string());
Ok(Self {
status: get_attempt_status(response_code, item.data.request.capture_method),
response: Err(ErrorResponse {
status_code: item.http_code,
code,
message: declined_message.to_owned(),
reason: Some(declined_message),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
pub fn get_setup_mandate_body(req: &types::SetupMandateRouterData) -> Result<Vec<u8>, Error> {
let card_holder_name = req.get_billing_full_name()?;
let auth_details = BamboraapacAuthType::try_from(&req.connector_auth_type)?;
let body = match &req.request.payment_method_data {
PaymentMethodData::Card(card) => {
format!(
r#"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:sipp="http://www.ippayments.com.au/interface/api/sipp">
<soapenv:Header/>
<soapenv:Body>
<sipp:TokeniseCreditCard>
<sipp:tokeniseCreditCardXML>
<![CDATA[
<TokeniseCreditCard>
<CardNumber>{}</CardNumber>
<ExpM>{}</ExpM>
<ExpY>{}</ExpY>
<CardHolderName>{}</CardHolderName>
<TokeniseAlgorithmID>2</TokeniseAlgorithmID>
<UserName>{}</UserName>
<Password>{}</Password>
</TokeniseCreditCard>
]]>
</sipp:tokeniseCreditCardXML>
</sipp:TokeniseCreditCard>
</soapenv:Body>
</soapenv:Envelope>
"#,
card.card_number.get_card_no(),
card.card_exp_month.peek(),
card.get_expiry_year_4_digit().peek(),
card_holder_name.peek(),
auth_details.username.peek(),
auth_details.password.peek(),
)
}
_ => {
return Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Bambora APAC"),
))?;
}
};
Ok(body.as_bytes().to_vec())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Envelope")]
#[serde(rename_all = "PascalCase")]
pub struct BamboraapacMandateResponse {
body: MandateBodyResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct MandateBodyResponse {
tokenise_credit_card_response: TokeniseCreditCardResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct TokeniseCreditCardResponse {
tokenise_credit_card_result: TokeniseCreditCardResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct TokeniseCreditCardResult {
tokenise_credit_card_response: MandateResponseBody,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct MandateResponseBody {
return_value: u8,
token: Option<String>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BamboraapacMandateResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
> for RouterData<F, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BamboraapacMandateResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_code = item
.response
.body
.tokenise_credit_card_response
.tokenise_credit_card_result
.tokenise_credit_card_response
.return_value;
let connector_mandate_id = item
.response
.body
.tokenise_credit_card_response
.tokenise_credit_card_result
.tokenise_credit_card_response
.token
.ok_or(errors::ConnectorError::MissingConnectorMandateID)?;
// transaction approved
if response_code == 0 {
Ok(Self {
status: enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(Some(MandateReference {
connector_mandate_id: Some(connector_mandate_id),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
// transaction failed
else {
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
status_code: item.http_code,
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
// capture body in soap format
pub fn get_capture_body(
req: &BamboraapacRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Vec<u8>, Error> {
let receipt = req.router_data.request.connector_transaction_id.to_owned();
let auth_details = BamboraapacAuthType::try_from(&req.router_data.connector_auth_type)?;
let body = format!(
r#"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Body>
<dts:SubmitSingleCapture>
<dts:trnXML>
<![CDATA[
<Capture>
<Receipt>{}</Receipt>
<Amount>{}</Amount>
<Security>
<UserName>{}</UserName>
<Password>{}</Password>
</Security>
</Capture>
]]>
</dts:trnXML>
</dts:SubmitSingleCapture>
</soapenv:Body>
</soapenv:Envelope>
"#,
receipt,
req.amount,
auth_details.username.peek(),
auth_details.password.peek(),
);
Ok(body.as_bytes().to_vec())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Envelope")]
#[serde(rename_all = "PascalCase")]
pub struct BamboraapacCaptureResponse {
body: CaptureBodyResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CaptureBodyResponse {
submit_single_capture_response: SubmitSingleCaptureResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSingleCaptureResponse {
submit_single_capture_result: SubmitSingleCaptureResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSingleCaptureResult {
response: CaptureResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CaptureResponse {
response_code: u8,
receipt: String,
declined_code: Option<String>,
declined_message: Option<String>,
}
impl TryFrom<PaymentsCaptureResponseRouterData<BamboraapacCaptureResponse>>
for types::PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<BamboraapacCaptureResponse>,
) -> Result<Self, Self::Error> {
let response_code = item
.response
.body
.submit_single_capture_response
.submit_single_capture_result
.response
.response_code;
let connector_transaction_id = item
.response
.body
.submit_single_capture_response
.submit_single_capture_result
.response
.receipt;
// storing receipt_id of authorize to metadata for future usage
let connector_metadata = Some(serde_json::json!(BamboraapacMeta {
authorize_id: item.data.request.connector_transaction_id.to_owned()
}));
// transaction approved
if response_code == 0 {
Ok(Self {
status: enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
connector_transaction_id.to_owned(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(connector_transaction_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
// transaction failed
else {
let code = item
.response
.body
.submit_single_capture_response
.submit_single_capture_result
.response
.declined_code
.unwrap_or(NO_ERROR_CODE.to_string());
let declined_message = item
.response
.body
.submit_single_capture_response
.submit_single_capture_result
.response
.declined_message
.unwrap_or(NO_ERROR_MESSAGE.to_string());
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
status_code: item.http_code,
code,
message: declined_message.to_owned(),
reason: Some(declined_message),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
// refund body in soap format
pub fn get_refund_body(
req: &BamboraapacRouterData<&types::RefundExecuteRouterData>,
) -> Result<Vec<u8>, Error> {
let receipt = req.router_data.request.connector_transaction_id.to_owned();
let auth_details = BamboraapacAuthType::try_from(&req.router_data.connector_auth_type)?;
let body = format!(
r#"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Header/>
<soapenv:Body>
<dts:SubmitSingleRefund>
<dts:trnXML>
<![CDATA[
<Refund>
<CustRef>{}</CustRef>
<Receipt>{}</Receipt>
<Amount>{}</Amount>
<Security>
<UserName>{}</UserName>
<Password>{}</Password>
</Security>
</Refund>
]]>
</dts:trnXML>
</dts:SubmitSingleRefund>
</soapenv:Body>
</soapenv:Envelope>
"#,
req.router_data.request.refund_id.to_owned(),
receipt,
req.amount,
auth_details.username.peek(),
auth_details.password.peek(),
);
Ok(body.as_bytes().to_vec())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Envelope")]
#[serde(rename_all = "PascalCase")]
pub struct BamboraapacRefundsResponse {
body: RefundBodyResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct RefundBodyResponse {
submit_single_refund_response: SubmitSingleRefundResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSingleRefundResponse {
submit_single_refund_result: SubmitSingleRefundResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubmitSingleRefundResult {
response: RefundResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct RefundResponse {
response_code: u8,
receipt: String,
declined_code: Option<String>,
declined_message: Option<String>,
}
fn get_status(item: u8) -> enums::RefundStatus {
match item {
0 => enums::RefundStatus::Success,
1 => enums::RefundStatus::Failure,
_ => enums::RefundStatus::Pending,
}
}
impl<F> TryFrom<ResponseRouterData<F, BamboraapacRefundsResponse, RefundsData, RefundsResponseData>>
for RouterData<F, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BamboraapacRefundsResponse, RefundsData, RefundsResponseData>,
) -> Result<Self, Self::Error> {
let response_code = item
.response
.body
.submit_single_refund_response
.submit_single_refund_result
.response
.response_code;
let connector_refund_id = item
.response
.body
.submit_single_refund_response
.submit_single_refund_result
.response
.receipt;
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: connector_refund_id.to_owned(),
refund_status: get_status(response_code),
}),
..item.data
})
}
}
pub fn get_payment_sync_body(req: &types::PaymentsSyncRouterData) -> Result<Vec<u8>, Error> {
let auth_details = BamboraapacAuthType::try_from(&req.connector_auth_type)?;
let connector_transaction_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
let body = format!(
r#"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Header/>
<soapenv:Body>
<dts:QueryTransaction>
<dts:queryXML>
<![CDATA[
<QueryTransaction>
<Criteria>
<AccountNumber>{}</AccountNumber>
<TrnStartTimestamp>2024-06-23 00:00:00</TrnStartTimestamp>
<TrnEndTimestamp>2099-12-31 23:59:59</TrnEndTimestamp>
<Receipt>{}</Receipt>
</Criteria>
<Security>
<UserName>{}</UserName>
<Password>{}</Password>
</Security>
</QueryTransaction>
]]>
</dts:queryXML>
</dts:QueryTransaction>
</soapenv:Body>
</soapenv:Envelope>
"#,
auth_details.account_number.peek(),
connector_transaction_id,
auth_details.username.peek(),
auth_details.password.peek(),
);
Ok(body.as_bytes().to_vec())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Envelope")]
#[serde(rename_all = "PascalCase")]
pub struct BamboraapacSyncResponse {
body: SyncBodyResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SyncBodyResponse {
query_transaction_response: QueryTransactionResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct QueryTransactionResponse {
query_transaction_result: QueryTransactionResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct QueryTransactionResult {
query_response: QueryResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct QueryResponse {
response: SyncResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SyncResponse {
response_code: u8,
receipt: String,
declined_code: Option<String>,
declined_message: Option<String>,
}
impl TryFrom<PaymentsSyncResponseRouterData<BamboraapacSyncResponse>>
for types::PaymentsSyncRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<BamboraapacSyncResponse>,
) -> Result<Self, Self::Error> {
let response_code = item
.response
.body
.query_transaction_response
.query_transaction_result
.query_response
.response
.response_code;
let connector_transaction_id = item
.response
.body
.query_transaction_response
.query_transaction_result
.query_response
.response
.receipt;
// transaction approved
if response_code == 0 {
Ok(Self {
status: get_attempt_status(response_code, item.data.request.capture_method),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
connector_transaction_id.to_owned(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(connector_transaction_id),
incremental_authorization_allowed: None,
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,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs | crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs | use api_models::webhooks::IncomingWebhookEvent;
use base64::Engine;
use cards::CardNumber;
use common_enums::{AttemptStatus, AuthenticationType, CountryAlpha2, Currency, RefundStatus};
use common_utils::{errors::CustomResult, ext_traits::XmlExt, pii::Email, types::FloatMajorUnit};
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::{
ApplePayWalletData, Card, GooglePayWalletData, PaymentMethodData, WalletData,
},
router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},
router_flow_types::{
Authorize, Capture, CompleteAuthorize, Execute, RSync, SetupMandate, Void,
},
router_request_types::{
CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCaptureData, ResponseId,
},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsPreAuthenticateRouterData,
PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsPreAuthenticateResponseRouterData, PaymentsPreprocessingResponseRouterData,
PaymentsResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
},
unimplemented_payment_method,
utils::{
get_unimplemented_payment_method_error_message, to_currency_base_unit_asf64,
AddressDetailsData as _, CardData as _, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData as _, RouterData as _,
},
};
type Error = Report<ConnectorError>;
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum TransactionType {
Auth,
Capture,
Refund,
Sale,
Validate,
Void,
}
pub struct NmiAuthType {
pub(super) api_key: Secret<String>,
pub(super) public_key: Option<Secret<String>>,
}
impl TryFrom<&ConnectorAuthType> for NmiAuthType {
type Error = Error;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
public_key: None,
}),
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
public_key: Some(key1.to_owned()),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize)]
pub struct NmiRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for NmiRouterData<T> {
fn from((amount, router_data): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Serialize)]
pub struct NmiVaultRequest {
security_key: Secret<String>,
ccnumber: CardNumber,
ccexp: Secret<String>,
cvv: Secret<String>,
first_name: Secret<String>,
last_name: Secret<String>,
address1: Option<Secret<String>>,
address2: Option<Secret<String>>,
city: Option<String>,
state: Option<Secret<String>>,
zip: Option<Secret<String>>,
country: Option<CountryAlpha2>,
customer_vault: CustomerAction,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CustomerAction {
AddCustomer,
UpdateCustomer,
}
fn try_build_nmi_vault_request_from_router_data(
connector_auth_type: &ConnectorAuthType,
payment_method_data: Option<PaymentMethodData>,
billing_address: Result<&hyperswitch_domain_models::address::AddressDetails, Error>,
) -> Result<NmiVaultRequest, Error> {
let auth_type: NmiAuthType = connector_auth_type.try_into()?;
let (ccnumber, ccexp, cvv) = get_card_details(payment_method_data)?;
let billing_details = billing_address?;
let first_name = billing_details.get_first_name()?;
Ok(NmiVaultRequest {
security_key: auth_type.api_key,
ccnumber,
ccexp,
cvv,
first_name: first_name.clone(),
last_name: billing_details
.get_last_name()
.unwrap_or(first_name)
.clone(),
address1: billing_details.line1.clone(),
address2: billing_details.line2.clone(),
city: billing_details.city.clone(),
state: billing_details.state.clone(),
country: billing_details.country,
zip: billing_details.zip.clone(),
customer_vault: CustomerAction::AddCustomer,
})
}
// Marker trait: only implemented for the allowed RouterData types
impl TryFrom<&PaymentsPreProcessingRouterData> for NmiVaultRequest {
type Error = Error;
fn try_from(item: &PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> {
try_build_nmi_vault_request_from_router_data(
&item.connector_auth_type,
item.request.payment_method_data.clone(),
item.get_billing_address(),
)
}
}
impl TryFrom<&PaymentsPreAuthenticateRouterData> for NmiVaultRequest {
type Error = Error;
fn try_from(item: &PaymentsPreAuthenticateRouterData) -> Result<Self, Self::Error> {
try_build_nmi_vault_request_from_router_data(
&item.connector_auth_type,
Some(item.request.payment_method_data.clone()),
item.get_billing_address(),
)
}
}
fn get_card_details(
payment_method_data: Option<PaymentMethodData>,
) -> CustomResult<(CardNumber, Secret<String>, Secret<String>), ConnectorError> {
match payment_method_data {
Some(PaymentMethodData::Card(ref card_details)) => Ok((
card_details.card_number.clone(),
card_details.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?,
card_details.card_cvc.clone(),
)),
_ => Err(
ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message("Nmi"))
.into(),
),
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NmiVaultResponse {
pub response: Response,
pub responsetext: String,
pub customer_vault_id: Option<Secret<String>>,
pub response_code: String,
pub transactionid: String,
}
fn process_nmi_vault_response(
connector_auth_type: &ConnectorAuthType,
amount: Option<i64>,
currency: Option<Currency>,
vault_response: &NmiVaultResponse,
http_code: u16,
connector_request_reference_id: String,
) -> Result<(Result<PaymentsResponseData, ErrorResponse>, AttemptStatus), Error> {
let auth_type: NmiAuthType = connector_auth_type.try_into()?;
let amount_data = amount.ok_or(ConnectorError::MissingRequiredField {
field_name: "amount",
})?;
let currency_data = currency.ok_or(ConnectorError::MissingRequiredField {
field_name: "currency",
})?;
build_nmi_vault_response(
auth_type,
amount_data,
currency_data,
vault_response,
http_code,
connector_request_reference_id,
)
}
fn build_nmi_vault_response(
auth_type: NmiAuthType,
amount_data: i64,
currency_data: Currency,
vault_response: &NmiVaultResponse,
http_code: u16,
connector_request_reference_id: String,
) -> Result<(Result<PaymentsResponseData, ErrorResponse>, AttemptStatus), Error> {
let (response, status) = match vault_response.response {
Response::Approved => (
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::Nmi {
amount: to_currency_base_unit_asf64(amount_data, currency_data.to_owned())?
.to_string(),
currency: currency_data,
customer_vault_id: vault_response
.customer_vault_id
.clone()
.ok_or(ConnectorError::MissingRequiredField {
field_name: "customer_vault_id",
})?
.peek()
.to_string(),
public_key: auth_type.public_key.ok_or(
ConnectorError::InvalidConnectorConfig {
config: "public_key",
},
)?,
order_id: connector_request_reference_id.clone(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(vault_response.transactionid.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
AttemptStatus::AuthenticationPending,
),
Response::Declined | Response::Error => (
Err(ErrorResponse {
code: vault_response.response_code.clone(),
message: vault_response.responsetext.to_owned(),
reason: Some(vault_response.responsetext.clone()),
status_code: http_code,
attempt_status: None,
connector_transaction_id: Some(vault_response.transactionid.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
AttemptStatus::Failure,
),
};
Ok((response, status))
}
impl TryFrom<PaymentsPreprocessingResponseRouterData<NmiVaultResponse>>
for PaymentsPreProcessingRouterData
{
type Error = Error;
fn try_from(
item: PaymentsPreprocessingResponseRouterData<NmiVaultResponse>,
) -> Result<Self, Self::Error> {
let (response, status) = process_nmi_vault_response(
&item.data.connector_auth_type,
item.data.request.amount,
item.data.request.currency,
&item.response,
item.http_code,
item.data.connector_request_reference_id.clone(),
)?;
Ok(Self {
status,
response,
..item.data
})
}
}
impl TryFrom<PaymentsPreAuthenticateResponseRouterData<NmiVaultResponse>>
for PaymentsPreAuthenticateRouterData
{
type Error = Error;
fn try_from(
item: PaymentsPreAuthenticateResponseRouterData<NmiVaultResponse>,
) -> Result<Self, Self::Error> {
let (response, status) = process_nmi_vault_response(
&item.data.connector_auth_type,
Some(item.data.request.amount),
item.data.request.currency,
&item.response,
item.http_code,
item.data.connector_request_reference_id.clone(),
)?;
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct NmiCompleteRequest {
amount: FloatMajorUnit,
#[serde(rename = "type")]
transaction_type: TransactionType,
security_key: Secret<String>,
orderid: Option<String>,
customer_vault_id: Secret<String>,
email: Option<Email>,
cardholder_auth: Option<String>,
cavv: Option<String>,
xid: Option<String>,
eci: Option<String>,
cvv: Secret<String>,
three_ds_version: Option<String>,
directory_server_id: Option<Secret<String>>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum NmiRedirectResponse {
NmiRedirectResponseData(NmiRedirectResponseData),
NmiErrorResponseData(NmiErrorResponseData),
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NmiErrorResponseData {
pub code: String,
pub message: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NmiRedirectResponseData {
cavv: Option<String>,
xid: Option<String>,
eci: Option<String>,
card_holder_auth: Option<String>,
three_ds_version: Option<String>,
order_id: Option<String>,
directory_server_id: Option<Secret<String>>,
customer_vault_id: Secret<String>,
}
impl TryFrom<&NmiRouterData<&PaymentsCompleteAuthorizeRouterData>> for NmiCompleteRequest {
type Error = Error;
fn try_from(
item: &NmiRouterData<&PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let transaction_type = match item.router_data.request.is_auto_capture()? {
true => TransactionType::Sale,
false => TransactionType::Auth,
};
let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?;
let payload_data = item
.router_data
.request
.get_redirect_response_payload()?
.expose();
let three_ds_data: NmiRedirectResponseData = serde_json::from_value(payload_data)
.change_context(ConnectorError::MissingConnectorRedirectionPayload {
field_name: "three_ds_data",
})?;
let (_, _, cvv) = get_card_details(item.router_data.request.payment_method_data.clone())?;
Ok(Self {
amount: item.amount,
transaction_type,
security_key: auth_type.api_key,
orderid: three_ds_data.order_id,
customer_vault_id: three_ds_data.customer_vault_id,
email: item.router_data.request.email.clone(),
cvv,
cardholder_auth: three_ds_data.card_holder_auth,
cavv: three_ds_data.cavv,
xid: three_ds_data.xid,
eci: three_ds_data.eci,
three_ds_version: three_ds_data.three_ds_version,
directory_server_id: three_ds_data.directory_server_id,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NmiCompleteResponse {
pub response: Response,
pub responsetext: String,
pub authcode: Option<String>,
pub transactionid: String,
pub avsresponse: Option<String>,
pub cvvresponse: Option<String>,
pub orderid: String,
pub response_code: String,
customer_vault_id: Option<Secret<String>>,
}
impl
TryFrom<
ResponseRouterData<
CompleteAuthorize,
NmiCompleteResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
> for PaymentsCompleteAuthorizeRouterData
{
type Error = Error;
fn try_from(
item: ResponseRouterData<
CompleteAuthorize,
NmiCompleteResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let (response, status) = match item.response.response {
Response::Approved => (
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.transactionid),
redirection_data: Box::new(None),
mandate_reference: match item.response.customer_vault_id {
Some(vault_id) => Box::new(Some(
hyperswitch_domain_models::router_response_types::MandateReference {
connector_mandate_id: Some(vault_id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
},
)),
None => Box::new(None),
},
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
incremental_authorization_allowed: None,
charges: None,
}),
if item.data.request.is_auto_capture()? {
AttemptStatus::Charged
} else {
AttemptStatus::Authorized
},
),
Response::Declined | Response::Error => (
Err(get_nmi_error_response(item.response, item.http_code)),
AttemptStatus::Failure,
),
};
Ok(Self {
status,
response,
..item.data
})
}
}
fn get_nmi_error_response(response: NmiCompleteResponse, http_code: u16) -> ErrorResponse {
ErrorResponse {
code: response.response_code,
message: response.responsetext.to_owned(),
reason: Some(response.responsetext),
status_code: http_code,
attempt_status: None,
connector_transaction_id: Some(response.transactionid),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
#[derive(Debug, Serialize)]
pub struct NmiValidateRequest {
#[serde(rename = "type")]
transaction_type: TransactionType,
security_key: Secret<String>,
#[serde(flatten)]
payment_data: NmiValidatePaymentData,
orderid: String,
customer_vault: CustomerAction,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum NmiValidatePaymentData {
ApplePayDecrypt(Box<ApplePayDecryptedData>),
ApplePay(Box<ApplePayData>),
Card(Box<CardData>),
}
#[derive(Debug, Serialize)]
pub struct NmiPaymentsRequest {
#[serde(rename = "type")]
transaction_type: TransactionType,
amount: FloatMajorUnit,
security_key: Secret<String>,
currency: Currency,
#[serde(flatten)]
payment_method: PaymentMethod,
#[serde(flatten)]
merchant_defined_field: Option<NmiMerchantDefinedField>,
orderid: String,
#[serde(skip_serializing_if = "Option::is_none")]
customer_vault: Option<CustomerAction>,
}
#[derive(Debug, Serialize)]
pub struct NmiMerchantDefinedField {
#[serde(flatten)]
inner: std::collections::BTreeMap<String, Secret<String>>,
}
impl NmiMerchantDefinedField {
pub fn new(metadata: &serde_json::Value) -> Self {
let metadata_as_string = metadata.to_string();
let hash_map: std::collections::BTreeMap<String, serde_json::Value> =
serde_json::from_str(&metadata_as_string).unwrap_or(std::collections::BTreeMap::new());
let inner = hash_map
.into_iter()
.enumerate()
.map(|(index, (hs_key, hs_value))| {
let nmi_key = format!("merchant_defined_field_{}", index + 1);
let val = match hs_value {
serde_json::Value::Bool(boolean) => boolean.to_string(),
serde_json::Value::Number(number) => number.to_string(),
serde_json::Value::String(string) => string.to_string(),
_ => hs_value.to_string(),
};
let nmi_value = format!("{hs_key}={val}");
(nmi_key, Secret::new(nmi_value))
})
.collect();
Self { inner }
}
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymentMethod {
CardNonThreeDs(Box<CardData>),
CardThreeDs(Box<CardThreeDsData>),
GPay(Box<GooglePayData>),
ApplePay(Box<ApplePayData>),
MandatePayment(Box<MandatePayment>),
ApplePayDecrypt(Box<ApplePayDecryptedData>),
}
#[derive(Debug, Serialize)]
pub struct MandatePayment {
customer_vault_id: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct CardData {
ccnumber: CardNumber,
ccexp: Secret<String>,
cvv: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct CardThreeDsData {
ccnumber: CardNumber,
ccexp: Secret<String>,
email: Option<Email>,
cardholder_auth: Option<String>,
cavv: Option<Secret<String>>,
eci: Option<String>,
cvv: Secret<String>,
three_ds_version: Option<String>,
directory_server_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct GooglePayData {
googlepay_payment_data: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct ApplePayData {
applepay_payment_data: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct ApplePayDecryptedData {
decrypted_applepay_data: String,
ccnumber: CardNumber,
ccexp: Secret<String>,
cavv: Secret<String>,
eci: Option<String>,
}
impl TryFrom<&NmiRouterData<&PaymentsAuthorizeRouterData>> for NmiPaymentsRequest {
type Error = Error;
fn try_from(item: &NmiRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
let transaction_type = match item.router_data.request.is_auto_capture()? {
true => TransactionType::Sale,
false => TransactionType::Auth,
};
let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?;
let amount = item.amount;
match item
.router_data
.request
.mandate_id
.clone()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id)
{
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_id,
)) => Ok(Self {
transaction_type,
security_key: auth_type.api_key,
amount,
currency: item.router_data.request.currency,
payment_method: PaymentMethod::MandatePayment(Box::new(MandatePayment {
customer_vault_id: Secret::new(
connector_mandate_id
.get_connector_mandate_id()
.ok_or(ConnectorError::MissingConnectorMandateID)?,
),
})),
merchant_defined_field: item
.router_data
.request
.metadata
.as_ref()
.map(NmiMerchantDefinedField::new),
orderid: item.router_data.connector_request_reference_id.clone(),
customer_vault: None,
}),
Some(api_models::payments::MandateReferenceId::NetworkMandateId(_))
| Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_)) => {
Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("nmi"),
))?
}
None => {
let payment_method = PaymentMethod::try_from((
&item.router_data.request.payment_method_data,
Some(item.router_data),
))?;
Ok(Self {
transaction_type,
security_key: auth_type.api_key,
amount,
currency: item.router_data.request.currency,
payment_method,
merchant_defined_field: item
.router_data
.request
.metadata
.as_ref()
.map(NmiMerchantDefinedField::new),
orderid: item.router_data.connector_request_reference_id.clone(),
customer_vault: item
.router_data
.request
.is_mandate_payment()
.then_some(CustomerAction::AddCustomer),
})
}
}
}
}
impl TryFrom<(&PaymentMethodData, Option<&PaymentsAuthorizeRouterData>)> for PaymentMethod {
type Error = Error;
fn try_from(
item: (&PaymentMethodData, Option<&PaymentsAuthorizeRouterData>),
) -> Result<Self, Self::Error> {
let (payment_method_data, router_data) = item;
match payment_method_data {
PaymentMethodData::Card(ref card) => match router_data {
Some(data) => match data.auth_type {
AuthenticationType::NoThreeDs => Ok(Self::try_from(card)?),
AuthenticationType::ThreeDs => Ok(Self::try_from((card, &data.request))?),
},
None => Ok(Self::try_from(card)?),
},
PaymentMethodData::Wallet(ref wallet_type) => match wallet_type {
WalletData::GooglePay(ref googlepay_data) => Ok(Self::try_from(googlepay_data)?),
WalletData::ApplePay(ref applepay_data) => {
let payment_method_token =
router_data.and_then(|data| data.payment_method_token.clone());
Ok(Self::try_from((applepay_data, payment_method_token))?)
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::AmazonPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(report!(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("nmi"),
))),
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => Err(
ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message(
"nmi",
))
.into(),
),
}
}
}
impl TryFrom<(&Card, &PaymentsAuthorizeData)> for PaymentMethod {
type Error = Error;
fn try_from(val: (&Card, &PaymentsAuthorizeData)) -> Result<Self, Self::Error> {
let (card_data, item) = val;
let auth_data = &item.get_authentication_data()?;
let ccexp = card_data.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?;
let card_3ds_details = CardThreeDsData {
ccnumber: card_data.card_number.clone(),
ccexp,
cvv: card_data.card_cvc.clone(),
email: item.email.clone(),
cavv: Some(auth_data.cavv.clone()),
eci: auth_data.eci.clone(),
cardholder_auth: None,
three_ds_version: auth_data
.message_version
.clone()
.map(|version| version.to_string()),
directory_server_id: auth_data
.threeds_server_transaction_id
.clone()
.map(Secret::new),
};
Ok(Self::CardThreeDs(Box::new(card_3ds_details)))
}
}
impl TryFrom<&Card> for PaymentMethod {
type Error = Error;
fn try_from(card: &Card) -> Result<Self, Self::Error> {
let ccexp = card.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?;
let card = CardData {
ccnumber: card.card_number.clone(),
ccexp,
cvv: card.card_cvc.clone(),
};
Ok(Self::CardNonThreeDs(Box::new(card)))
}
}
impl TryFrom<&GooglePayWalletData> for PaymentMethod {
type Error = Report<ConnectorError>;
fn try_from(wallet_data: &GooglePayWalletData) -> Result<Self, Self::Error> {
let gpay_data = GooglePayData {
googlepay_payment_data: Secret::new(
wallet_data
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?
.clone(),
),
};
Ok(Self::GPay(Box::new(gpay_data)))
}
}
impl TryFrom<(&ApplePayWalletData, Option<PaymentMethodToken>)> for PaymentMethod {
type Error = Error;
fn try_from(
(apple_pay_wallet_data, payment_method_token): (
&ApplePayWalletData,
Option<PaymentMethodToken>,
),
) -> Result<Self, Self::Error> {
match payment_method_token {
Some(payment_method_token) => match payment_method_token {
PaymentMethodToken::ApplePayDecrypt(apple_pay_decrypt_data) => {
Ok(Self::ApplePayDecrypt(Box::new(ApplePayDecryptedData {
decrypted_applepay_data: "1".to_string(), // Set to "1" to indicate decrypted data is being sent
ccnumber: apple_pay_decrypt_data
.application_primary_account_number
.clone(),
ccexp: apple_pay_decrypt_data
.get_expiry_date_as_mmyy()
.change_context(ConnectorError::InvalidDataFormat {
field_name: "application_expiration_date",
})?,
cavv: apple_pay_decrypt_data
.payment_data
.online_payment_cryptogram
.clone(),
eci: apple_pay_decrypt_data.payment_data.eci_indicator.clone(),
})))
}
PaymentMethodToken::Token(_) => {
Err(unimplemented_payment_method!("Apple Pay", "Manual", "NMI"))?
}
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "NMI"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "NMI"))?
}
},
None => {
let apple_pay_encrypted_data = apple_pay_wallet_data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
let base64_decoded_apple_pay_data = base64::prelude::BASE64_STANDARD
.decode(apple_pay_encrypted_data)
.change_context(ConnectorError::InvalidDataFormat {
field_name: "apple_pay_encrypted_data",
})?;
let hex_encoded_apple_pay_data = hex::encode(base64_decoded_apple_pay_data);
let apple_pay_data = ApplePayData {
applepay_payment_data: Secret::new(hex_encoded_apple_pay_data),
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs | crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs | use std::collections::HashMap;
use api_models::payments;
use cards::CardNumber;
use common_enums::{enums, BankNames, CaptureMethod, Currency};
use common_types::payments::ApplePayPredecryptData;
use common_utils::{
crypto::{self, GenerateDigest},
errors::CustomResult,
ext_traits::Encode,
pii::Email,
request::Method,
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{Report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::{
BankRedirectData, Card, CardDetailsForNetworkTransactionId, GooglePayWalletData,
PaymentMethodData, RealTimePaymentData, WalletData,
},
router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use strum::Display;
use url::Url;
// These needs to be accepted from SDK, need to be done after 1.0.0 stability as API contract will change
const GOOGLEPAY_API_VERSION_MINOR: u8 = 0;
const GOOGLEPAY_API_VERSION: u8 = 2;
use crate::{
constants,
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
},
unimplemented_payment_method,
utils::{self, PaymentsAuthorizeRequestData, QrImage, RefundsRequestData, RouterData as _},
};
pub struct FiuuRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for FiuuRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub struct FiuuAuthType {
pub(super) merchant_id: Secret<String>,
pub(super) verify_key: Secret<String>,
pub(super) secret_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for FiuuAuthType {
type Error = Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
merchant_id: key1.to_owned(),
verify_key: api_key.to_owned(),
secret_key: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum TxnType {
Sals,
Auts,
}
impl TryFrom<Option<CaptureMethod>> for TxnType {
type Error = Report<errors::ConnectorError>;
fn try_from(capture_method: Option<CaptureMethod>) -> Result<Self, Self::Error> {
match capture_method {
Some(CaptureMethod::Automatic) | Some(CaptureMethod::SequentialAutomatic) | None => {
Ok(Self::Sals)
}
Some(CaptureMethod::Manual) => Ok(Self::Auts),
_ => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
}
#[derive(Serialize, Deserialize, Display, Debug, Clone)]
enum TxnChannel {
#[serde(rename = "CREDITAN")]
#[strum(serialize = "CREDITAN")]
Creditan,
#[serde(rename = "RPP_DUITNOWQR")]
#[strum(serialize = "RPP_DUITNOWQR")]
RppDuitNowQr,
}
#[derive(Serialize, Deserialize, Display, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
pub enum FPXTxnChannel {
FpxAbb,
FpxUob,
FpxAbmb,
FpxScb,
FpxBsn,
FpxKfh,
FpxBmmb,
FpxBkrm,
FpxHsbc,
FpxAgrobank,
FpxBocm,
FpxMb2u,
FpxCimbclicks,
FpxAmb,
FpxHlb,
FpxPbb,
FpxRhb,
FpxBimb,
FpxOcbc,
}
#[derive(Debug, Clone, Serialize)]
pub enum BankCode {
PHBMMYKL,
AGOBMYK1,
MFBBMYKL,
ARBKMYKL,
BKCHMYKL,
BIMBMYKL,
BMMBMYKL,
BKRMMYK1,
BSNAMYK1,
CIBBMYKL,
HLBBMYKL,
HBMBMYKL,
KFHOMYKL,
MBBEMYKL,
PBBEMYKL,
RHBBMYKL,
SCBLMYKX,
UOVBMYKL,
OCBCMYKL,
}
impl TryFrom<BankNames> for BankCode {
type Error = Report<errors::ConnectorError>;
fn try_from(bank: BankNames) -> Result<Self, Self::Error> {
match bank {
BankNames::AffinBank => Ok(Self::PHBMMYKL),
BankNames::AgroBank => Ok(Self::AGOBMYK1),
BankNames::AllianceBank => Ok(Self::MFBBMYKL),
BankNames::AmBank => Ok(Self::ARBKMYKL),
BankNames::BankOfChina => Ok(Self::BKCHMYKL),
BankNames::BankIslam => Ok(Self::BIMBMYKL),
BankNames::BankMuamalat => Ok(Self::BMMBMYKL),
BankNames::BankRakyat => Ok(Self::BKRMMYK1),
BankNames::BankSimpananNasional => Ok(Self::BSNAMYK1),
BankNames::CimbBank => Ok(Self::CIBBMYKL),
BankNames::HongLeongBank => Ok(Self::HLBBMYKL),
BankNames::HsbcBank => Ok(Self::HBMBMYKL),
BankNames::KuwaitFinanceHouse => Ok(Self::KFHOMYKL),
BankNames::Maybank => Ok(Self::MBBEMYKL),
BankNames::PublicBank => Ok(Self::PBBEMYKL),
BankNames::RhbBank => Ok(Self::RHBBMYKL),
BankNames::StandardCharteredBank => Ok(Self::SCBLMYKX),
BankNames::UobBank => Ok(Self::UOVBMYKL),
BankNames::OcbcBank => Ok(Self::OCBCMYKL),
bank => Err(errors::ConnectorError::NotSupported {
message: format!("Invalid BankName for FPX Refund: {bank:?}"),
connector: "Fiuu",
})?,
}
}
}
impl TryFrom<BankNames> for FPXTxnChannel {
type Error = Report<errors::ConnectorError>;
fn try_from(bank_names: BankNames) -> Result<Self, Self::Error> {
match bank_names {
BankNames::AffinBank => Ok(Self::FpxAbb),
BankNames::AgroBank => Ok(Self::FpxAgrobank),
BankNames::AllianceBank => Ok(Self::FpxAbmb),
BankNames::AmBank => Ok(Self::FpxAmb),
BankNames::BankOfChina => Ok(Self::FpxBocm),
BankNames::BankIslam => Ok(Self::FpxBimb),
BankNames::BankMuamalat => Ok(Self::FpxBmmb),
BankNames::BankRakyat => Ok(Self::FpxBkrm),
BankNames::BankSimpananNasional => Ok(Self::FpxBsn),
BankNames::CimbBank => Ok(Self::FpxCimbclicks),
BankNames::HongLeongBank => Ok(Self::FpxHlb),
BankNames::HsbcBank => Ok(Self::FpxHsbc),
BankNames::KuwaitFinanceHouse => Ok(Self::FpxKfh),
BankNames::Maybank => Ok(Self::FpxMb2u),
BankNames::PublicBank => Ok(Self::FpxPbb),
BankNames::RhbBank => Ok(Self::FpxRhb),
BankNames::StandardCharteredBank => Ok(Self::FpxScb),
BankNames::UobBank => Ok(Self::FpxUob),
BankNames::OcbcBank => Ok(Self::FpxOcbc),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Fiuu"),
))?,
}
}
}
#[derive(Serialize, Debug, Clone)]
pub struct FiuuMandateRequest {
#[serde(rename = "0")]
mandate_request: Secret<String>,
}
#[derive(Serialize, Debug, Clone)]
pub struct FiuuRecurringRequest {
record_type: FiuuRecordType,
merchant_id: Secret<String>,
token: Secret<String>,
order_id: String,
currency: Currency,
amount: StringMajorUnit,
billing_name: Secret<String>,
email: Email,
verify_key: Secret<String>,
}
#[derive(Serialize, Debug, Clone, strum::Display)]
pub enum FiuuRecordType {
T,
}
impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuMandateRequest {
type Error = Report<errors::ConnectorError>;
fn try_from(item: &FiuuRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
let auth: FiuuAuthType = FiuuAuthType::try_from(&item.router_data.connector_auth_type)?;
let record_type = FiuuRecordType::T;
let merchant_id = auth.merchant_id;
let order_id = item.router_data.connector_request_reference_id.clone();
let currency = item.router_data.request.currency;
let amount = item.amount.clone();
let billing_name = item
.router_data
.request
.get_card_holder_name_from_additional_payment_method_data()?;
let email = item.router_data.get_billing_email()?;
let token = Secret::new(item.router_data.request.get_connector_mandate_id()?);
let verify_key = auth.verify_key;
let recurring_request = FiuuRecurringRequest {
record_type: record_type.clone(),
merchant_id: merchant_id.clone(),
token: token.clone(),
order_id: order_id.clone(),
currency,
amount: amount.clone(),
billing_name: billing_name.clone(),
email: email.clone(),
verify_key: verify_key.clone(),
};
let check_sum = calculate_check_sum(recurring_request)?;
let mandate_request = format!(
"{}|{}||{}|{}|{}|{}|{}|{}|||{}",
record_type,
merchant_id.peek(),
token.peek(),
order_id,
currency,
amount.get_amount_as_string(),
billing_name.peek(),
email.peek(),
check_sum.peek()
);
Ok(Self {
mandate_request: mandate_request.into(),
})
}
}
pub fn calculate_check_sum(
req: FiuuRecurringRequest,
) -> CustomResult<Secret<String>, errors::ConnectorError> {
let formatted_string = format!(
"{}{}{}{}{}{}{}",
req.record_type,
req.merchant_id.peek(),
req.token.peek(),
req.order_id,
req.currency,
req.amount.get_amount_as_string(),
req.verify_key.peek()
);
Ok(Secret::new(hex::encode(
crypto::Md5
.generate_digest(formatted_string.as_bytes())
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
)))
}
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuPaymentRequest {
#[serde(rename = "MerchantID")]
merchant_id: Secret<String>,
reference_no: String,
txn_type: TxnType,
txn_currency: Currency,
txn_amount: StringMajorUnit,
signature: Secret<String>,
#[serde(rename = "ReturnURL")]
return_url: Option<String>,
#[serde(rename = "NotificationURL")]
notification_url: Option<Url>,
#[serde(flatten)]
payment_method_data: FiuuPaymentMethodData,
}
#[derive(Serialize, Debug, Clone)]
#[serde(untagged)]
pub enum FiuuPaymentMethodData {
FiuuQRData(Box<FiuuQRData>),
FiuuCardData(Box<FiuuCardData>),
FiuuCardWithNTI(Box<FiuuCardWithNTI>),
FiuuFpxData(Box<FiuuFPXData>),
FiuuGooglePayData(Box<FiuuGooglePayData>),
FiuuApplePayData(Box<FiuuApplePayData>),
}
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuFPXData {
#[serde(rename = "non_3DS")]
non_3ds: i32,
txn_channel: FPXTxnChannel,
}
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuQRData {
txn_channel: TxnChannel,
}
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct FiuuCardData {
#[serde(rename = "non_3DS")]
non_3ds: i32,
#[serde(rename = "TxnChannel")]
txn_channel: TxnChannel,
cc_pan: CardNumber,
cc_cvv2: Secret<String>,
cc_month: Secret<String>,
cc_year: Secret<String>,
#[serde(rename = "mpstokenstatus")]
mps_token_status: Option<i32>,
#[serde(rename = "CustEmail")]
customer_email: Option<Email>,
}
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct FiuuCardWithNTI {
#[serde(rename = "TxnChannel")]
txn_channel: TxnChannel,
cc_pan: CardNumber,
cc_month: Secret<String>,
cc_year: Secret<String>,
#[serde(rename = "OriginalSchemeID")]
original_scheme_id: Secret<String>,
}
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct FiuuApplePayData {
#[serde(rename = "TxnChannel")]
txn_channel: TxnChannel,
cc_month: Secret<String>,
cc_year: Secret<String>,
cc_token: CardNumber,
eci: Option<String>,
token_cryptogram: Secret<String>,
token_type: FiuuTokenType,
#[serde(rename = "non_3DS")]
non_3ds: i32,
}
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "PascalCase")]
pub enum FiuuTokenType {
ApplePay,
GooglePay,
}
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct FiuuGooglePayData {
txn_channel: TxnChannel,
#[serde(rename = "GooglePay[apiVersion]")]
api_version: u8,
#[serde(rename = "GooglePay[apiVersionMinor]")]
api_version_minor: u8,
#[serde(rename = "GooglePay[paymentMethodData][info][assuranceDetails][accountVerified]")]
account_verified: Option<bool>,
#[serde(
rename = "GooglePay[paymentMethodData][info][assuranceDetails][cardHolderAuthenticated]"
)]
card_holder_authenticated: Option<bool>,
#[serde(rename = "GooglePay[paymentMethodData][info][cardDetails]")]
card_details: String,
#[serde(rename = "GooglePay[paymentMethodData][info][cardNetwork]")]
card_network: String,
#[serde(rename = "GooglePay[paymentMethodData][tokenizationData][token]")]
token: Secret<String>,
#[serde(rename = "GooglePay[paymentMethodData][tokenizationData][type]")]
tokenization_data_type: Secret<String>,
#[serde(rename = "GooglePay[paymentMethodData][type]")]
pm_type: String,
#[serde(rename = "SCREAMING_SNAKE_CASE")]
token_type: FiuuTokenType,
#[serde(rename = "non_3DS")]
non_3ds: i32,
}
pub fn calculate_signature(
signature_data: String,
) -> Result<Secret<String>, Report<errors::ConnectorError>> {
let message = signature_data.as_bytes();
let encoded_data = hex::encode(
crypto::Md5
.generate_digest(message)
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
);
Ok(Secret::new(encoded_data))
}
impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuPaymentRequest {
type Error = Report<errors::ConnectorError>;
fn try_from(item: &FiuuRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
let auth = FiuuAuthType::try_from(&item.router_data.connector_auth_type)?;
let merchant_id = auth.merchant_id.peek().to_string();
let txn_currency = item.router_data.request.currency;
let txn_amount = item.amount.clone();
let reference_no = item.router_data.connector_request_reference_id.clone();
let verify_key = auth.verify_key.peek().to_string();
let signature = calculate_signature(format!(
"{}{merchant_id}{reference_no}{verify_key}",
txn_amount.get_amount_as_string()
))?;
let txn_type = match item.router_data.request.is_auto_capture()? {
true => TxnType::Sals,
false => TxnType::Auts,
};
let return_url = item.router_data.request.router_return_url.clone();
let non_3ds = match item.router_data.is_three_ds() {
false => 1,
true => 0,
};
let notification_url = Some(
Url::parse(&item.router_data.request.get_webhook_url()?)
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
);
let payment_method_data = match item
.router_data
.request
.mandate_id
.clone()
.and_then(|mandate_id| mandate_id.mandate_reference_id)
{
None => match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref card) => {
FiuuPaymentMethodData::try_from((card, item.router_data))
}
PaymentMethodData::RealTimePayment(ref real_time_payment_data) => {
match *real_time_payment_data.clone() {
RealTimePaymentData::DuitNow {} => {
Ok(FiuuPaymentMethodData::FiuuQRData(Box::new(FiuuQRData {
txn_channel: TxnChannel::RppDuitNowQr,
})))
}
RealTimePaymentData::Fps {}
| RealTimePaymentData::PromptPay {}
| RealTimePaymentData::VietQr {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiuu"),
)
.into())
}
}
}
PaymentMethodData::BankRedirect(ref bank_redirect_data) => match bank_redirect_data
{
BankRedirectData::OnlineBankingFpx { ref issuer } => {
Ok(FiuuPaymentMethodData::FiuuFpxData(Box::new(FiuuFPXData {
txn_channel: FPXTxnChannel::try_from(*issuer)?,
non_3ds,
})))
}
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Bizum {}
| BankRedirectData::Blik { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Eps { .. }
| BankRedirectData::Giropay { .. }
| BankRedirectData::Ideal { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::Sofort { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {}
| BankRedirectData::OpenBanking { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiuu"),
)
.into())
}
},
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletData::GooglePay(google_pay_data) => {
FiuuPaymentMethodData::try_from(google_pay_data)
}
WalletData::ApplePay(_apple_pay_data) => {
let payment_method_token = item.router_data.get_payment_method_token()?;
match payment_method_token {
PaymentMethodToken::Token(_) => {
Err(unimplemented_payment_method!("Apple Pay", "Manual", "Fiuu"))?
}
PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
FiuuPaymentMethodData::try_from(decrypt_data)
}
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Fiuu"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Fiuu"))?
}
}
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiuu"),
)
.into()),
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Reward
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiuu"),
)
.into())
}
},
// Card payments using network transaction ID
Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => {
match item.router_data.request.payment_method_data {
PaymentMethodData::CardDetailsForNetworkTransactionId(ref raw_card_details) => {
FiuuPaymentMethodData::try_from((raw_card_details, network_transaction_id))
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiuu"),
)
.into()),
}
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiuu"),
)
.into()),
}?;
Ok(Self {
merchant_id: auth.merchant_id,
reference_no,
txn_type,
txn_currency,
txn_amount,
return_url,
payment_method_data,
signature,
notification_url,
})
}
}
impl TryFrom<(&Card, &PaymentsAuthorizeRouterData)> for FiuuPaymentMethodData {
type Error = Report<errors::ConnectorError>;
fn try_from(
(req_card, item): (&Card, &PaymentsAuthorizeRouterData),
) -> Result<Self, Self::Error> {
let (mps_token_status, customer_email) =
if item.request.is_customer_initiated_mandate_payment() {
(Some(1), Some(item.get_billing_email()?))
} else {
(Some(3), None)
};
let non_3ds = match item.is_three_ds() {
false => 1,
true => 0,
};
Ok(Self::FiuuCardData(Box::new(FiuuCardData {
txn_channel: TxnChannel::Creditan,
non_3ds,
cc_pan: req_card.card_number.clone(),
cc_cvv2: req_card.card_cvc.clone(),
cc_month: req_card.card_exp_month.clone(),
cc_year: req_card.card_exp_year.clone(),
mps_token_status,
customer_email,
})))
}
}
impl TryFrom<(&CardDetailsForNetworkTransactionId, String)> for FiuuPaymentMethodData {
type Error = Report<errors::ConnectorError>;
fn try_from(
(raw_card_data, network_transaction_id): (&CardDetailsForNetworkTransactionId, String),
) -> Result<Self, Self::Error> {
Ok(Self::FiuuCardWithNTI(Box::new(FiuuCardWithNTI {
txn_channel: TxnChannel::Creditan,
cc_pan: raw_card_data.card_number.clone(),
cc_month: raw_card_data.card_exp_month.clone(),
cc_year: raw_card_data.card_exp_year.clone(),
original_scheme_id: Secret::new(network_transaction_id),
})))
}
}
impl TryFrom<&GooglePayWalletData> for FiuuPaymentMethodData {
type Error = Report<errors::ConnectorError>;
fn try_from(data: &GooglePayWalletData) -> Result<Self, Self::Error> {
Ok(Self::FiuuGooglePayData(Box::new(FiuuGooglePayData {
txn_channel: TxnChannel::Creditan,
api_version: GOOGLEPAY_API_VERSION,
api_version_minor: GOOGLEPAY_API_VERSION_MINOR,
account_verified: data
.info
.assurance_details
.as_ref()
.map(|details| details.account_verified),
card_holder_authenticated: data
.info
.assurance_details
.as_ref()
.map(|details| details.card_holder_authenticated),
card_details: data.info.card_details.clone(),
card_network: data.info.card_network.clone(),
token: data
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?
.clone()
.into(),
tokenization_data_type: data
.tokenization_data
.get_encrypted_token_type()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet token type",
})?
.clone()
.into(),
pm_type: data.pm_type.clone(),
token_type: FiuuTokenType::GooglePay,
// non_3ds field Applicable to card processing via specific processor using specific currency for pre-approved partner only.
// Equal to 0 by default and 1 for non-3DS transaction, That is why it is hardcoded to 1 for googlepay transactions.
non_3ds: 1,
})))
}
}
impl TryFrom<Box<ApplePayPredecryptData>> for FiuuPaymentMethodData {
type Error = Report<errors::ConnectorError>;
fn try_from(decrypt_data: Box<ApplePayPredecryptData>) -> Result<Self, Self::Error> {
Ok(Self::FiuuApplePayData(Box::new(FiuuApplePayData {
txn_channel: TxnChannel::Creditan,
cc_month: decrypt_data.get_expiry_month().change_context(
errors::ConnectorError::InvalidDataFormat {
field_name: "expiration_month",
},
)?,
cc_year: decrypt_data.get_four_digit_expiry_year(),
cc_token: decrypt_data.application_primary_account_number,
eci: decrypt_data.payment_data.eci_indicator,
token_cryptogram: decrypt_data.payment_data.online_payment_cryptogram,
token_type: FiuuTokenType::ApplePay,
// non_3ds field Applicable to card processing via specific processor using specific currency for pre-approved partner only.
// Equal to 0 by default and 1 for non-3DS transaction, That is why it is hardcoded to 1 for apple pay decrypt flow transactions.
non_3ds: 1,
})))
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PaymentsResponse {
pub reference_no: String,
#[serde(rename = "TxnID")]
pub txn_id: String,
pub txn_type: TxnType,
pub txn_currency: Currency,
pub txn_amount: StringMajorUnit,
pub txn_channel: String,
pub txn_data: TxnData,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct DuitNowQrCodeResponse {
pub reference_no: String,
pub txn_type: TxnType,
pub txn_currency: Currency,
pub txn_amount: StringMajorUnit,
pub txn_channel: String,
#[serde(rename = "TxnID")]
pub txn_id: String,
pub txn_data: QrTxnData,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct QrTxnData {
pub request_data: QrRequestData,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct QrRequestData {
pub qr_data: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FiuuPaymentsResponse {
PaymentResponse(Box<PaymentsResponse>),
QRPaymentResponse(Box<DuitNowQrCodeResponse>),
Error(FiuuErrorResponse),
RecurringResponse(Vec<Box<FiuuRecurringResponse>>),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FiuuRecurringResponse {
status: FiuuRecurringStautus,
#[serde(rename = "orderid")]
order_id: String,
#[serde(rename = "tranID")]
tran_id: Option<String>,
reason: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum FiuuRecurringStautus {
Accepted,
Failed,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct TxnData {
#[serde(rename = "RequestURL")]
pub request_url: String,
pub request_type: RequestType,
pub request_data: RequestData,
pub request_method: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum RequestType {
Redirect,
Response,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RequestData {
NonThreeDS(NonThreeDSResponseData),
RedirectData(Option<HashMap<String, String>>),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct QrCodeData {
#[serde(rename = "tranID")]
pub tran_id: String,
pub status: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NonThreeDSResponseData {
#[serde(rename = "tranID")]
pub tran_id: String,
pub status: String,
#[serde(rename = "extraP")]
pub extra_parameters: Option<ExtraParameters>,
pub error_code: Option<String>,
pub error_desc: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ExtraParameters {
pub token: Option<Secret<String>>,
}
impl TryFrom<PaymentsResponseRouterData<FiuuPaymentsResponse>> for PaymentsAuthorizeRouterData {
type Error = Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<FiuuPaymentsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
FiuuPaymentsResponse::QRPaymentResponse(ref response) => Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.txn_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs | crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs | use std::collections::HashMap;
#[cfg(feature = "payouts")]
use api_models::payouts::{BankRedirect, PayoutMethodData};
use api_models::webhooks;
use common_enums::{enums, Currency};
use common_utils::{id_type, pii::Email, request::Method, types::FloatMajorUnit};
use hyperswitch_domain_models::{
payment_method_data::{BankRedirectData, PaymentMethodData},
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
InteracCustomerInfo, RouterData,
},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::PoFulfill, router_response_types::PayoutsResponseData,
types::PayoutsRouterData,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
#[cfg(feature = "payouts")]
use crate::types::PayoutsResponseRouterData;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, PaymentsAuthorizeRequestData, RouterData as _},
};
pub struct LoonioRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for LoonioRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
// Auth Struct
pub struct LoonioAuthType {
pub(super) merchant_id: Secret<String>,
pub(super) merchant_token: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for LoonioAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
merchant_id: api_key.to_owned(),
merchant_token: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize)]
pub struct LoonioPaymentRequest {
pub currency_code: Currency,
pub customer_profile: LoonioCustomerProfile,
pub amount: FloatMajorUnit,
pub customer_id: id_type::CustomerId,
pub transaction_id: String,
pub payment_method_type: InteracPaymentMethodType,
#[serde(skip_serializing_if = "Option::is_none")]
pub redirect_url: Option<LoonioRedirectUrl>,
#[serde(skip_serializing_if = "Option::is_none")]
pub webhook_url: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum InteracPaymentMethodType {
InteracEtransfer,
}
#[derive(Debug, Serialize)]
pub struct LoonioCustomerProfile {
pub first_name: Secret<String>,
pub last_name: Secret<String>,
pub email: Email,
}
#[derive(Debug, Serialize)]
pub struct LoonioRedirectUrl {
pub success_url: String,
pub failed_url: String,
}
impl TryFrom<&LoonioRouterData<&PaymentsAuthorizeRouterData>> for LoonioPaymentRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &LoonioRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankRedirect(BankRedirectData::Interac { .. }) => {
let transaction_id = item.router_data.connector_request_reference_id.clone();
let customer_profile = LoonioCustomerProfile {
first_name: item.router_data.get_billing_first_name()?,
last_name: item.router_data.get_billing_last_name()?,
email: item.router_data.get_billing_email()?,
};
let redirect_url = LoonioRedirectUrl {
success_url: item.router_data.request.get_router_return_url()?,
failed_url: item.router_data.request.get_router_return_url()?,
};
Ok(Self {
currency_code: item.router_data.request.currency,
customer_profile,
amount: item.amount,
customer_id: item.router_data.get_customer_id()?,
transaction_id,
payment_method_type: InteracPaymentMethodType::InteracEtransfer,
redirect_url: Some(redirect_url),
webhook_url: Some(item.router_data.request.get_webhook_url()?),
})
}
PaymentMethodData::BankRedirect(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Loonio"),
))?,
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Loonio"),
)
.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoonioPaymentsResponse {
pub payment_form: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, LoonioPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, LoonioPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.data.connector_request_reference_id.clone(),
),
redirection_data: Box::new(Some(RedirectForm::Form {
endpoint: item.response.payment_form,
method: Method::Get,
form_fields: HashMap::new(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoonioTransactionStatus {
Created,
Prepared,
Pending,
Settled,
Available,
Abandoned,
Rejected,
Failed,
Rollback,
Returned,
Nsf,
}
impl From<LoonioTransactionStatus> for enums::AttemptStatus {
fn from(item: LoonioTransactionStatus) -> Self {
match item {
LoonioTransactionStatus::Created => Self::AuthenticationPending,
LoonioTransactionStatus::Prepared | LoonioTransactionStatus::Pending => Self::Pending,
LoonioTransactionStatus::Settled | LoonioTransactionStatus::Available => Self::Charged,
LoonioTransactionStatus::Abandoned
| LoonioTransactionStatus::Rejected
| LoonioTransactionStatus::Failed
| LoonioTransactionStatus::Returned
| LoonioTransactionStatus::Nsf => Self::Failure,
LoonioTransactionStatus::Rollback => Self::Voided,
}
}
}
// Sync Response Structures
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoonioTransactionSyncResponse {
pub transaction_id: String,
pub state: LoonioTransactionStatus,
pub customer_bank_info: Option<LoonioCustomerInfo>,
}
#[derive(Default, Debug, Serialize)]
pub struct LoonioRefundRequest {
pub amount: FloatMajorUnit,
}
impl<F> TryFrom<&LoonioRouterData<&RefundsRouterData<F>>> for LoonioRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &LoonioRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, LoonioPaymentResponseData, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, LoonioPaymentResponseData, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
LoonioPaymentResponseData::Sync(sync_response) => {
let connector_response =
sync_response
.customer_bank_info
.as_ref()
.map(|customer_info| {
ConnectorResponseData::with_additional_payment_method_data(
AdditionalPaymentMethodConnectorResponse::BankRedirect {
interac: Some(InteracCustomerInfo {
customer_info: Some(
common_types::payments::InteracCustomerInfoDetails::from(
customer_info,
),
),
}),
},
)
});
Ok(Self {
status: enums::AttemptStatus::from(sync_response.state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
sync_response.transaction_id,
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
connector_response,
..item.data
})
}
LoonioPaymentResponseData::Webhook(webhook_body) => {
let payment_status = enums::AttemptStatus::from(&webhook_body.event_code);
let connector_response = webhook_body.customer_info.as_ref().map(|customer_info| {
ConnectorResponseData::with_additional_payment_method_data(
AdditionalPaymentMethodConnectorResponse::BankRedirect {
interac: Some(InteracCustomerInfo {
customer_info: Some(
common_types::payments::InteracCustomerInfoDetails::from(
customer_info,
),
),
}),
},
)
});
Ok(Self {
status: payment_status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
webhook_body.api_transaction_id,
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
connector_response,
..item.data
})
}
}
}
}
impl From<&LoonioCustomerInfo> for common_types::payments::InteracCustomerInfoDetails {
fn from(value: &LoonioCustomerInfo) -> Self {
Self {
customer_name: value.customer_name.clone(),
customer_email: value.customer_email.clone(),
customer_phone_number: value.customer_phone_number.clone(),
customer_bank_id: value.customer_bank_id.clone(),
customer_bank_name: value.customer_bank_name.clone(),
}
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct LoonioErrorResponse {
pub status: u16,
pub error_code: Option<String>,
pub message: String,
}
// Webhook related structs
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoonioWebhookEventCode {
TransactionPrepared,
TransactionPending,
TransactionAvailable,
TransactionSettled,
TransactionFailed,
TransactionRejected,
#[serde(rename = "TRANSACTION_WAITING_STATUS_FILE")]
TransactionWaitingStatusFile,
#[serde(rename = "TRANSACTION_STATUS_FILE_RECEIVED")]
TransactionStatusFileReceived,
#[serde(rename = "TRANSACTION_STATUS_FILE_FAILED")]
TransactionStatusFileFailed,
#[serde(rename = "TRANSACTION_RETURNED")]
TransactionReturned,
#[serde(rename = "TRANSACTION_WRONG_DESTINATION")]
TransactionWrongDestination,
#[serde(rename = "TRANSACTION_NSF")]
TransactionNsf,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoonioWebhookTransactionType {
Incoming,
OutgoingVerified,
OutgoingNotVerified,
OutgoingCustomerDefined,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LoonioWebhookBody {
pub amount: FloatMajorUnit,
pub api_transaction_id: String,
pub signature: Option<String>,
pub event_code: LoonioWebhookEventCode,
#[serde(rename = "type")]
pub transaction_type: LoonioWebhookTransactionType,
pub customer_info: Option<LoonioCustomerInfo>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct LoonioCustomerInfo {
pub customer_name: Option<Secret<String>>,
pub customer_email: Option<Email>,
pub customer_phone_number: Option<Secret<String>>,
pub customer_bank_id: Option<Secret<String>>,
pub customer_bank_name: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum LoonioPaymentResponseData {
Sync(LoonioTransactionSyncResponse),
Webhook(LoonioWebhookBody),
}
impl From<&LoonioWebhookEventCode> for webhooks::IncomingWebhookEvent {
fn from(event_code: &LoonioWebhookEventCode) -> Self {
match event_code {
LoonioWebhookEventCode::TransactionSettled
| LoonioWebhookEventCode::TransactionAvailable => Self::PaymentIntentSuccess,
LoonioWebhookEventCode::TransactionPending
| LoonioWebhookEventCode::TransactionPrepared => Self::PaymentIntentProcessing,
LoonioWebhookEventCode::TransactionFailed
// deprecated
| LoonioWebhookEventCode::TransactionRejected
| LoonioWebhookEventCode::TransactionStatusFileFailed
| LoonioWebhookEventCode::TransactionReturned
| LoonioWebhookEventCode::TransactionWrongDestination
| LoonioWebhookEventCode::TransactionNsf => Self::PaymentIntentFailure,
_ => Self::EventNotSupported,
}
}
}
pub(crate) fn get_loonio_webhook_event(
transaction_type: &LoonioWebhookTransactionType,
event_code: &LoonioWebhookEventCode,
) -> webhooks::IncomingWebhookEvent {
match transaction_type {
LoonioWebhookTransactionType::OutgoingNotVerified => {
#[cfg(feature = "payouts")]
{
match event_code {
LoonioWebhookEventCode::TransactionPrepared => {
webhooks::IncomingWebhookEvent::PayoutCreated
}
LoonioWebhookEventCode::TransactionPending => {
webhooks::IncomingWebhookEvent::PayoutProcessing
}
LoonioWebhookEventCode::TransactionAvailable
| LoonioWebhookEventCode::TransactionSettled => {
webhooks::IncomingWebhookEvent::PayoutSuccess
}
LoonioWebhookEventCode::TransactionFailed
| LoonioWebhookEventCode::TransactionRejected => {
webhooks::IncomingWebhookEvent::PayoutFailure
}
_ => webhooks::IncomingWebhookEvent::EventNotSupported,
}
}
#[cfg(not(feature = "payouts"))]
{
webhooks::IncomingWebhookEvent::EventNotSupported
}
}
_ => match event_code {
LoonioWebhookEventCode::TransactionSettled
| LoonioWebhookEventCode::TransactionAvailable => {
webhooks::IncomingWebhookEvent::PaymentIntentSuccess
}
LoonioWebhookEventCode::TransactionPending
| LoonioWebhookEventCode::TransactionPrepared => {
webhooks::IncomingWebhookEvent::PaymentIntentProcessing
}
LoonioWebhookEventCode::TransactionFailed
| LoonioWebhookEventCode::TransactionRejected
| LoonioWebhookEventCode::TransactionStatusFileFailed
| LoonioWebhookEventCode::TransactionReturned
| LoonioWebhookEventCode::TransactionWrongDestination
| LoonioWebhookEventCode::TransactionNsf => {
webhooks::IncomingWebhookEvent::PaymentIntentFailure
}
_ => webhooks::IncomingWebhookEvent::EventNotSupported,
},
}
}
impl From<&LoonioWebhookEventCode> for enums::AttemptStatus {
fn from(event_code: &LoonioWebhookEventCode) -> Self {
match event_code {
LoonioWebhookEventCode::TransactionSettled
| LoonioWebhookEventCode::TransactionAvailable => Self::Charged,
LoonioWebhookEventCode::TransactionPending
| LoonioWebhookEventCode::TransactionPrepared => Self::Pending,
LoonioWebhookEventCode::TransactionFailed
| LoonioWebhookEventCode::TransactionRejected
| LoonioWebhookEventCode::TransactionStatusFileFailed
| LoonioWebhookEventCode::TransactionReturned
| LoonioWebhookEventCode::TransactionWrongDestination
| LoonioWebhookEventCode::TransactionNsf => Self::Failure,
_ => Self::Pending,
}
}
}
// Payout Structures
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
pub struct LoonioPayoutFulfillRequest {
pub currency_code: Currency,
pub customer_profile: LoonioCustomerProfile,
pub amount: FloatMajorUnit,
pub customer_id: id_type::CustomerId,
pub transaction_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub webhook_url: Option<String>,
}
#[cfg(feature = "payouts")]
impl TryFrom<&LoonioRouterData<&PayoutsRouterData<PoFulfill>>> for LoonioPayoutFulfillRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &LoonioRouterData<&PayoutsRouterData<PoFulfill>>,
) -> Result<Self, Self::Error> {
match item.router_data.get_payout_method_data()? {
PayoutMethodData::BankRedirect(BankRedirect::Interac(interac_data)) => {
let customer_profile = LoonioCustomerProfile {
first_name: item.router_data.get_billing_first_name()?,
last_name: item.router_data.get_billing_last_name()?,
email: interac_data.email,
};
Ok(Self {
currency_code: item.router_data.request.destination_currency,
customer_profile,
amount: item.amount,
customer_id: item.router_data.get_customer_id()?,
transaction_id: item.router_data.connector_request_reference_id.clone(),
webhook_url: item.router_data.request.webhook_url.clone(),
})
}
PayoutMethodData::Card(_)
| PayoutMethodData::Bank(_)
| PayoutMethodData::Wallet(_)
| PayoutMethodData::Passthrough(_) => Err(errors::ConnectorError::NotSupported {
message: "Payment Method Not Supported".to_string(),
connector: "Loonio",
})?,
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoonioPayoutFulfillResponse {
pub id: i64,
pub api_transaction_id: String,
#[serde(rename = "type")]
pub transaction_type: String,
pub state: LoonioPayoutStatus,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoonioPayoutStatus {
Created,
Prepared,
Pending,
Settled,
Available,
Rejected,
Abandoned,
ConnectedAbandoned,
ConnectedInsufficientFunds,
Failed,
Nsf,
Returned,
Rollback,
}
#[cfg(feature = "payouts")]
impl From<LoonioPayoutStatus> for enums::PayoutStatus {
fn from(item: LoonioPayoutStatus) -> Self {
match item {
LoonioPayoutStatus::Created | LoonioPayoutStatus::Prepared => Self::Initiated,
LoonioPayoutStatus::Pending => Self::Pending,
LoonioPayoutStatus::Settled | LoonioPayoutStatus::Available => Self::Success,
LoonioPayoutStatus::Rejected
| LoonioPayoutStatus::Abandoned
| LoonioPayoutStatus::ConnectedAbandoned
| LoonioPayoutStatus::ConnectedInsufficientFunds
| LoonioPayoutStatus::Failed
| LoonioPayoutStatus::Nsf
| LoonioPayoutStatus::Returned
| LoonioPayoutStatus::Rollback => Self::Failed,
}
}
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, LoonioPayoutFulfillResponse>>
for PayoutsRouterData<F>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, LoonioPayoutFulfillResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::from(item.response.state)),
connector_payout_id: Some(item.response.api_transaction_id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoonioPayoutSyncResponse {
pub transaction_id: String,
pub state: LoonioPayoutStatus,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, LoonioPayoutSyncResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, LoonioPayoutSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::from(item.response.state)),
connector_payout_id: Some(item.response.transaction_id.to_string()),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs | crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs | use std::collections::HashMap;
use base64::Engine;
use cards::CardNumber;
use common_enums::{enums, Currency};
use common_types::payments::{ApplePayPaymentData, ApplePayPredecryptData};
use common_utils::{
ext_traits::ValueExt,
id_type,
pii::{Email, IpAddress, SecretSerdeValue},
request::Method,
types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{
ApplePayWalletData, BankRedirectData, GiftCardData, PaymentMethodData, WalletData,
},
router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{
CompleteAuthorizeData, PaymentMethodTokenizationData, PaymentsSyncData, ResponseId,
},
router_response_types::{
ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, RedirectForm,
RefundsResponseData,
},
types::{
ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData,
PaymentsPreProcessingRouterData, RefundsRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsPreprocessingResponseRouterData, PaymentsResponseRouterData,
RefundsResponseRouterData, ResponseRouterData,
},
utils::{
self, missing_field_err, to_connector_meta, BrowserInformationData, CardData,
PaymentMethodTokenizationRequestData, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData,
RouterData as RouterDataUtils,
},
};
const MAX_ID_LENGTH: usize = 36;
pub struct PaysafeRouterData<T> {
pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for PaysafeRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct PaysafeConnectorMetadataObject {
pub account_id: PaysafePaymentMethodDetails,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct PaysafePaymentMethodDetails {
pub apple_pay: Option<HashMap<Currency, ApplePayAccountDetails>>,
pub card: Option<HashMap<Currency, CardAccountId>>,
pub interac: Option<HashMap<Currency, RedirectAccountId>>,
pub pay_safe_card: Option<HashMap<Currency, RedirectAccountId>>,
pub skrill: Option<HashMap<Currency, RedirectAccountId>>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct CardAccountId {
no_three_ds: Option<Secret<String>>,
three_ds: Option<Secret<String>>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct ApplePayAccountDetails {
encrypt: Option<Secret<String>>,
decrypt: Option<Secret<String>>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct RedirectAccountId {
three_ds: Option<Secret<String>>,
}
impl TryFrom<&Option<SecretSerdeValue>> for PaysafeConnectorMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
Ok(metadata)
}
}
impl TryFrom<&ConnectorCustomerRouterData> for PaysafeCustomerDetails {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(customer_data: &ConnectorCustomerRouterData) -> Result<Self, Self::Error> {
let merchant_customer_id = match customer_data.customer_id.as_ref() {
Some(customer_id) if customer_id.get_string_repr().len() <= MAX_ID_LENGTH => {
Ok(customer_id.get_string_repr().to_string())
}
Some(customer_id) => Err(errors::ConnectorError::MaxFieldLengthViolated {
connector: "Paysafe".to_string(),
field_name: "customer_id".to_string(),
max_length: MAX_ID_LENGTH,
received_length: customer_id.get_string_repr().len(),
}),
None => Err(errors::ConnectorError::MissingRequiredField {
field_name: "customer_id",
}),
}?;
Ok(Self {
merchant_customer_id,
first_name: customer_data.get_optional_billing_first_name(),
last_name: customer_data.get_optional_billing_last_name(),
email: customer_data.get_optional_billing_email(),
phone: customer_data.get_optional_billing_phone_number(),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeCustomerDetails {
pub merchant_customer_id: String,
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub email: Option<Email>,
pub phone: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDs {
pub merchant_url: String,
pub device_channel: DeviceChannel,
pub message_category: ThreeDsMessageCategory,
pub authentication_purpose: ThreeDsAuthenticationPurpose,
pub requestor_challenge_preference: ThreeDsChallengePreference,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum DeviceChannel {
Browser,
Sdk,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ThreeDsMessageCategory {
Payment,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ThreeDsAuthenticationPurpose {
PaymentTransaction,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ThreeDsChallengePreference {
ChallengeMandated,
NoPreference,
NoChallengeRequested,
ChallengeRequested,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafePaymentHandleRequest {
pub merchant_ref_num: String,
pub amount: MinorUnit,
pub settle_with_auth: bool,
#[serde(flatten)]
pub payment_method: PaysafePaymentMethod,
pub currency_code: Currency,
pub payment_type: PaysafePaymentType,
pub transaction_type: TransactionType,
pub return_links: Vec<ReturnLink>,
pub account_id: Secret<String>,
pub three_ds: Option<ThreeDs>,
pub profile: Option<PaysafeProfile>,
pub billing_details: Option<PaysafeBillingDetails>,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeBillingDetails {
pub nick_name: Option<Secret<String>>,
pub street: Option<Secret<String>>,
pub street2: Option<Secret<String>>,
pub city: Option<String>,
pub state: Secret<String>,
pub zip: Secret<String>,
pub country: api_models::enums::CountryAlpha2,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeProfile {
pub first_name: Secret<String>,
pub last_name: Secret<String>,
pub email: Email,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum PaysafePaymentMethod {
ApplePay {
#[serde(rename = "applePay")]
apple_pay: Box<PaysafeApplepayPayment>,
},
Card {
card: PaysafeCard,
},
Interac {
#[serde(rename = "interacEtransfer")]
interac_etransfer: InteracBankRedirect,
},
PaysafeCard {
#[serde(rename = "paysafecard")]
pay_safe_card: PaysafeGiftCard,
},
Skrill {
skrill: SkrillWallet,
},
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplepayPayment {
pub label: Option<String>,
pub request_billing_address: Option<bool>,
#[serde(rename = "applePayPaymentToken")]
pub apple_pay_payment_token: PaysafeApplePayPaymentToken,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayPaymentToken {
pub token: PaysafeApplePayToken,
#[serde(skip_serializing_if = "Option::is_none")]
pub billing_contact: Option<PaysafeApplePayBillingContact>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayToken {
pub payment_data: PaysafeApplePayPaymentData,
pub payment_method: PaysafeApplePayPaymentMethod,
pub transaction_identifier: String,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum PaysafeApplePayPaymentData {
Encrypted(PaysafeApplePayEncryptedData),
Decrypted(PaysafeApplePayDecryptedDataWrapper),
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayEncryptedData {
pub data: Secret<String>,
pub signature: Secret<String>,
pub header: PaysafeApplePayHeader,
pub version: Secret<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayDecryptedDataWrapper {
pub decrypted_data: PaysafeApplePayDecryptedData,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayDecryptedData {
pub application_primary_account_number: CardNumber,
pub application_expiration_date: Secret<String>,
pub currency_code: String,
pub transaction_amount: Option<MinorUnit>,
pub cardholder_name: Option<Secret<String>>,
pub device_manufacturer_identifier: Option<String>,
pub payment_data_type: Option<String>,
pub payment_data: PaysafeApplePayDecryptedPaymentData,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayDecryptedPaymentData {
pub online_payment_cryptogram: Secret<String>,
pub eci_indicator: Option<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayHeader {
pub public_key_hash: String,
pub ephemeral_public_key: String,
pub transaction_id: String,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayPaymentMethod {
pub display_name: Secret<String>,
pub network: Secret<String>,
#[serde(rename = "type")]
pub method_type: Secret<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeApplePayBillingContact {
pub address_lines: Vec<Option<Secret<String>>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub administrative_area: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub country: Option<String>,
pub country_code: api_models::enums::CountryAlpha2,
#[serde(skip_serializing_if = "Option::is_none")]
pub family_name: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub given_name: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub locality: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phonetic_family_name: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phonetic_given_name: Option<Secret<String>>,
pub postal_code: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sub_administrative_area: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sub_locality: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SkrillWallet {
pub consumer_id: Email,
pub country_code: Option<api_models::enums::CountryAlpha2>,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct InteracBankRedirect {
pub consumer_id: Email,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaysafeGiftCard {
pub consumer_id: id_type::CustomerId,
}
#[derive(Debug, Serialize)]
pub struct ReturnLink {
pub rel: LinkType,
pub href: String,
pub method: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum LinkType {
OnCompleted,
OnFailed,
OnCancelled,
Default,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaysafePaymentType {
// For Apple Pay and Google Pay, paymentType is 'CARD' as per Paysafe docs and is not reserved for card payments only
Card,
Skrill,
InteracEtransfer,
Paysafecard,
}
#[derive(Debug, Serialize)]
pub enum TransactionType {
#[serde(rename = "PAYMENT")]
Payment,
}
impl PaysafePaymentMethodDetails {
pub fn get_applepay_encrypt_account_id(
&self,
currency: Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
self.apple_pay
.as_ref()
.and_then(|apple_pay| apple_pay.get(¤cy))
.and_then(|flow| flow.encrypt.clone())
.ok_or_else(|| errors::ConnectorError::InvalidConnectorConfig {
config: "Missing ApplePay encrypt account_id",
})
}
pub fn get_applepay_decrypt_account_id(
&self,
currency: Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
self.apple_pay
.as_ref()
.and_then(|apple_pay| apple_pay.get(¤cy))
.and_then(|flow| flow.decrypt.clone())
.ok_or_else(|| errors::ConnectorError::InvalidConnectorConfig {
config: "Missing ApplePay decrypt account_id",
})
}
pub fn get_no_three_ds_account_id(
&self,
currency: Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
self.card
.as_ref()
.and_then(|cards| cards.get(¤cy))
.and_then(|card| card.no_three_ds.clone())
.ok_or(errors::ConnectorError::InvalidConnectorConfig {
config: "Missing no_3ds account_id",
})
}
pub fn get_three_ds_account_id(
&self,
currency: Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
self.card
.as_ref()
.and_then(|cards| cards.get(¤cy))
.and_then(|card| card.three_ds.clone())
.ok_or(errors::ConnectorError::InvalidConnectorConfig {
config: "Missing 3ds account_id",
})
}
pub fn get_skrill_account_id(
&self,
currency: Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
self.skrill
.as_ref()
.and_then(|wallets| wallets.get(¤cy))
.and_then(|skrill| skrill.three_ds.clone())
.ok_or(errors::ConnectorError::InvalidConnectorConfig {
config: "Missing skrill account_id",
})
}
pub fn get_interac_account_id(
&self,
currency: Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
self.interac
.as_ref()
.and_then(|redirects| redirects.get(¤cy))
.and_then(|interac| interac.three_ds.clone())
.ok_or(errors::ConnectorError::InvalidConnectorConfig {
config: "Missing interac account_id",
})
}
pub fn get_paysafe_gift_card_account_id(
&self,
currency: Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
self.pay_safe_card
.as_ref()
.and_then(|gift_cards| gift_cards.get(¤cy))
.and_then(|pay_safe_card| pay_safe_card.three_ds.clone())
.ok_or(errors::ConnectorError::InvalidConnectorConfig {
config: "Missing paysafe gift card account_id",
})
}
}
fn create_paysafe_billing_details<T>(
is_customer_initiated_mandate_payment: bool,
item: &T,
) -> Result<Option<PaysafeBillingDetails>, error_stack::Report<errors::ConnectorError>>
where
T: RouterDataUtils,
{
// For customer-initiated mandate payments, zip, country and state fields are mandatory
if is_customer_initiated_mandate_payment {
Ok(Some(PaysafeBillingDetails {
nick_name: item.get_optional_billing_first_name(),
street: item.get_optional_billing_line1(),
street2: item.get_optional_billing_line2(),
city: item.get_optional_billing_city(),
zip: item.get_billing_zip()?,
country: item.get_billing_country()?,
state: item.get_billing_state_code()?,
}))
}
// For normal payments, only send billing details if billing mandatory fields are available
else if let (Some(zip), Some(country), Some(state)) = (
item.get_optional_billing_zip(),
item.get_optional_billing_country(),
item.get_optional_billing_state_code(),
) {
Ok(Some(PaysafeBillingDetails {
nick_name: item.get_optional_billing_first_name(),
street: item.get_optional_billing_line1(),
street2: item.get_optional_billing_line2(),
city: item.get_optional_billing_city(),
zip,
country,
state,
}))
} else {
Ok(None)
}
}
impl TryFrom<&PaysafeRouterData<&PaymentsPreProcessingRouterData>> for PaysafePaymentHandleRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaysafeRouterData<&PaymentsPreProcessingRouterData>,
) -> Result<Self, Self::Error> {
let metadata: PaysafeConnectorMetadataObject =
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
let amount = item.amount;
let currency_code = item.router_data.request.get_currency()?;
let redirect_url = item.router_data.request.get_router_return_url()?;
let return_links = vec![
ReturnLink {
rel: LinkType::Default,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
ReturnLink {
rel: LinkType::OnCompleted,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
ReturnLink {
rel: LinkType::OnFailed,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
ReturnLink {
rel: LinkType::OnCancelled,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
];
let settle_with_auth = matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
);
let transaction_type = TransactionType::Payment;
let billing_details = create_paysafe_billing_details(
item.router_data
.request
.is_customer_initiated_mandate_payment(),
item.router_data,
)?;
let (payment_method, payment_type, account_id) =
match item.router_data.request.get_payment_method_data()?.clone() {
PaymentMethodData::Card(req_card) => {
let card = PaysafeCard {
card_num: req_card.card_number.clone(),
card_expiry: PaysafeCardExpiry {
month: req_card.card_exp_month.clone(),
year: req_card.get_expiry_year_4_digit(),
},
cvv: if req_card.card_cvc.clone().expose().is_empty() {
None
} else {
Some(req_card.card_cvc.clone())
},
holder_name: item.router_data.get_optional_billing_full_name(),
};
let payment_method = PaysafePaymentMethod::Card { card: card.clone() };
let payment_type = PaysafePaymentType::Card;
let account_id = metadata
.account_id
.get_no_three_ds_account_id(currency_code)?;
(payment_method, payment_type, account_id)
}
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::ApplePay(applepay_data) => {
let is_encrypted = matches!(
applepay_data.payment_data,
ApplePayPaymentData::Encrypted(_)
);
let account_id = if is_encrypted {
metadata
.account_id
.get_applepay_encrypt_account_id(currency_code)?
} else {
metadata
.account_id
.get_applepay_decrypt_account_id(currency_code)?
};
let applepay_payment =
PaysafeApplepayPayment::try_from((&applepay_data, item))?;
let payment_method = PaysafePaymentMethod::ApplePay {
apple_pay: Box::new(applepay_payment),
};
let payment_type = PaysafePaymentType::Card;
(payment_method, payment_type, account_id)
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePay(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::PaypalRedirect(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::WeChatPayQr(_)
| WalletData::RevolutPay(_)
| WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paysafe"),
))?,
},
_ => Err(errors::ConnectorError::NotImplemented(
"Payment Method".to_string(),
))?,
};
Ok(Self {
merchant_ref_num: item.router_data.connector_request_reference_id.clone(),
amount,
settle_with_auth,
payment_method,
currency_code,
payment_type,
transaction_type,
return_links,
account_id,
three_ds: None,
profile: None,
billing_details,
})
}
}
impl TryFrom<&PaysafeRouterData<&TokenizationRouterData>> for PaysafePaymentHandleRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaysafeRouterData<&TokenizationRouterData>) -> Result<Self, Self::Error> {
let metadata: PaysafeConnectorMetadataObject =
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
let amount = item.amount;
let currency_code = item.router_data.request.currency;
let redirect_url = item.router_data.request.get_router_return_url()?;
let return_links = vec![
ReturnLink {
rel: LinkType::Default,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
ReturnLink {
rel: LinkType::OnCompleted,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
ReturnLink {
rel: LinkType::OnFailed,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
ReturnLink {
rel: LinkType::OnCancelled,
href: redirect_url.clone(),
method: Method::Get.to_string(),
},
];
let settle_with_auth = matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
);
let transaction_type = TransactionType::Payment;
let billing_details = create_paysafe_billing_details(
item.router_data
.request
.is_customer_initiated_mandate_payment(),
item.router_data,
)?;
let (payment_method, payment_type, account_id) =
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = PaysafeCard {
card_num: req_card.card_number.clone(),
card_expiry: PaysafeCardExpiry {
month: req_card.card_exp_month.clone(),
year: req_card.get_expiry_year_4_digit(),
},
cvv: if req_card.card_cvc.clone().expose().is_empty() {
None
} else {
Some(req_card.card_cvc.clone())
},
holder_name: item.router_data.get_optional_billing_full_name(),
};
let payment_method = PaysafePaymentMethod::Card { card: card.clone() };
let payment_type = PaysafePaymentType::Card;
let account_id = metadata
.account_id
.get_no_three_ds_account_id(currency_code)?;
(payment_method, payment_type, account_id)
}
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::ApplePay(applepay_data) => {
let is_encrypted = matches!(
applepay_data.payment_data,
ApplePayPaymentData::Encrypted(_)
);
let account_id = if is_encrypted {
metadata
.account_id
.get_applepay_encrypt_account_id(currency_code)?
} else {
metadata
.account_id
.get_applepay_decrypt_account_id(currency_code)?
};
let applepay_payment =
PaysafeApplepayPayment::try_from((&applepay_data, item))?;
let payment_method = PaysafePaymentMethod::ApplePay {
apple_pay: Box::new(applepay_payment),
};
let payment_type = PaysafePaymentType::Card;
(payment_method, payment_type, account_id)
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePay(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::PaypalRedirect(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::WeChatPayQr(_)
| WalletData::RevolutPay(_)
| WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paysafe"),
))?,
},
_ => Err(errors::ConnectorError::NotImplemented(
"Payment Method".to_string(),
))?,
};
Ok(Self {
merchant_ref_num: item.router_data.connector_request_reference_id.clone(),
amount,
settle_with_auth,
payment_method,
currency_code,
payment_type,
transaction_type,
return_links,
account_id,
three_ds: None,
profile: None,
billing_details,
})
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaysafeUsage {
SingleUse,
MultiUse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaysafePaymentHandleResponse {
pub id: String,
pub merchant_ref_num: String,
pub payment_handle_token: Secret<String>,
pub usage: Option<PaysafeUsage>,
pub status: PaysafePaymentHandleStatus,
pub links: Option<Vec<PaymentLink>>,
pub error: Option<Error>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentLink {
pub rel: String,
pub href: String,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaysafePaymentHandleStatus {
Initiated,
Payable,
#[default]
Processing,
Failed,
Expired,
Completed,
Error,
}
impl TryFrom<PaysafePaymentHandleStatus> for common_enums::AttemptStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: PaysafePaymentHandleStatus) -> Result<Self, Self::Error> {
match item {
PaysafePaymentHandleStatus::Completed => Ok(Self::Authorized),
PaysafePaymentHandleStatus::Failed
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/payload/responses.rs | crates/hyperswitch_connectors/src/connectors/payload/responses.rs | use masking::Secret;
use serde::{Deserialize, Serialize};
// PaymentsResponse
#[derive(Default, Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum PayloadPaymentStatus {
Authorized,
Declined,
Processed,
#[default]
Processing,
Rejected,
Voided,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PayloadPaymentsResponse {
PayloadCardsResponse(PayloadCardsResponseData),
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum AvsResponse {
Unknown,
NoMatch,
Zip,
Street,
StreetAndZip,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PayloadCardsResponseData {
pub amount: Option<f64>,
pub avs: Option<AvsResponse>,
pub customer_id: Option<Secret<String>>,
#[serde(rename = "id")]
pub transaction_id: String,
#[serde(rename = "payment_method_id")]
pub connector_payment_method_id: Option<Secret<String>>,
pub processing_id: Option<Secret<String>>,
pub processing_method_id: Option<String>,
pub ref_number: Option<String>,
pub status: PayloadPaymentStatus,
pub status_code: Option<String>,
pub status_message: Option<String>,
#[serde(rename = "type")]
pub response_type: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomerResponse {
pub id: String,
}
// Type definition for Refund Response
// Added based on assumptions since this is not provided in the documentation
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum RefundStatus {
Declined,
Processed,
#[default]
Processing,
Rejected,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundsLedger {
pub amount: f64,
#[serde(rename = "assoc_transaction_id")]
pub associated_transaction_id: String, // Connector transaction id
#[serde(rename = "id")]
pub ledger_id: Secret<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PayloadRefundResponse {
pub amount: Option<f64>,
#[serde(rename = "id")]
pub transaction_id: String,
pub ledger: Vec<RefundsLedger>,
#[serde(rename = "payment_method_id")]
pub connector_payment_method_id: Option<Secret<String>>,
pub processing_id: Option<Secret<String>>,
pub ref_number: Option<String>,
pub status: RefundStatus,
pub status_code: Option<String>,
pub status_message: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct PayloadErrorResponse {
pub error_type: String,
pub error_description: String,
pub object: String,
/// Payload returns arbitrary details in JSON format
pub details: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum PayloadWebhooksTrigger {
Payment,
Processed,
Authorized,
Credit,
Refund,
Reversal,
Void,
AutomaticPayment,
Decline,
Deposit,
Reject,
#[serde(rename = "payment_activation:status")]
PaymentActivationStatus,
#[serde(rename = "payment_link:status")]
PaymentLinkStatus,
ProcessingStatus,
BankAccountReject,
Chargeback,
ChargebackReversal,
#[serde(rename = "transaction:operation")]
TransactionOperation,
#[serde(rename = "transaction:operation:clear")]
TransactionOperationClear,
}
// Webhook response structures
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PayloadWebhookEvent {
pub object: String, // Added to match actual webhook structure
pub trigger: PayloadWebhooksTrigger,
pub webhook_id: String,
pub triggered_at: String, // Added to match actual webhook structure
// Webhooks Payload
pub triggered_on: PayloadEventDetails,
pub url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PayloadEventDetails {
#[serde(rename = "id")]
pub transaction_id: Option<String>,
pub object: String,
pub value: Option<serde_json::Value>, // Changed to handle any value type including null
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/payload/transformers.rs | crates/hyperswitch_connectors/src/connectors/payload/transformers.rs | use std::collections::HashMap;
use api_models::webhooks::IncomingWebhookEvent;
use common_enums::enums;
use common_utils::{ext_traits::ValueExt, types::StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
address::AddressDetails,
payment_method_data::{BankDebitData, PaymentMethodData},
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ErrorResponse, RouterData,
},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{
ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, RefundsResponseData,
},
types::{
ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCaptureRouterData,
RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeOptionInterface, Secret};
use serde::Deserialize;
use super::{requests, responses};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
get_unimplemented_payment_method_error_message, is_manual_capture, AddressDetailsData,
CardData, CustomerData, PaymentsAuthorizeRequestData, PaymentsSetupMandateRequestData,
RouterData as OtherRouterData,
},
};
type Error = error_stack::Report<errors::ConnectorError>;
#[allow(clippy::too_many_arguments)]
fn build_payload_payment_request_data(
payment_method_data: &PaymentMethodData,
connector_auth_type: &ConnectorAuthType,
currency: enums::Currency,
amount: StringMajorUnit,
billing_address: &AddressDetails,
capture_method: Option<enums::CaptureMethod>,
is_mandate: bool,
customer_id: Option<String>,
is_three_ds: bool,
) -> Result<requests::PayloadPaymentRequestData, Error> {
let payment_method: Result<requests::PayloadPaymentMethods, Error> = match payment_method_data {
PaymentMethodData::Card(req_card) => {
if is_three_ds {
Err(errors::ConnectorError::NotSupported {
message: "Cards 3DS".to_string(),
connector: "Payload",
})?
}
let card = requests::PayloadCard {
number: req_card.clone().card_number,
expiry: req_card
.clone()
.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?,
cvc: req_card.card_cvc.clone(),
};
Ok(requests::PayloadPaymentMethods::Card(card))
}
PaymentMethodData::BankDebit(BankDebitData::AchBankDebit {
account_number,
routing_number,
bank_type,
bank_holder_type,
bank_account_holder_name,
..
}) => {
let account_class = bank_holder_type.map(|holder_type| match holder_type {
enums::BankHolderType::Business => requests::PayloadAccClass::Business,
enums::BankHolderType::Personal => requests::PayloadAccClass::Personal,
});
let account_type = bank_type
.map(|b_type| match b_type {
enums::BankType::Checking => requests::PayloadAccAccountType::Checking,
enums::BankType::Savings => requests::PayloadAccAccountType::Savings,
})
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "bank_type",
})?;
let account_holder = bank_account_holder_name.clone().ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "bank_account_holder_name",
}
})?;
let bank = requests::PayloadBank {
account_class,
account_currency: currency.to_string(),
account_number: account_number.clone(),
account_type,
routing_number: routing_number.clone(),
account_holder,
};
Ok(requests::PayloadPaymentMethods::BankAccount(bank))
}
_ => Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Payload"),
)
.into()),
};
let city = billing_address.get_optional_city().to_owned();
let country = billing_address.get_optional_country().to_owned();
let postal_code = billing_address.get_zip()?.to_owned();
let state_province = billing_address.get_optional_state().to_owned();
let street_address = billing_address.get_optional_line1().to_owned();
// For manual capture, set status to "authorized"
let status = if is_manual_capture(capture_method) {
Some(responses::PayloadPaymentStatus::Authorized)
} else {
None
};
let billing_address = requests::BillingAddress {
city,
country,
postal_code,
state_province,
street_address,
};
let payload_auth = PayloadAuth::try_from((connector_auth_type, currency))?;
Ok(requests::PayloadPaymentRequestData {
amount,
payment_method: payment_method?,
transaction_types: requests::TransactionTypes::Payment,
status,
billing_address,
processing_id: payload_auth.processing_account_id,
keep_active: is_mandate,
customer_id,
})
}
pub struct PayloadRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for PayloadRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
impl TryFrom<&ConnectorCustomerRouterData> for requests::CustomerRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ConnectorCustomerRouterData) -> Result<Self, Self::Error> {
Ok(Self {
keep_active: item.request.is_mandate_payment(),
email: item.request.get_email()?,
name: item.request.get_name()?,
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, responses::CustomerResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, responses::CustomerResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(item.response.id),
)),
..item.data
})
}
}
// Auth Struct
#[derive(Debug, Clone, Deserialize)]
pub struct PayloadAuth {
pub api_key: Secret<String>,
pub processing_account_id: Option<Secret<String>>,
}
#[derive(Debug, Clone)]
pub struct PayloadAuthType {
pub auths: HashMap<enums::Currency, PayloadAuth>,
}
impl TryFrom<(&ConnectorAuthType, enums::Currency)> for PayloadAuth {
type Error = Error;
fn try_from(value: (&ConnectorAuthType, enums::Currency)) -> Result<Self, Self::Error> {
let (auth_type, currency) = value;
match auth_type {
ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
let auth_key = auth_key_map.get(¤cy).ok_or(
errors::ConnectorError::CurrencyNotSupported {
message: currency.to_string(),
connector: "Payload",
},
)?;
auth_key
.to_owned()
.parse_value("PayloadAuth")
.change_context(errors::ConnectorError::FailedToObtainAuthType)
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<&ConnectorAuthType> for PayloadAuthType {
type Error = Error;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
let auths = auth_key_map
.iter()
.map(|(currency, auth_key)| {
let auth: PayloadAuth = auth_key
.to_owned()
.parse_value("PayloadAuth")
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "auth_key_map",
})?;
Ok((*currency, auth))
})
.collect::<Result<_, Self::Error>>()?;
Ok(Self { auths })
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<&SetupMandateRouterData> for requests::PayloadPaymentRequestData {
type Error = Error;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
match item.request.amount {
Some(amount) if amount > 0 => Err(errors::ConnectorError::FlowNotSupported {
flow: "Setup mandate with non zero amount".to_string(),
connector: "Payload".to_string(),
}
.into()),
_ => {
let billing_address = item.get_billing_address()?;
let is_mandate = item.request.is_customer_initiated_mandate_payment();
build_payload_payment_request_data(
&item.request.payment_method_data,
&item.connector_auth_type,
item.request.currency,
StringMajorUnit::zero(),
billing_address,
item.request.capture_method,
is_mandate,
item.get_connector_customer_id()?.into(),
item.is_three_ds(),
)
}
}
}
}
impl TryFrom<&PayloadRouterData<&PaymentsAuthorizeRouterData>>
for requests::PayloadPaymentsRequest
{
type Error = Error;
fn try_from(
item: &PayloadRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { .. })
| PaymentMethodData::Card(_) => {
let billing_address: &AddressDetails = item.router_data.get_billing_address()?;
let is_mandate = item.router_data.request.is_mandate_payment();
let payment_request = build_payload_payment_request_data(
&item.router_data.request.payment_method_data,
&item.router_data.connector_auth_type,
item.router_data.request.currency,
item.amount.clone(),
billing_address,
item.router_data.request.capture_method,
is_mandate,
item.router_data.connector_customer.clone(),
item.router_data.is_three_ds(),
)?;
Ok(Self::PaymentRequest(Box::new(payment_request)))
}
// PaymentMethodData::BankDebit()
PaymentMethodData::MandatePayment => {
// For manual capture, set status to "authorized"
let status = if is_manual_capture(item.router_data.request.capture_method) {
Some(responses::PayloadPaymentStatus::Authorized)
} else {
None
};
Ok(Self::PayloadMandateRequest(Box::new(
requests::PayloadMandateRequestData {
amount: item.amount.clone(),
transaction_types: requests::TransactionTypes::Payment,
payment_method_id: Secret::new(
item.router_data.request.get_connector_mandate_id()?,
),
status,
},
)))
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
impl From<responses::PayloadPaymentStatus> for common_enums::AttemptStatus {
fn from(item: responses::PayloadPaymentStatus) -> Self {
match item {
responses::PayloadPaymentStatus::Authorized => Self::Authorized,
responses::PayloadPaymentStatus::Processed => Self::Charged,
responses::PayloadPaymentStatus::Processing => Self::Pending,
responses::PayloadPaymentStatus::Rejected
| responses::PayloadPaymentStatus::Declined => Self::Failure,
responses::PayloadPaymentStatus::Voided => Self::Voided,
}
}
}
impl<F: 'static, T>
TryFrom<ResponseRouterData<F, responses::PayloadPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
where
T: 'static,
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, responses::PayloadPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.clone() {
responses::PayloadPaymentsResponse::PayloadCardsResponse(response) => {
let status = enums::AttemptStatus::from(response.status);
let router_data: &dyn std::any::Any = &item.data;
let is_mandate_payment = router_data
.downcast_ref::<PaymentsAuthorizeRouterData>()
.is_some_and(|router_data| router_data.request.is_mandate_payment())
|| router_data
.downcast_ref::<SetupMandateRouterData>()
.is_some();
let mandate_reference = if is_mandate_payment {
let connector_payment_method_id =
response.connector_payment_method_id.clone().expose_option();
if connector_payment_method_id.is_some() {
Some(MandateReference {
connector_mandate_id: connector_payment_method_id,
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})
} else {
None
}
} else {
None
};
let connector_response = {
response.avs.map(|avs_response| {
let payment_checks = serde_json::json!({
"avs_result": avs_response
});
AdditionalPaymentMethodConnectorResponse::Card {
authentication_data: None,
payment_checks: Some(payment_checks),
card_network: None,
domestic_network: None,
}
})
}
.map(ConnectorResponseData::with_additional_payment_method_data);
let response_result = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
attempt_status: None,
code: response
.status_code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: response
.status_message
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: response.status_message,
status_code: item.http_code,
connector_transaction_id: Some(response.transaction_id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.transaction_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: response.ref_number,
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response: response_result,
connector_response,
..item.data
})
}
}
}
}
impl<T> TryFrom<&PayloadRouterData<T>> for requests::PayloadCancelRequest {
type Error = Error;
fn try_from(_item: &PayloadRouterData<T>) -> Result<Self, Self::Error> {
Ok(Self {
status: responses::PayloadPaymentStatus::Voided,
})
}
}
impl TryFrom<&PayloadRouterData<&PaymentsCaptureRouterData>> for requests::PayloadCaptureRequest {
type Error = Error;
fn try_from(
_item: &PayloadRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: responses::PayloadPaymentStatus::Processed,
})
}
}
impl<F> TryFrom<&PayloadRouterData<&RefundsRouterData<F>>> for requests::PayloadRefundRequest {
type Error = Error;
fn try_from(item: &PayloadRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let connector_transaction_id = item.router_data.request.connector_transaction_id.clone();
Ok(Self {
transaction_type: requests::TransactionTypes::Refund,
amount: item.amount.to_owned(),
ledger_assoc_transaction_id: connector_transaction_id,
})
}
}
impl From<responses::RefundStatus> for enums::RefundStatus {
fn from(item: responses::RefundStatus) -> Self {
match item {
responses::RefundStatus::Processed => Self::Success,
responses::RefundStatus::Processing => Self::Pending,
responses::RefundStatus::Declined | responses::RefundStatus::Rejected => Self::Failure,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, responses::PayloadRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<Execute, responses::PayloadRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, responses::PayloadRefundResponse>>
for RefundsRouterData<RSync>
{
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<RSync, responses::PayloadRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
// Webhook transformations
impl From<responses::PayloadWebhooksTrigger> for IncomingWebhookEvent {
fn from(trigger: responses::PayloadWebhooksTrigger) -> Self {
match trigger {
// Payment Success Events
responses::PayloadWebhooksTrigger::Processed => Self::PaymentIntentSuccess,
responses::PayloadWebhooksTrigger::Authorized => {
Self::PaymentIntentAuthorizationSuccess
}
// Payment Processing Events
responses::PayloadWebhooksTrigger::Payment
| responses::PayloadWebhooksTrigger::AutomaticPayment => Self::PaymentIntentProcessing,
// Payment Failure Events
responses::PayloadWebhooksTrigger::Decline
| responses::PayloadWebhooksTrigger::Reject
| responses::PayloadWebhooksTrigger::BankAccountReject => Self::PaymentIntentFailure,
responses::PayloadWebhooksTrigger::Void
| responses::PayloadWebhooksTrigger::Reversal => Self::PaymentIntentCancelled,
// Dispute Events
responses::PayloadWebhooksTrigger::Chargeback => Self::DisputeOpened,
responses::PayloadWebhooksTrigger::ChargebackReversal => Self::DisputeWon,
// Other payment-related events
// Events not supported by our standard flows
responses::PayloadWebhooksTrigger::PaymentActivationStatus
| responses::PayloadWebhooksTrigger::Refund
| responses::PayloadWebhooksTrigger::Credit
| responses::PayloadWebhooksTrigger::Deposit
| responses::PayloadWebhooksTrigger::PaymentLinkStatus
| responses::PayloadWebhooksTrigger::ProcessingStatus
| responses::PayloadWebhooksTrigger::TransactionOperation
| responses::PayloadWebhooksTrigger::TransactionOperationClear => {
Self::EventNotSupported
}
}
}
}
impl TryFrom<responses::PayloadWebhooksTrigger> for responses::PayloadPaymentStatus {
type Error = Error;
fn try_from(trigger: responses::PayloadWebhooksTrigger) -> Result<Self, Self::Error> {
match trigger {
// Payment Success Events
responses::PayloadWebhooksTrigger::Processed => Ok(Self::Processed),
responses::PayloadWebhooksTrigger::Authorized => Ok(Self::Authorized),
// Payment Processing Events
responses::PayloadWebhooksTrigger::Payment
| responses::PayloadWebhooksTrigger::AutomaticPayment
| responses::PayloadWebhooksTrigger::Reversal => Ok(Self::Processing),
// Payment Failure Events
responses::PayloadWebhooksTrigger::Decline
| responses::PayloadWebhooksTrigger::Reject
| responses::PayloadWebhooksTrigger::BankAccountReject => Ok(Self::Declined),
responses::PayloadWebhooksTrigger::Void => Ok(Self::Voided),
responses::PayloadWebhooksTrigger::Refund => {
Err(errors::ConnectorError::NotSupported {
message: "Refund Webhook".to_string(),
connector: "Payload",
}
.into())
}
responses::PayloadWebhooksTrigger::Chargeback
| responses::PayloadWebhooksTrigger::ChargebackReversal
| responses::PayloadWebhooksTrigger::PaymentActivationStatus
| responses::PayloadWebhooksTrigger::Credit
| responses::PayloadWebhooksTrigger::Deposit
| responses::PayloadWebhooksTrigger::PaymentLinkStatus
| responses::PayloadWebhooksTrigger::ProcessingStatus
| responses::PayloadWebhooksTrigger::TransactionOperation
| responses::PayloadWebhooksTrigger::TransactionOperationClear => {
Err(errors::ConnectorError::WebhookEventTypeNotFound.into())
}
}
}
}
impl TryFrom<responses::PayloadWebhookEvent> for responses::PayloadPaymentsResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(webhook_body: responses::PayloadWebhookEvent) -> Result<Self, Self::Error> {
let status = responses::PayloadPaymentStatus::try_from(webhook_body.trigger.clone())?;
Ok(Self::PayloadCardsResponse(
responses::PayloadCardsResponseData {
amount: None,
avs: None,
customer_id: None,
transaction_id: webhook_body
.triggered_on
.transaction_id
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?,
connector_payment_method_id: None,
processing_id: None,
processing_method_id: None,
ref_number: None,
status,
status_code: None,
status_message: None,
response_type: None,
},
))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/payload/requests.rs | crates/hyperswitch_connectors/src/connectors/payload/requests.rs | use common_utils::{pii::Email, types::StringMajorUnit};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::connectors::payload::responses;
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PayloadPaymentsRequest {
PaymentRequest(Box<PayloadPaymentRequestData>),
PayloadMandateRequest(Box<PayloadMandateRequestData>),
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum TransactionTypes {
Credit,
Chargeback,
ChargebackReversal,
Deposit,
Payment,
Refund,
Reversal,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct BillingAddress {
#[serde(rename = "payment_method[billing_address][city]")]
pub city: Option<String>,
#[serde(rename = "payment_method[billing_address][country_code]")]
pub country: Option<common_enums::CountryAlpha2>,
#[serde(rename = "payment_method[billing_address][postal_code]")]
pub postal_code: Secret<String>,
#[serde(rename = "payment_method[billing_address][state_province]")]
pub state_province: Option<Secret<String>>,
#[serde(rename = "payment_method[billing_address][street_address]")]
pub street_address: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize)]
pub struct PayloadPaymentRequestData {
pub amount: StringMajorUnit,
#[serde(flatten)]
pub payment_method: PayloadPaymentMethods,
#[serde(rename = "type")]
pub transaction_types: TransactionTypes,
// For manual capture, set status to "authorized", otherwise omit
#[serde(skip_serializing_if = "Option::is_none")]
pub status: Option<responses::PayloadPaymentStatus>,
// Billing address fields are for AVS validation
#[serde(flatten)]
pub billing_address: BillingAddress,
pub processing_id: Option<Secret<String>>,
/// Allows one-time payment by customer without saving their payment method
/// This is true by default
#[serde(rename = "payment_method[keep_active]")]
pub keep_active: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer_id: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct CustomerRequest {
pub keep_active: bool,
pub email: Email,
pub name: Secret<String>,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct PayloadMandateRequestData {
pub amount: StringMajorUnit,
#[serde(rename = "type")]
pub transaction_types: TransactionTypes,
// Based on the connectors' response, we can do recurring payment either based on a default payment method id saved in the customer profile or a specific payment method id
// Connector by default, saves every payment method
pub payment_method_id: Secret<String>,
// For manual capture, set status to "authorized", otherwise omit
#[serde(skip_serializing_if = "Option::is_none")]
pub status: Option<responses::PayloadPaymentStatus>,
}
#[derive(Default, Clone, Debug, Serialize, Eq, PartialEq)]
pub struct PayloadCard {
#[serde(rename = "payment_method[card][card_number]")]
pub number: cards::CardNumber,
#[serde(rename = "payment_method[card][expiry]")]
pub expiry: Secret<String>,
#[serde(rename = "payment_method[card][card_code]")]
pub cvc: Secret<String>,
}
#[derive(Clone, Debug, Serialize)]
pub struct PayloadBank {
#[serde(rename = "payment_method[bank_account][account_class]")]
pub account_class: Option<PayloadAccClass>,
#[serde(rename = "payment_method[bank_account][account_currency]")]
pub account_currency: String,
#[serde(rename = "payment_method[bank_account][account_number]")]
pub account_number: Secret<String>,
#[serde(rename = "payment_method[bank_account][account_type]")]
pub account_type: PayloadAccAccountType,
#[serde(rename = "payment_method[bank_account][routing_number]")]
pub routing_number: Secret<String>,
#[serde(rename = "payment_method[account_holder]")]
pub account_holder: Secret<String>,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PayloadAccClass {
Personal,
Business,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PayloadAccAccountType {
Checking,
Savings,
}
#[derive(Clone, Debug, Serialize)]
#[serde(tag = "payment_method[type]")]
#[serde(rename_all = "snake_case")]
pub enum PayloadPaymentMethods {
Card(PayloadCard),
BankAccount(PayloadBank),
}
#[derive(Clone, Debug, Serialize, PartialEq)]
pub struct PayloadCancelRequest {
pub status: responses::PayloadPaymentStatus,
}
// Type definition for CaptureRequest
#[derive(Clone, Debug, Serialize, PartialEq)]
pub struct PayloadCaptureRequest {
pub status: responses::PayloadPaymentStatus,
}
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
pub struct PayloadRefundRequest {
#[serde(rename = "type")]
pub transaction_type: TransactionTypes,
pub amount: StringMajorUnit,
#[serde(rename = "ledger[0][assoc_transaction_id]")]
pub ledger_assoc_transaction_id: String,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/square/transformers.rs | crates/hyperswitch_connectors/src/connectors/square/transformers.rs | use api_models::webhooks::IncomingWebhookEvent;
use common_enums::enums;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankDebitData, Card, PayLaterData, PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
router_flow_types::{refunds::Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData as _},
};
impl TryFrom<(&types::TokenizationRouterData, BankDebitData)> for SquareTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (&types::TokenizationRouterData, BankDebitData),
) -> Result<Self, Self::Error> {
let (_item, bank_debit_data) = value;
match bank_debit_data {
BankDebitData::AchBankDebit { .. }
| BankDebitData::SepaBankDebit { .. }
| BankDebitData::BecsBankDebit { .. }
| BankDebitData::BacsBankDebit { .. }
| BankDebitData::SepaGuarenteedBankDebit { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Square"),
))?
}
}
}
}
impl TryFrom<(&types::TokenizationRouterData, Card)> for SquareTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: (&types::TokenizationRouterData, Card)) -> Result<Self, Self::Error> {
let (item, card_data) = value;
let auth = SquareAuthType::try_from(&item.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let exp_year = Secret::new(
card_data
.get_expiry_year_4_digit()
.peek()
.parse::<u16>()
.change_context(errors::ConnectorError::DateFormattingFailed)?,
);
let exp_month = Secret::new(
card_data
.card_exp_month
.peek()
.parse::<u16>()
.change_context(errors::ConnectorError::DateFormattingFailed)?,
);
//The below error will never happen because if session-id is not generated it would give error in execute_pretasks itself.
let session_id = Secret::new(
item.session_token
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?,
);
Ok(Self::Card(SquareTokenizeData {
client_id: auth.key1,
session_id,
card_data: SquareCardData {
exp_year,
exp_month,
number: card_data.card_number,
cvv: card_data.card_cvc,
},
}))
}
}
impl TryFrom<(&types::TokenizationRouterData, PayLaterData)> for SquareTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (&types::TokenizationRouterData, PayLaterData),
) -> Result<Self, Self::Error> {
let (_item, pay_later_data) = value;
match pay_later_data {
PayLaterData::AfterpayClearpayRedirect { .. }
| PayLaterData::KlarnaRedirect { .. }
| PayLaterData::KlarnaSdk { .. }
| PayLaterData::AffirmRedirect { .. }
| PayLaterData::PayBrightRedirect { .. }
| PayLaterData::WalleyRedirect { .. }
| PayLaterData::AlmaRedirect { .. }
| PayLaterData::FlexitiRedirect { .. }
| PayLaterData::AtomeRedirect { .. }
| PayLaterData::BreadpayRedirect { .. }
| PayLaterData::PayjustnowRedirect { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Square"),
))?
}
}
}
}
impl TryFrom<(&types::TokenizationRouterData, WalletData)> for SquareTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: (&types::TokenizationRouterData, WalletData)) -> Result<Self, Self::Error> {
let (_item, wallet_data) = value;
match wallet_data {
WalletData::AmazonPay(_)
| WalletData::ApplePay(_)
| WalletData::GooglePay(_)
| WalletData::BluecodeRedirect {}
| WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Square"),
))?,
}
}
}
#[derive(Debug, Serialize)]
pub struct SquareCardData {
cvv: Secret<String>,
exp_month: Secret<u16>,
exp_year: Secret<u16>,
number: cards::CardNumber,
}
#[derive(Debug, Serialize)]
pub struct SquareTokenizeData {
client_id: Secret<String>,
session_id: Secret<String>,
card_data: SquareCardData,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum SquareTokenRequest {
Card(SquareTokenizeData),
}
impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::BankDebit(bank_debit_data) => {
Self::try_from((item, bank_debit_data))
}
PaymentMethodData::Card(card_data) => Self::try_from((item, card_data)),
PaymentMethodData::Wallet(wallet_data) => Self::try_from((item, wallet_data)),
PaymentMethodData::PayLater(pay_later_data) => Self::try_from((item, pay_later_data)),
PaymentMethodData::GiftCard(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Square"),
))?
}
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SquareSessionResponse {
session_id: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, SquareSessionResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SquareSessionResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::Pending,
session_token: Some(item.response.session_id.clone().expose()),
response: Ok(PaymentsResponseData::SessionTokenResponse {
session_token: item.response.session_id.expose(),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct SquareTokenResponse {
card_nonce: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, SquareTokenResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SquareTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.card_nonce.expose(),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct SquarePaymentsAmountData {
amount: i64,
currency: enums::Currency,
}
#[derive(Debug, Serialize)]
pub struct SquarePaymentsRequestExternalDetails {
source: String,
#[serde(rename = "type")]
source_type: String,
}
#[derive(Debug, Serialize)]
pub struct SquarePaymentsRequest {
amount_money: SquarePaymentsAmountData,
idempotency_key: Secret<String>,
source_id: Secret<String>,
autocomplete: bool,
external_details: SquarePaymentsRequestExternalDetails,
}
impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let autocomplete = item.request.is_auto_capture()?;
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(_) => {
let pm_token = item.get_payment_method_token()?;
Ok(Self {
idempotency_key: Secret::new(item.attempt_id.clone()),
source_id: match pm_token {
PaymentMethodToken::Token(token) => token,
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Square"),
)?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Square"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Square"))?
}
},
amount_money: SquarePaymentsAmountData {
amount: item.request.amount,
currency: item.request.currency,
},
autocomplete,
external_details: SquarePaymentsRequestExternalDetails {
source: "Hyperswitch".to_string(),
source_type: "Card".to_string(),
},
})
}
PaymentMethodData::BankDebit(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Square"),
))?
}
}
}
}
// Auth Struct
pub struct SquareAuthType {
pub(super) api_key: Secret<String>,
pub(super) key1: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for SquareAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1, .. } => Ok(Self {
api_key: api_key.to_owned(),
key1: key1.to_owned(),
}),
ConnectorAuthType::HeaderKey { .. }
| ConnectorAuthType::SignatureKey { .. }
| ConnectorAuthType::MultiAuthKey { .. }
| ConnectorAuthType::CurrencyAuthKey { .. }
| ConnectorAuthType::TemporaryAuth
| ConnectorAuthType::NoKey
| ConnectorAuthType::CertificateAuth { .. } => {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
}
// PaymentsResponse
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum SquarePaymentStatus {
Completed,
Failed,
Approved,
Canceled,
Pending,
}
impl From<SquarePaymentStatus> for enums::AttemptStatus {
fn from(item: SquarePaymentStatus) -> Self {
match item {
SquarePaymentStatus::Completed => Self::Charged,
SquarePaymentStatus::Approved => Self::Authorized,
SquarePaymentStatus::Failed => Self::Failure,
SquarePaymentStatus::Canceled => Self::Voided,
SquarePaymentStatus::Pending => Self::Pending,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct SquarePaymentsResponseDetails {
status: SquarePaymentStatus,
id: String,
amount_money: SquarePaymentsAmountData,
reference_id: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct SquarePaymentsResponse {
payment: SquarePaymentsResponseDetails,
}
impl<F, T> TryFrom<ResponseRouterData<F, SquarePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SquarePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
//Since this try_from is being used in Authorize, Sync, Capture & Void flow. Field amount_captured should only be updated in case of Charged status.
let status = enums::AttemptStatus::from(item.response.payment.status);
let mut amount_captured = None;
if status == enums::AttemptStatus::Charged {
amount_captured = Some(item.response.payment.amount_money.amount)
};
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.payment.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.payment.reference_id,
incremental_authorization_allowed: None,
charges: None,
}),
amount_captured,
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
pub struct SquareRefundRequest {
amount_money: SquarePaymentsAmountData,
idempotency_key: Secret<String>,
payment_id: Secret<String>,
}
impl<F> TryFrom<&types::RefundsRouterData<F>> for SquareRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
Ok(Self {
amount_money: SquarePaymentsAmountData {
amount: item.request.refund_amount,
currency: item.request.currency,
},
idempotency_key: Secret::new(item.request.refund_id.clone()),
payment_id: Secret::new(item.request.connector_transaction_id.clone()),
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Completed,
Failed,
Pending,
Rejected,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Completed => Self::Success,
RefundStatus::Failed | RefundStatus::Rejected => Self::Failure,
RefundStatus::Pending => Self::Pending,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct SquareRefundResponseDetails {
status: RefundStatus,
id: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RefundResponse {
refund: SquareRefundResponseDetails,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund.id,
refund_status: enums::RefundStatus::from(item.response.refund.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund.id,
refund_status: enums::RefundStatus::from(item.response.refund.status),
}),
..item.data
})
}
}
#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct SquareErrorDetails {
pub category: Option<String>,
pub code: Option<String>,
pub detail: Option<String>,
}
#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct SquareErrorResponse {
pub errors: Vec<SquareErrorDetails>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SquareWebhookObject {
Payment(SquarePaymentsResponseDetails),
Refund(SquareRefundResponseDetails),
}
#[derive(Debug, Deserialize)]
pub struct SquareWebhookData {
pub id: String,
pub object: SquareWebhookObject,
}
#[derive(Debug, Deserialize)]
pub struct SquareWebhookBody {
#[serde(rename = "type")]
pub webhook_type: String,
pub data: SquareWebhookData,
}
impl From<SquareWebhookObject> for IncomingWebhookEvent {
fn from(item: SquareWebhookObject) -> Self {
match item {
SquareWebhookObject::Payment(payment_data) => match payment_data.status {
SquarePaymentStatus::Completed => Self::PaymentIntentSuccess,
SquarePaymentStatus::Failed => Self::PaymentIntentFailure,
SquarePaymentStatus::Pending => Self::PaymentIntentProcessing,
SquarePaymentStatus::Approved | SquarePaymentStatus::Canceled => {
Self::EventNotSupported
}
},
SquareWebhookObject::Refund(refund_data) => match refund_data.status {
RefundStatus::Completed => Self::RefundSuccess,
RefundStatus::Failed | RefundStatus::Rejected => Self::RefundFailure,
RefundStatus::Pending => Self::EventNotSupported,
},
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs | crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs | use std::collections::HashMap;
use api_models::payments::PollConfig;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
pii::{self, Email, IpAddress},
types::MinorUnit,
};
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, UpiData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::{Duration, OffsetDateTime};
use crate::{
types::{
CreateOrderResponseRouterData, PaymentsResponseRouterData, RefundsResponseRouterData,
ResponseRouterData,
},
utils::{
get_unimplemented_payment_method_error_message, missing_field_err,
PaymentsAuthorizeRequestData, RouterData as OtherRouterData,
},
};
pub struct RazorpayRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for RazorpayRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
pub const VERSION: i32 = 1;
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayOrderRequest {
pub amount: MinorUnit,
pub currency: enums::Currency,
pub receipt: String,
pub partial_payment: Option<bool>,
pub first_payment_min_amount: Option<MinorUnit>,
pub notes: Option<RazorpayNotes>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum RazorpayNotes {
Map(HashMap<String, String>),
EmptyMap(HashMap<String, String>),
}
impl TryFrom<&RazorpayRouterData<&types::CreateOrderRouterData>> for RazorpayOrderRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RazorpayRouterData<&types::CreateOrderRouterData>,
) -> Result<Self, Self::Error> {
let currency = item.router_data.request.currency;
let receipt = item.router_data.connector_request_reference_id.clone();
Ok(Self {
amount: item.amount,
currency,
receipt,
partial_payment: None,
first_payment_min_amount: None,
notes: None,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RazorpayMetaData {
pub order_id: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayOrderResponse {
pub id: String,
}
impl TryFrom<CreateOrderResponseRouterData<RazorpayOrderResponse>>
for types::CreateOrderRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: CreateOrderResponseRouterData<RazorpayOrderResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::PaymentsCreateOrderResponse {
order_id: item.response.id.clone(),
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct UpiDetails {
flow: UpiFlow,
vpa: Secret<String, pii::UpiVpaMaskingStrategy>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UpiFlow {
Collect,
Intent,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayPaymentsRequest {
amount: MinorUnit,
currency: enums::Currency,
order_id: String,
email: Email,
contact: Secret<String>,
method: RazorpayPaymentMethod,
upi: UpiDetails,
#[serde(skip_serializing_if = "Option::is_none")]
ip: Option<Secret<String, IpAddress>>,
#[serde(skip_serializing_if = "Option::is_none")]
user_agent: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RazorpayPaymentMethod {
Upi,
}
impl TryFrom<&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>> for RazorpayPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RazorpayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payment_router_data = item.router_data;
let router_request = &payment_router_data.request;
let payment_method_data = &router_request.payment_method_data;
let (razorpay_payment_method, upi_details) = match payment_method_data {
PaymentMethodData::Upi(upi_type_data) => match upi_type_data {
UpiData::UpiCollect(upi_collect_data) => {
let vpa_secret = upi_collect_data
.vpa_id
.clone()
.ok_or_else(missing_field_err("payment_method_data.upi.collect.vpa_id"))?;
(
RazorpayPaymentMethod::Upi,
UpiDetails {
flow: UpiFlow::Collect,
vpa: vpa_secret,
},
)
}
UpiData::UpiIntent(_) | UpiData::UpiQr(_) => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("razorpay"),
))?
}
},
_ => Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("razorpay"),
))?,
};
let contact_number = item.router_data.get_billing_phone_number()?;
let order_id = router_request.get_order_id()?;
let email = item.router_data.get_billing_email()?;
let ip = router_request.get_ip_address_as_optional();
let user_agent = router_request.get_optional_user_agent();
Ok(Self {
amount: item.amount,
currency: router_request.currency,
order_id,
email,
contact: contact_number,
method: razorpay_payment_method,
upi: upi_details,
ip,
user_agent,
})
}
}
pub struct RazorpayAuthType {
pub(super) razorpay_id: Secret<String>,
pub(super) razorpay_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for RazorpayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
razorpay_id: api_key.to_owned(),
razorpay_secret: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NextAction {
pub action: String,
pub url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RazorpayPaymentsResponse {
pub razorpay_payment_id: String,
}
impl TryFrom<PaymentsResponseRouterData<RazorpayPaymentsResponse>>
for types::PaymentsAuthorizeRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<RazorpayPaymentsResponse>,
) -> Result<Self, Self::Error> {
let connector_metadata = get_wait_screen_metadata()?;
let order_id = item.data.request.get_order_id()?;
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.razorpay_payment_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(order_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WaitScreenData {
display_from_timestamp: i128,
display_to_timestamp: Option<i128>,
poll_config: Option<PollConfig>,
}
pub fn get_wait_screen_metadata() -> CustomResult<Option<serde_json::Value>, errors::ConnectorError>
{
let current_time = OffsetDateTime::now_utc().unix_timestamp_nanos();
Ok(Some(serde_json::json!(WaitScreenData {
display_from_timestamp: current_time,
display_to_timestamp: Some(current_time + Duration::minutes(5).whole_nanoseconds()),
poll_config: Some(PollConfig {
delay_in_secs: 5,
frequency: 5,
}),
})))
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RazorpaySyncResponse {
items: Vec<RazorpaySyncItem>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RazorpaySyncItem {
id: String,
status: RazorpayStatus,
}
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RazorpayStatus {
Created,
Authorized,
Captured,
Refunded,
Failed,
}
fn get_psync_razorpay_payment_status(razorpay_status: RazorpayStatus) -> enums::AttemptStatus {
match razorpay_status {
RazorpayStatus::Created => enums::AttemptStatus::Pending,
RazorpayStatus::Authorized => enums::AttemptStatus::Authorized,
RazorpayStatus::Captured | RazorpayStatus::Refunded => enums::AttemptStatus::Charged,
RazorpayStatus::Failed => enums::AttemptStatus::Failure,
}
}
impl<F, T> TryFrom<ResponseRouterData<F, RazorpaySyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, RazorpaySyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = match item.response.items.last() {
Some(last_item) => {
let razorpay_status = last_item.status;
get_psync_razorpay_payment_status(razorpay_status)
}
None => item.data.status,
};
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayRefundRequest {
pub amount: MinorUnit,
}
impl<F> TryFrom<&RazorpayRouterData<&types::RefundsRouterData<F>>> for RazorpayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RazorpayRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayRefundResponse {
pub id: String,
pub status: RazorpayRefundStatus,
}
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RazorpayRefundStatus {
Created,
Processed,
Failed,
Pending,
}
impl From<RazorpayRefundStatus> for enums::RefundStatus {
fn from(item: RazorpayRefundStatus) -> Self {
match item {
RazorpayRefundStatus::Processed => Self::Success,
RazorpayRefundStatus::Pending | RazorpayRefundStatus::Created => Self::Pending,
RazorpayRefundStatus::Failed => Self::Failure,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, RazorpayRefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RazorpayRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
// This code can be used later when Razorpay webhooks are implemented
// #[derive(Debug, Deserialize, Serialize)]
// #[serde(untagged)]
// pub enum RazorpayPaymentsResponseData {
// PsyncResponse(RazorpaySyncResponse),
// WebhookResponse(WebhookPaymentEntity),
// }
// impl From<RazorpayWebhookPaymentStatus> for enums::AttemptStatus {
// fn from(status: RazorpayWebhookPaymentStatus) -> Self {
// match status {
// RazorpayWebhookPaymentStatus::Authorized => Self::Authorized,
// RazorpayWebhookPaymentStatus::Captured => Self::Charged,
// RazorpayWebhookPaymentStatus::Failed => Self::Failure,
// }
// }
// }
// impl<F, T> TryFrom<ResponseRouterData<F, RazorpayPaymentsResponseData, T, PaymentsResponseData>>
// for RouterData<F, T, PaymentsResponseData>
// {
// type Error = error_stack::Report<errors::ConnectorError>;
// fn try_from(
// item: ResponseRouterData<F, RazorpayPaymentsResponseData, T, PaymentsResponseData>,
// ) -> Result<Self, Self::Error> {
// match item.response {
// RazorpayPaymentsResponseData::PsyncResponse(sync_response) => {
// let status = get_psync_razorpay_payment_status(sync_response.status.clone());
// Ok(Self {
// status,
// response: if is_payment_failure(status) {
// Err(RouterErrorResponse {
// code: sync_response.status.clone().to_string(),
// message: sync_response.status.clone().to_string(),
// reason: Some(sync_response.status.to_string()),
// status_code: item.http_code,
// attempt_status: Some(status),
// connector_transaction_id: None,
// network_advice_code: None,
// network_decline_code: None,
// network_error_message: None,
// })
// } else {
// Ok(PaymentsResponseData::TransactionResponse {
// resource_id: ResponseId::NoResponseId,
// redirection_data: Box::new(None),
// mandate_reference: Box::new(None),
// connector_metadata: None,
// network_txn_id: None,
// connector_response_reference_id: None,
// incremental_authorization_allowed: None,
// charges: None,
// })
// },
// ..item.data
// })
// }
// RazorpayPaymentsResponseData::WebhookResponse(webhook_payment_entity) => {
// let razorpay_status = webhook_payment_entity.status;
// let status = enums::AttemptStatus::from(razorpay_status.clone());
// Ok(Self {
// status,
// response: if is_payment_failure(status) {
// Err(RouterErrorResponse {
// code: razorpay_status.clone().to_string(),
// message: razorpay_status.clone().to_string(),
// reason: Some(razorpay_status.to_string()),
// status_code: item.http_code,
// attempt_status: Some(status),
// connector_transaction_id: Some(webhook_payment_entity.id.clone()),
// network_advice_code: None,
// network_decline_code: None,
// network_error_message: None,
// })
// } else {
// Ok(PaymentsResponseData::TransactionResponse {
// resource_id: ResponseId::ConnectorTransactionId(
// webhook_payment_entity.id.clone(),
// ),
// redirection_data: Box::new(None),
// mandate_reference: Box::new(None),
// connector_metadata: None,
// network_txn_id: None,
// connector_response_reference_id: Some(webhook_payment_entity.id),
// incremental_authorization_allowed: None,
// charges: None,
// })
// },
// ..item.data
// })
// }
// }
// }
// }
impl TryFrom<RefundsResponseRouterData<RSync, RazorpayRefundResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RazorpayRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ErrorResponse {
RazorpayErrorResponse(RazorpayErrorResponse),
RazorpayStringError(String),
RazorpayError(RazorpayErrorMessage),
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayErrorMessage {
pub message: String,
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayErrorResponse {
pub error: RazorpayError,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayError {
pub code: String,
pub description: String,
pub source: Option<String>,
pub step: Option<String>,
pub reason: Option<String>,
pub metadata: Option<Metadata>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Metadata {
pub order_id: Option<String>,
}
// This code can be used later when Razorpay webhooks are implemented
// #[derive(Debug, Serialize, Deserialize)]
// pub struct RazorpayWebhookPayload {
// pub event: RazorpayWebhookEventType,
// pub payload: RazorpayWebhookPayloadBody,
// }
// #[derive(Debug, Serialize, Deserialize)]
// #[serde(untagged)]
// pub enum RazorpayWebhookEventType {
// Payments(RazorpayWebhookPaymentEvent),
// Refunds(RazorpayWebhookRefundEvent),
// }
// #[derive(Debug, Serialize, Deserialize)]
// pub struct RazorpayWebhookPayloadBody {
// pub refund: Option<RazorpayRefundWebhookPayload>,
// pub payment: RazorpayPaymentWebhookPayload,
// }
// #[derive(Debug, Serialize, Deserialize)]
// pub struct RazorpayPaymentWebhookPayload {
// pub entity: WebhookPaymentEntity,
// }
// #[derive(Debug, Serialize, Deserialize)]
// pub struct RazorpayRefundWebhookPayload {
// pub entity: WebhookRefundEntity,
// }
// #[derive(Debug, Serialize, Deserialize)]
// pub struct WebhookRefundEntity {
// pub id: String,
// pub status: RazorpayWebhookRefundEvent,
// }
// #[derive(Debug, Serialize, Eq, PartialEq, Deserialize)]
// pub enum RazorpayWebhookRefundEvent {
// #[serde(rename = "refund.created")]
// Created,
// #[serde(rename = "refund.processed")]
// Processed,
// #[serde(rename = "refund.failed")]
// Failed,
// #[serde(rename = "refund.speed_change")]
// SpeedChange,
// }
// #[derive(Debug, Serialize, Deserialize)]
// pub struct WebhookPaymentEntity {
// pub id: String,
// pub status: RazorpayWebhookPaymentStatus,
// }
// #[derive(Debug, Serialize, Eq, PartialEq, Clone, Deserialize)]
// #[serde(rename_all = "snake_case")]
// pub enum RazorpayWebhookPaymentStatus {
// Authorized,
// Captured,
// Failed,
// }
// #[derive(Debug, Serialize, Eq, PartialEq, Deserialize)]
// pub enum RazorpayWebhookPaymentEvent {
// #[serde(rename = "payment.authorized")]
// Authorized,
// #[serde(rename = "payment.captured")]
// Captured,
// #[serde(rename = "payment.failed")]
// Failed,
// }
// impl TryFrom<RazorpayWebhookEventType> for api_models::webhooks::IncomingWebhookEvent {
// type Error = errors::ConnectorError;
// fn try_from(event_type: RazorpayWebhookEventType) -> Result<Self, Self::Error> {
// match event_type {
// RazorpayWebhookEventType::Payments(payment_event) => match payment_event {
// RazorpayWebhookPaymentEvent::Authorized => {
// Ok(Self::PaymentIntentAuthorizationSuccess)
// }
// RazorpayWebhookPaymentEvent::Captured => Ok(Self::PaymentIntentSuccess),
// RazorpayWebhookPaymentEvent::Failed => Ok(Self::PaymentIntentFailure),
// },
// RazorpayWebhookEventType::Refunds(refund_event) => match refund_event {
// RazorpayWebhookRefundEvent::Processed => Ok(Self::RefundSuccess),
// RazorpayWebhookRefundEvent::Created => Ok(Self::RefundSuccess),
// RazorpayWebhookRefundEvent::Failed => Ok(Self::RefundFailure),
// RazorpayWebhookRefundEvent::SpeedChange => Ok(Self::EventNotSupported),
// },
// }
// }
// }
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs | crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs | use common_enums::{enums, CaptureMethod, FutureUsage, GooglePayCardFundingSource, PaymentChannel};
use common_types::{
payments::{
ApplePayPaymentData, ApplePayPredecryptData, BillingDescriptor, GPayPredecryptData,
GpayTokenizationData,
},
primitive_wrappers,
};
use common_utils::{
crypto::{self, GenerateDigest},
date_time,
ext_traits::Encode,
fp_utils,
id_type::CustomerId,
pii::{self, Email, IpAddress},
request::Method,
types::{FloatMajorUnit, MinorUnit, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
address::Address,
payment_method_data::{
self, ApplePayWalletData, BankRedirectData, CardDetailsForNetworkTransactionId,
GooglePayWalletData, PayLaterData, PaymentMethodData, WalletData,
},
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ErrorResponse, L2L3Data, PaymentMethodToken, RouterData,
},
router_flow_types::{
refunds::{Execute, RSync},
Authorize, Capture, CompleteAuthorize, PSync, PostCaptureVoid, SetupMandate, Void,
},
router_request_types::{
authentication::MessageExtensionAttribute, AuthenticationData, BrowserInformation,
CompleteAuthorizeData, PaymentsAuthorizeData, ResponseId, SetupMandateRequestData,
},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types,
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::payouts::PoFulfill, router_response_types::PayoutsResponseData,
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors::{self},
};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
#[cfg(feature = "payouts")]
use crate::{types::PayoutsResponseRouterData, utils::PayoutsData as _};
use crate::{
types::{
PaymentsPreAuthenticateResponseRouterData, PaymentsPreprocessingResponseRouterData,
RefundsResponseRouterData, ResponseRouterData,
},
utils::{
self, convert_amount, missing_field_err, AddressData, AddressDetailsData,
BrowserInformationData, CardData, ForeignTryFrom, PaymentsAuthorizeRequestData,
PaymentsCancelRequestData, PaymentsCompleteAuthorizeRequestData,
PaymentsPreAuthenticateRequestData, PaymentsPreProcessingRequestData,
PaymentsSetupMandateRequestData, RouterData as _,
},
};
fn to_boolean(string: String) -> bool {
let str = string.as_str();
matches!(str, "true" | "yes")
}
// The dimensions of the challenge window for full screen.
const CHALLENGE_WINDOW_SIZE: &str = "05";
// The challenge preference for the challenge flow.
const CHALLENGE_PREFERENCE: &str = "01";
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct NuveiThreeDSInitPaymentRequest {
pub session_token: Secret<String>,
pub merchant_id: Secret<String>,
pub merchant_site_id: Secret<String>,
pub client_unique_id: String,
pub client_request_id: Secret<String>,
pub amount: StringMajorUnit,
pub payment_option: CardPaymentOption,
pub device_details: DeviceDetails,
pub currency: enums::Currency,
pub user_token_id: Option<CustomerId>,
pub billing_address: Option<BillingAddress>,
pub url_details: UrlDetails,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardPaymentOption {
pub card: Card,
}
impl TryFrom<(&types::PaymentsPreAuthenticateRouterData, String)>
for NuveiThreeDSInitPaymentRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, session_token): (&types::PaymentsPreAuthenticateRouterData, String),
) -> Result<Self, Self::Error> {
let currency = item.request.get_currency()?;
let connector_auth: NuveiAuthType = NuveiAuthType::try_from(&item.connector_auth_type)?;
let amount = item.request.get_minor_amount()?.to_nuvei_amount(currency)?;
let payment_method_data = item.request.get_payment_method_data()?.clone();
let card = match payment_method_data {
PaymentMethodData::Card(card) => card,
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nuvei"),
))?,
};
let browser_info = item
.request
.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))?;
let return_url = item
.request
.router_return_url
.clone()
.ok_or_else(missing_field_err("return_url"))?;
let billing_address = item.get_billing().ok().map(|billing| billing.into());
Ok(Self {
session_token: session_token.into(),
merchant_id: connector_auth.merchant_id,
merchant_site_id: connector_auth.merchant_site_id,
client_request_id: item.connector_request_reference_id.clone().into(),
client_unique_id: item.connector_request_reference_id.clone(),
amount,
currency,
payment_option: CardPaymentOption {
card: Card {
card_number: Some(card.card_number),
card_holder_name: item.get_optional_billing_full_name(),
expiration_month: Some(card.card_exp_month),
expiration_year: Some(card.card_exp_year),
cvv: Some(card.card_cvc),
..Default::default()
},
},
device_details: DeviceDetails {
ip_address: browser_info.get_ip_address()?,
},
user_token_id: item.customer_id.clone(),
billing_address,
url_details: UrlDetails {
success_url: return_url.clone(),
failure_url: return_url.clone(),
pending_url: return_url,
},
})
}
}
impl TryFrom<(&types::PaymentsPreProcessingRouterData, String)> for NuveiThreeDSInitPaymentRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, session_token): (&types::PaymentsPreProcessingRouterData, String),
) -> Result<Self, Self::Error> {
let currency = item.request.get_currency()?;
let connector_auth: NuveiAuthType = NuveiAuthType::try_from(&item.connector_auth_type)?;
let amount = item.request.get_minor_amount()?.to_nuvei_amount(currency)?;
let payment_method_data = item.request.get_payment_method_data()?.clone();
let card = match payment_method_data {
PaymentMethodData::Card(card) => card,
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nuvei"),
))?,
};
let browser_info = item
.request
.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))?;
let return_url = item
.request
.router_return_url
.clone()
.ok_or_else(missing_field_err("return_url"))?;
let billing_address = item.get_billing().ok().map(|billing| billing.into());
Ok(Self {
session_token: session_token.into(),
merchant_id: connector_auth.merchant_id,
merchant_site_id: connector_auth.merchant_site_id,
client_request_id: item.connector_request_reference_id.clone().into(),
client_unique_id: item.connector_request_reference_id.clone(),
amount,
currency,
payment_option: CardPaymentOption {
card: Card {
card_number: Some(card.card_number),
card_holder_name: item.get_optional_billing_full_name(),
expiration_month: Some(card.card_exp_month),
expiration_year: Some(card.card_exp_year),
cvv: Some(card.card_cvc),
..Default::default()
},
},
device_details: DeviceDetails {
ip_address: browser_info.get_ip_address()?,
},
user_token_id: item.customer_id.clone(),
billing_address,
url_details: UrlDetails {
success_url: return_url.clone(),
failure_url: return_url.clone(),
pending_url: return_url,
},
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NuveiSessionRequest {
pub merchant_id: Secret<String>,
pub merchant_site_id: Secret<String>,
pub client_request_id: String,
pub time_stamp: date_time::DateTime<date_time::YYYYMMDDHHmmss>,
pub checksum: Secret<String>,
}
impl TryFrom<&types::PaymentsAuthorizeSessionTokenRouterData> for NuveiSessionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &types::PaymentsAuthorizeSessionTokenRouterData,
) -> Result<Self, Self::Error> {
let connector_meta: NuveiAuthType = NuveiAuthType::try_from(&item.connector_auth_type)?;
let merchant_id = connector_meta.merchant_id;
let merchant_site_id = connector_meta.merchant_site_id;
let client_request_id = item.connector_request_reference_id.clone();
let time_stamp = date_time::DateTime::<date_time::YYYYMMDDHHmmss>::from(date_time::now());
let merchant_secret = connector_meta.merchant_secret;
Ok(Self {
merchant_id: merchant_id.clone(),
merchant_site_id: merchant_site_id.clone(),
client_request_id: client_request_id.clone(),
time_stamp: time_stamp.clone(),
checksum: Secret::new(encode_payload(&[
merchant_id.peek(),
merchant_site_id.peek(),
&client_request_id,
&time_stamp.to_string(),
merchant_secret.peek(),
])?),
})
}
}
#[derive(Debug, Serialize, Default, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NuveiSessionResponse {
pub session_token: Secret<String>,
pub status: String,
pub err_code: i64,
pub reason: String,
pub merchant_id: Secret<String>,
pub merchant_site_id: Secret<String>,
pub client_request_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, NuveiSessionResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, NuveiSessionResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::Pending,
session_token: Some(item.response.session_token.clone().expose()),
response: Ok(PaymentsResponseData::SessionTokenResponse {
session_token: item.response.session_token.expose(),
}),
..item.data
})
}
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct NuveiPaymentBaseRequest {
pub time_stamp: String,
pub session_token: Secret<String>,
pub merchant_id: Secret<String>,
pub merchant_site_id: Secret<String>,
pub client_request_id: Secret<String>,
pub client_unique_id: String,
pub amount: StringMajorUnit,
pub currency: enums::Currency,
pub checksum: Secret<String>,
pub transaction_type: TransactionType,
pub dynamic_descriptor: Option<NuveiDynamicDescriptor>,
pub is_partial_approval: Option<PartialApprovalFlag>,
pub items: Option<Vec<NuveiItem>>,
pub amount_details: Option<NuveiAmountDetails>,
pub user_token_id: Option<CustomerId>,
pub is_rebilling: Option<IsRebilling>,
}
impl<F, Req> TryFrom<(&RouterData<F, Req, PaymentsResponseData>, String)>
for NuveiPaymentBaseRequest
where
F: std::fmt::Debug,
Req: NuveiAuthorizePreprocessingCommon + std::fmt::Debug,
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (&RouterData<F, Req, PaymentsResponseData>, String),
) -> Result<Self, Self::Error> {
let (item, session_token) = value;
let currency = item.request.get_currency();
let amount = item
.request
.get_minor_amount_required()?
.to_nuvei_amount(currency)?;
fp_utils::when(session_token.is_empty(), || {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "session_token",
})
})?;
let auth = NuveiAuthType::try_from(&item.connector_auth_type)?;
let client_request_id = item.connector_request_reference_id.clone();
let time_stamp =
date_time::format_date(date_time::now(), date_time::DateFormat::YYYYMMDDHHmmss)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let (is_rebilling, user_token_id) = match (
item.request.get_payment_method_data_required()?,
item.request.is_customer_initiated_mandate_payment(),
) {
(PaymentMethodData::Card(_) | PaymentMethodData::Wallet(_), true) => {
(Some(IsRebilling::False), item.customer_id.clone())
}
(
PaymentMethodData::MandatePayment
| PaymentMethodData::CardDetailsForNetworkTransactionId(_),
_,
) => (
Some(IsRebilling::True),
Some(
item.customer_id
.clone()
.ok_or_else(missing_field_err("customer_id"))?,
),
),
_ => (None, None),
};
Ok(Self {
merchant_id: auth.merchant_id.clone(),
merchant_site_id: auth.merchant_site_id.clone(),
client_request_id: Secret::new(client_request_id.clone()),
client_unique_id: client_request_id.clone(),
time_stamp: time_stamp.clone(),
session_token: Secret::new(session_token),
user_token_id,
is_rebilling,
amount: amount.clone(),
currency,
dynamic_descriptor: item.request.get_dynamic_descriptor()?,
is_partial_approval: item.request.get_is_partial_approval(),
items: get_l2_l3_items(&item.l2_l3_data, currency)?,
amount_details: get_amount_details(&item.l2_l3_data, currency)?,
transaction_type: TransactionType::get_from_capture_method_and_amount_string(
item.request.get_capture_method().unwrap_or_default(),
&amount.get_amount_as_string(),
),
checksum: Secret::new(
encode_payload(&[
auth.merchant_id.peek(),
auth.merchant_site_id.peek(),
&client_request_id,
&amount.get_amount_as_string(),
¤cy.to_string(),
&time_stamp,
auth.merchant_secret.peek(),
])
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
),
})
}
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct NuveiPaymentsRequest {
#[serde(flatten)]
pub base: NuveiPaymentBaseRequest,
pub payment_option: PaymentOption,
pub device_details: DeviceDetails,
pub billing_address: Option<BillingAddress>,
pub shipping_address: Option<ShippingAddress>,
pub related_transaction_id: Option<String>,
pub external_scheme_details: Option<ExternalSchemeDetails>,
pub is_moto: Option<bool>,
pub url_details: Option<UrlDetails>,
}
/// Handles payment request for capture, void and refund flows
#[derive(Debug, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct NuveiPaymentFlowRequest {
pub time_stamp: String,
pub merchant_id: Secret<String>,
pub merchant_site_id: Secret<String>,
pub client_request_id: String,
pub client_unique_id: String,
pub amount: StringMajorUnit,
pub currency: enums::Currency,
pub related_transaction_id: Option<String>,
pub checksum: Secret<String>,
}
#[derive(Debug, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct NuveiPaymentSyncRequest {
pub merchant_id: Secret<String>,
pub merchant_site_id: Secret<String>,
pub client_unique_id: String,
pub time_stamp: String,
pub checksum: Secret<String>,
pub transaction_id: String,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub enum TransactionType {
Auth,
#[default]
Sale,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentOption {
pub card: Option<Card>,
pub redirect_url: Option<Url>,
pub user_payment_option_id: Option<String>,
pub alternative_payment_method: Option<AlternativePaymentMethod>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
pub card_number: Option<cards::CardNumber>,
pub card_holder_name: Option<Secret<String>>,
pub expiration_month: Option<Secret<String>>,
pub expiration_year: Option<Secret<String>>,
#[serde(rename = "CVV")]
pub cvv: Option<Secret<String>>,
pub three_d: Option<ThreeD>,
pub cc_card_number: Option<Secret<String>>,
pub bin: Option<Secret<String>>,
pub last4_digits: Option<Secret<String>>,
pub cc_exp_month: Option<Secret<String>>,
pub cc_exp_year: Option<Secret<String>>,
pub acquirer_id: Option<Secret<String>>,
pub cvv2_reply: Option<String>,
pub avs_code: Option<String>,
pub card_type: Option<String>,
pub brand: Option<String>,
pub issuer_bank_name: Option<String>,
pub issuer_country: Option<String>,
pub external_token: Option<ExternalToken>,
pub stored_credentials: Option<StoredCredentialMode>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExternalToken {
pub external_token_provider: ExternalTokenProvider,
pub mobile_token: Option<Secret<String>>,
pub cryptogram: Option<Secret<String>>,
pub eci_provider: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum ExternalTokenProvider {
#[default]
GooglePay,
ApplePay,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExternalMpi {
pub eci: Option<String>,
pub cavv: Secret<String>,
#[serde(rename = "dsTransID")]
pub ds_trans_id: Option<String>,
pub challenge_preference: Option<String>,
pub exemption_request_reason: Option<String>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeD {
pub method_completion_ind: Option<MethodCompletion>,
pub browser_details: Option<BrowserDetails>,
#[serde(rename = "notificationURL")]
pub notification_url: Option<String>,
#[serde(rename = "merchantURL")]
pub merchant_url: Option<String>,
pub acs_url: Option<String>,
pub c_req: Option<Secret<String>>,
pub external_mpi: Option<ExternalMpi>,
pub transaction_id: Option<String>,
pub platform_type: Option<PlatformType>,
pub v2supported: Option<String>,
pub v2_additional_params: Option<V2AdditionalParams>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub enum MethodCompletion {
#[serde(rename = "Y")]
Success,
#[serde(rename = "N")]
Failure,
#[serde(rename = "U")]
#[default]
Unavailable,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub enum PlatformType {
#[serde(rename = "01")]
App,
#[serde(rename = "02")]
#[default]
Browser,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BrowserDetails {
pub accept_header: String,
pub ip: Secret<String, IpAddress>,
pub java_enabled: String,
pub java_script_enabled: String,
pub language: String,
pub color_depth: u8,
pub screen_height: u32,
pub screen_width: u32,
pub time_zone: i32,
pub user_agent: String,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct V2AdditionalParams {
pub challenge_window_size: Option<String>,
/// Recurring Expiry in format YYYYMMDD. REQUIRED if isRebilling = 0, We recommend setting rebillExpiry to a value of no more than 5 years from the date of the initial transaction processing date.
pub rebill_expiry: Option<String>,
/// Recurring Frequency in days
pub rebill_frequency: Option<String>,
pub challenge_preference: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeviceDetails {
pub ip_address: Secret<String, IpAddress>,
}
impl TransactionType {
fn get_from_capture_method_and_amount_string(
capture_method: CaptureMethod,
amount: &str,
) -> Self {
let amount_value = amount.parse::<f64>();
if capture_method == CaptureMethod::Manual || amount_value == Ok(0.0) {
Self::Auth
} else {
Self::Sale
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NuveiRedirectionResponse {
pub cres: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NuveiACSResponse {
#[serde(rename = "threeDSServerTransID")]
pub three_ds_server_trans_id: Secret<String>,
#[serde(rename = "acsTransID")]
pub acs_trans_id: Secret<String>,
pub message_type: String,
pub message_version: String,
pub trans_status: Option<LiabilityShift>,
pub message_extension: Option<Vec<MessageExtensionAttribute>>,
pub acs_signed_content: Option<serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum LiabilityShift {
#[serde(rename = "Y", alias = "1", alias = "y")]
Success,
#[serde(rename = "N", alias = "0", alias = "n")]
Failed,
}
pub fn encode_payload(
payload: &[&str],
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
let data = payload.join("");
let digest = crypto::Sha256
.generate_digest(data.as_bytes())
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("error encoding nuvie payload")?;
Ok(hex::encode(digest))
}
impl From<NuveiPaymentSyncResponse> for NuveiTransactionSyncResponse {
fn from(value: NuveiPaymentSyncResponse) -> Self {
match value {
NuveiPaymentSyncResponse::NuveiDmn(payment_dmn_notification) => {
Self::from(*payment_dmn_notification)
}
NuveiPaymentSyncResponse::NuveiApi(nuvei_transaction_sync_response) => {
*nuvei_transaction_sync_response
}
}
}
}
#[derive(Debug)]
pub struct NuveiCardDetails {
card: payment_method_data::Card,
three_d: Option<ThreeD>,
card_holder_name: Option<Secret<String>>,
stored_credentials: Option<StoredCredentialMode>,
}
// Define new structs with camelCase serialization
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
struct GooglePayCamelCase {
pm_type: Secret<String>,
description: Secret<String>,
info: GooglePayInfoCamelCase,
tokenization_data: GooglePayTokenizationDataCamelCase,
}
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
struct GooglePayInfoCamelCase {
card_network: Secret<String>,
card_details: Secret<String>,
assurance_details: Option<GooglePayAssuranceDetailsCamelCase>,
card_funding_source: Option<GooglePayCardFundingSource>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExternalSchemeDetails {
transaction_id: Secret<String>, // This is sensitive information
brand: Option<NuveiCardType>,
}
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
struct GooglePayAssuranceDetailsCamelCase {
card_holder_authenticated: bool,
account_verified: bool,
}
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
struct GooglePayTokenizationDataCamelCase {
#[serde(rename = "type")]
token_type: Secret<String>,
token: Secret<String>,
}
// Define ApplePay structs with camelCase serialization
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
struct ApplePayCamelCase {
payment_data: Secret<String>,
payment_method: ApplePayPaymentMethodCamelCase,
transaction_identifier: Secret<String>,
}
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
struct ApplePayPaymentMethodCamelCase {
display_name: Secret<String>,
network: Secret<String>,
#[serde(rename = "type")]
pm_type: Secret<String>,
}
fn get_google_pay_decrypt_data(
predecrypt_data: &GPayPredecryptData,
brand: Option<String>,
) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> {
Ok(NuveiPaymentsRequest {
payment_option: PaymentOption {
card: Some(Card {
brand,
card_number: Some(predecrypt_data.application_primary_account_number.clone()),
last4_digits: Some(Secret::new(
predecrypt_data
.application_primary_account_number
.clone()
.get_last4(),
)),
expiration_month: Some(predecrypt_data.card_exp_month.clone()),
expiration_year: Some(predecrypt_data.card_exp_year.clone()),
external_token: Some(ExternalToken {
external_token_provider: ExternalTokenProvider::GooglePay,
mobile_token: None,
cryptogram: predecrypt_data.cryptogram.clone(),
eci_provider: predecrypt_data.eci_indicator.clone(),
}),
..Default::default()
}),
..Default::default()
},
..Default::default()
})
}
fn get_googlepay_info<F, Req>(
item: &RouterData<F, Req, PaymentsResponseData>,
gpay_data: &GooglePayWalletData,
) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>>
where
Req: NuveiAuthorizePreprocessingCommon,
{
if let Ok(PaymentMethodToken::GooglePayDecrypt(ref token)) = item.get_payment_method_token() {
return get_google_pay_decrypt_data(token, Some(gpay_data.info.card_network.clone()));
}
match &gpay_data.tokenization_data {
GpayTokenizationData::Decrypted(gpay_predecrypt_data) => get_google_pay_decrypt_data(
gpay_predecrypt_data,
Some(gpay_data.info.card_network.clone()),
),
GpayTokenizationData::Encrypted(ref encrypted_data) => Ok(NuveiPaymentsRequest {
payment_option: PaymentOption {
card: Some(Card {
external_token: Some(ExternalToken {
external_token_provider: ExternalTokenProvider::GooglePay,
mobile_token: {
let (token_type, token) = (
encrypted_data.token_type.clone(),
encrypted_data.token.clone(),
);
let google_pay: GooglePayCamelCase = GooglePayCamelCase {
pm_type: Secret::new(gpay_data.pm_type.clone()),
description: Secret::new(gpay_data.description.clone()),
info: GooglePayInfoCamelCase {
card_network: Secret::new(gpay_data.info.card_network.clone()),
card_details: Secret::new(gpay_data.info.card_details.clone()),
assurance_details: gpay_data
.info
.assurance_details
.as_ref()
.map(|details| GooglePayAssuranceDetailsCamelCase {
card_holder_authenticated: details
.card_holder_authenticated,
account_verified: details.account_verified,
}),
card_funding_source: gpay_data.info.card_funding_source.clone(),
},
tokenization_data: GooglePayTokenizationDataCamelCase {
token_type: token_type.into(),
token: token.into(),
},
};
Some(Secret::new(
google_pay.encode_to_string_of_json().change_context(
errors::ConnectorError::RequestEncodingFailed,
)?,
))
},
cryptogram: None,
eci_provider: None,
}),
..Default::default()
}),
..Default::default()
},
..Default::default()
}),
}
}
fn get_apple_pay_decrypt_data(
apple_pay_predecrypt_data: &ApplePayPredecryptData,
network: String,
) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> {
Ok(NuveiPaymentsRequest {
payment_option: PaymentOption {
card: Some(Card {
brand: Some(network),
card_number: Some(
apple_pay_predecrypt_data
.application_primary_account_number
.clone(),
),
last4_digits: Some(Secret::new(
apple_pay_predecrypt_data
.application_primary_account_number
.get_last4(),
)),
expiration_month: Some(
apple_pay_predecrypt_data
.application_expiration_month
.clone(),
),
expiration_year: Some(
apple_pay_predecrypt_data
.application_expiration_year
.clone(),
),
external_token: Some(ExternalToken {
external_token_provider: ExternalTokenProvider::ApplePay,
mobile_token: None,
cryptogram: Some(
apple_pay_predecrypt_data
.payment_data
.online_payment_cryptogram
.clone(),
),
eci_provider: apple_pay_predecrypt_data.payment_data.eci_indicator.clone(),
}),
..Default::default()
}),
..Default::default()
},
..Default::default()
})
}
fn get_applepay_info<F, Req>(
item: &RouterData<F, Req, PaymentsResponseData>,
apple_pay_data: &ApplePayWalletData,
) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>>
where
Req: NuveiAuthorizePreprocessingCommon,
{
if let Ok(PaymentMethodToken::ApplePayDecrypt(ref token)) = item.get_payment_method_token() {
return get_apple_pay_decrypt_data(token, apple_pay_data.payment_method.network.clone());
}
match apple_pay_data.payment_data {
ApplePayPaymentData::Decrypted(ref apple_pay_predecrypt_data) => {
get_apple_pay_decrypt_data(
apple_pay_predecrypt_data,
apple_pay_data.payment_method.network.clone(),
)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs | crates/hyperswitch_connectors/src/connectors/bitpay/transformers.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,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs | crates/hyperswitch_connectors/src/connectors/santander/transformers.rs | use std::collections::HashMap;
use api_models::payments::{QrCodeInformation, VoucherNextStepData};
use common_enums::{enums, AttemptStatus};
use common_utils::{
errors::CustomResult,
ext_traits::{ByteSliceExt, Encode},
id_type,
request::Method,
types::{AmountConvertor, FloatMajorUnit, StringMajorUnit, StringMajorUnitForConnector},
};
use crc::{Algorithm, Crc};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankTransferData, PaymentMethodData, VoucherData},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use time::OffsetDateTime;
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self as connector_utils, QrImage, RouterData as _},
};
const CRC_16_CCITT_FALSE: Algorithm<u16> = Algorithm {
width: 16,
poly: 0x1021,
init: 0xFFFF,
refin: false,
refout: false,
xorout: 0x0000,
check: 0x29B1,
residue: 0x0000,
};
type Error = error_stack::Report<errors::ConnectorError>;
pub struct SantanderRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for SantanderRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SantanderMetadataObject {
pub pix_key: Secret<String>,
pub expiration_time: i32,
pub cpf: Secret<String>,
pub merchant_city: String,
pub merchant_name: String,
pub workspace_id: String,
pub covenant_code: String, // max_size : 9
}
impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for SantanderMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
meta_data: &Option<common_utils::pii::SecretSerdeValue>,
) -> Result<Self, Self::Error> {
let metadata = connector_utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
pub fn format_emv_field(id: &str, value: &str) -> String {
format!("{id}{:02}{value}", value.len())
}
pub fn generate_emv_string(
payload_url: &str,
merchant_name: &str,
merchant_city: &str,
amount: Option<&str>,
txid: Option<&str>,
) -> String {
let mut emv = String::new();
// 00: Payload Format Indicator
emv += &format_emv_field("00", "01");
// 01: Point of Initiation Method (dynamic)
emv += &format_emv_field("01", "12");
// 26: Merchant Account Info
let gui = format_emv_field("00", "br.gov.bcb.pix");
let url = format_emv_field("25", payload_url);
let merchant_account_info = format_emv_field("26", &(gui + &url));
emv += &merchant_account_info;
// 52: Merchant Category Code (0000)
emv += &format_emv_field("52", "0000");
// 53: Currency Code (986 for BRL)
emv += &format_emv_field("53", "986");
// 54: Amount (optional)
if let Some(amount) = amount {
emv += &format_emv_field("54", amount);
}
// 58: Country Code (BR)
emv += &format_emv_field("58", "BR");
// 59: Merchant Name
emv += &format_emv_field("59", merchant_name);
// 60: Merchant City
emv += &format_emv_field("60", merchant_city);
// 62: Additional Data Field Template (optional TXID)
if let Some(txid) = txid {
let reference = format_emv_field("05", txid);
emv += &format_emv_field("62", &reference);
}
// Placeholder for CRC (we need to calculate this last)
emv += "6304";
// Compute CRC16-CCITT (False) checksum
let crc = Crc::<u16>::new(&CRC_16_CCITT_FALSE);
let checksum = crc.checksum(emv.as_bytes());
emv += &format!("{checksum:04X}");
emv
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SantanderAuthUpdateResponse {
#[serde(rename = "camelCase")]
pub refresh_url: String,
pub token_type: String,
pub client_id: String,
pub access_token: Secret<String>,
pub scopes: String,
pub expires_in: i64,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct SantanderCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SantanderPSyncBoletoRequest {
payer_document_number: Secret<i64>,
}
pub struct SantanderAuthType {
pub(super) _api_key: Secret<String>,
pub(super) _key1: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for SantanderAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
_api_key: api_key.to_owned(),
_key1: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, SantanderAuthUpdateResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SantanderAuthUpdateResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
impl TryFrom<&SantanderRouterData<&PaymentsAuthorizeRouterData>> for SantanderPaymentRequest {
type Error = Error;
fn try_from(
value: &SantanderRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if value.router_data.request.capture_method != Some(enums::CaptureMethod::Automatic) {
return Err(errors::ConnectorError::FlowNotSupported {
flow: format!("{:?}", value.router_data.request.capture_method),
connector: "Santander".to_string(),
}
.into());
}
match value.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankTransfer(ref bank_transfer_data) => {
Self::try_from((value, bank_transfer_data.as_ref()))
}
PaymentMethodData::Voucher(ref voucher_data) => Self::try_from((value, voucher_data)),
_ => Err(errors::ConnectorError::NotImplemented(
crate::utils::get_unimplemented_payment_method_error_message("Santander"),
))?,
}
}
}
impl TryFrom<&SantanderRouterData<&PaymentsSyncRouterData>> for SantanderPSyncBoletoRequest {
type Error = Error;
fn try_from(value: &SantanderRouterData<&PaymentsSyncRouterData>) -> Result<Self, Self::Error> {
let payer_document_number: i64 = value
.router_data
.connector_request_reference_id
.parse()
.map_err(|_| errors::ConnectorError::ParsingFailed)?;
Ok(Self {
payer_document_number: Secret::new(payer_document_number),
})
}
}
impl
TryFrom<(
&SantanderRouterData<&PaymentsAuthorizeRouterData>,
&VoucherData,
)> for SantanderPaymentRequest
{
type Error = Error;
fn try_from(
value: (
&SantanderRouterData<&PaymentsAuthorizeRouterData>,
&VoucherData,
),
) -> Result<Self, Self::Error> {
let santander_mca_metadata =
SantanderMetadataObject::try_from(&value.0.router_data.connector_meta_data)?;
let voucher_data = match &value.0.router_data.request.payment_method_data {
PaymentMethodData::Voucher(VoucherData::Boleto(boleto_data)) => boleto_data,
_ => {
return Err(errors::ConnectorError::NotImplemented(
crate::utils::get_unimplemented_payment_method_error_message("Santander"),
)
.into());
}
};
let nsu_code = if value
.0
.router_data
.is_payment_id_from_merchant
.unwrap_or(false)
&& value.0.router_data.payment_id.len() > 20
{
return Err(errors::ConnectorError::MaxFieldLengthViolated {
connector: "Santander".to_string(),
field_name: "payment_id".to_string(),
max_length: 20,
received_length: value.0.router_data.payment_id.len(),
}
.into());
} else {
value.0.router_data.payment_id.clone()
};
Ok(Self::Boleto(Box::new(SantanderBoletoPaymentRequest {
environment: Environment::from(router_env::env::which()),
nsu_code,
nsu_date: OffsetDateTime::now_utc()
.date()
.format(&time::macros::format_description!("[year]-[month]-[day]"))
.change_context(errors::ConnectorError::DateFormattingFailed)?,
covenant_code: santander_mca_metadata.covenant_code.clone(),
bank_number: voucher_data.bank_number.clone().ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "document_type",
}
})?, // size: 13
client_number: Some(value.0.router_data.get_customer_id()?),
due_date: voucher_data.due_date.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "due_date",
},
)?,
issue_date: OffsetDateTime::now_utc()
.date()
.format(&time::macros::format_description!("[year]-[month]-[day]"))
.change_context(errors::ConnectorError::DateFormattingFailed)?,
currency: Some(value.0.router_data.request.currency),
nominal_value: value.0.amount.to_owned(),
participant_code: value
.0
.router_data
.request
.merchant_order_reference_id
.clone(),
payer: Payer {
name: value.0.router_data.get_billing_full_name()?,
document_type: voucher_data.document_type.ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "document_type",
}
})?,
document_number: voucher_data.social_security_number.clone(),
address: Secret::new(
[
value.0.router_data.get_billing_line1()?,
value.0.router_data.get_billing_line2()?,
]
.map(|s| s.expose())
.join(" "),
),
neighborhood: value.0.router_data.get_billing_line1()?,
city: value.0.router_data.get_billing_city()?,
state: value.0.router_data.get_billing_state()?,
zipcode: value.0.router_data.get_billing_zip()?,
},
beneficiary: None,
document_kind: BoletoDocumentKind::BillProposal, // to change
discount: Some(Discount {
discount_type: DiscountType::Free,
discount_one: None,
discount_two: None,
discount_three: None,
}),
fine_percentage: voucher_data.fine_percentage.clone(),
fine_quantity_days: voucher_data.fine_quantity_days.clone(),
interest_percentage: voucher_data.interest_percentage.clone(),
deduction_value: None,
protest_type: None,
protest_quantity_days: None,
write_off_quantity_days: voucher_data.write_off_quantity_days.clone(),
payment_type: PaymentType::Registration,
parcels_quantity: None,
value_type: None,
min_value_or_percentage: None,
max_value_or_percentage: None,
iof_percentage: None,
sharing: None,
key: None,
tx_id: None,
messages: voucher_data.messages.clone(),
})))
}
}
impl
TryFrom<(
&SantanderRouterData<&PaymentsAuthorizeRouterData>,
&BankTransferData,
)> for SantanderPaymentRequest
{
type Error = Error;
fn try_from(
value: (
&SantanderRouterData<&PaymentsAuthorizeRouterData>,
&BankTransferData,
),
) -> Result<Self, Self::Error> {
let santander_mca_metadata =
SantanderMetadataObject::try_from(&value.0.router_data.connector_meta_data)?;
let debtor = Some(SantanderDebtor {
cpf: santander_mca_metadata.cpf.clone(),
name: value.0.router_data.get_billing_full_name()?,
});
Ok(Self::PixQR(Box::new(SantanderPixQRPaymentRequest {
calender: SantanderCalendar {
creation: OffsetDateTime::now_utc()
.date()
.format(&time::macros::format_description!("[year]-[month]-[day]"))
.change_context(errors::ConnectorError::DateFormattingFailed)?,
expiration: santander_mca_metadata.expiration_time,
},
debtor,
value: SantanderValue {
original: value.0.amount.to_owned(),
},
key: santander_mca_metadata.pix_key.clone(),
request_payer: value
.0
.router_data
.request
.billing_descriptor
.as_ref()
.and_then(|descriptor| descriptor.statement_descriptor.clone()),
additional_info: None,
})))
}
}
#[derive(Debug, Serialize)]
pub enum SantanderPaymentRequest {
PixQR(Box<SantanderPixQRPaymentRequest>),
Boleto(Box<SantanderBoletoPaymentRequest>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Discount {
#[serde(rename = "type")]
pub discount_type: DiscountType,
pub discount_one: Option<DiscountObject>,
pub discount_two: Option<DiscountObject>,
pub discount_three: Option<DiscountObject>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SantanderBoletoPaymentRequest {
pub environment: Environment,
pub nsu_code: String,
pub nsu_date: String,
pub covenant_code: String,
pub bank_number: Secret<String>,
pub client_number: Option<id_type::CustomerId>,
pub due_date: String,
pub issue_date: String,
pub currency: Option<enums::Currency>,
pub nominal_value: StringMajorUnit,
pub participant_code: Option<String>,
pub payer: Payer,
pub beneficiary: Option<Beneficiary>,
pub document_kind: BoletoDocumentKind,
pub discount: Option<Discount>,
pub fine_percentage: Option<String>,
pub fine_quantity_days: Option<String>,
pub interest_percentage: Option<String>,
pub deduction_value: Option<FloatMajorUnit>,
pub protest_type: Option<ProtestType>,
pub protest_quantity_days: Option<i64>,
pub write_off_quantity_days: Option<String>,
pub payment_type: PaymentType,
pub parcels_quantity: Option<i64>,
pub value_type: Option<String>,
pub min_value_or_percentage: Option<f64>,
pub max_value_or_percentage: Option<f64>,
pub iof_percentage: Option<f64>,
pub sharing: Option<Sharing>,
pub key: Option<Key>,
pub tx_id: Option<String>,
pub messages: Option<Vec<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Payer {
pub name: Secret<String>,
pub document_type: enums::DocumentKind,
pub document_number: Option<Secret<String>>,
pub address: Secret<String>,
pub neighborhood: Secret<String>,
pub city: String,
pub state: Secret<String>,
pub zipcode: Secret<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Beneficiary {
pub name: Option<Secret<String>>,
pub document_type: Option<enums::DocumentKind>,
pub document_number: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Environment {
#[serde(rename = "Teste")]
Sandbox,
#[serde(rename = "Producao")]
Production,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum SantanderDocumentKind {
Cpf,
Cnpj,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BoletoDocumentKind {
#[serde(rename = "DUPLICATA_MERCANTIL")]
DuplicateMercantil,
#[serde(rename = "DUPLICATA_SERVICO")]
DuplicateService,
#[serde(rename = "NOTA_PROMISSORIA")]
PromissoryNote,
#[serde(rename = "NOTA_PROMISSORIA_RURAL")]
RuralPromissoryNote,
#[serde(rename = "RECIBO")]
Receipt,
#[serde(rename = "APOLICE_SEGURO")]
InsurancePolicy,
#[serde(rename = "BOLETO_CARTAO_CREDITO")]
BillCreditCard,
#[serde(rename = "BOLETO_PROPOSTA")]
BillProposal,
#[serde(rename = "BOLETO_DEPOSITO_APORTE")]
BoletoDepositoAponte,
#[serde(rename = "CHEQUE")]
Check,
#[serde(rename = "NOTA_PROMISSORIA_DIRETA")]
DirectPromissoryNote,
#[serde(rename = "OUTROS")]
Others,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DiscountType {
#[serde(rename = "ISENTO")]
Free,
#[serde(rename = "VALOR_DATA_FIXA")]
FixedDateValue,
#[serde(rename = "VALOR_DIA_CORRIDO")]
ValueDayConductor,
#[serde(rename = "VALOR_DIA_UTIL")]
ValueWorthDay,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct DiscountObject {
pub value: f64,
pub limit_date: String, // YYYY-MM-DD
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ProtestType {
#[serde(rename = "SEM_PROTESTO")]
WithoutProtest,
#[serde(rename = "DIAS_CORRIDOS")]
DaysConducted,
#[serde(rename = "DIAS_UTEIS")]
WorkingDays,
#[serde(rename = "CADASTRO_CONVENIO")]
RegistrationAgreement,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaymentType {
#[serde(rename = "REGISTRO")]
Registration,
#[serde(rename = "DIVERGENTE")]
Divergent,
#[serde(rename = "PARCIAL")]
Partial,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Sharing {
pub code: String,
pub value: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Key {
#[serde(rename = "type")]
pub key_type: Option<String>,
pub dict_key: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SantanderPixQRCodeRequest {
#[serde(rename = "calendario")]
pub calender: SantanderCalendar,
#[serde(rename = "devedor")]
pub debtor: SantanderDebtor,
#[serde(rename = "valor")]
pub value: SantanderValue,
#[serde(rename = "chave")]
pub key: Secret<String>,
#[serde(rename = "solicitacaoPagador")]
pub request_payer: Option<String>,
#[serde(rename = "infoAdicionais")]
pub additional_info: Option<Vec<SantanderAdditionalInfo>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SantanderPixQRPaymentRequest {
#[serde(rename = "calendario")]
pub calender: SantanderCalendar,
#[serde(rename = "devedor")]
pub debtor: Option<SantanderDebtor>,
#[serde(rename = "valor")]
pub value: SantanderValue,
#[serde(rename = "chave")]
pub key: Secret<String>,
#[serde(rename = "solicitacaoPagador")]
pub request_payer: Option<String>,
#[serde(rename = "infoAdicionais")]
pub additional_info: Option<Vec<SantanderAdditionalInfo>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SantanderDebtor {
pub cpf: Secret<String>,
#[serde(rename = "nome")]
pub name: Secret<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SantanderValue {
pub original: StringMajorUnit,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SantanderAdditionalInfo {
#[serde(rename = "nome")]
pub name: String,
#[serde(rename = "valor")]
pub value: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SantanderPaymentStatus {
Active,
Completed,
RemovedByReceivingUser,
RemovedByPSP,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SantanderVoidStatus {
RemovedByReceivingUser,
}
impl From<SantanderPaymentStatus> for AttemptStatus {
fn from(item: SantanderPaymentStatus) -> Self {
match item {
SantanderPaymentStatus::Active => Self::Authorizing,
SantanderPaymentStatus::Completed => Self::Charged,
SantanderPaymentStatus::RemovedByReceivingUser => Self::Voided,
SantanderPaymentStatus::RemovedByPSP => Self::Failure,
}
}
}
impl From<router_env::env::Env> for Environment {
fn from(item: router_env::env::Env) -> Self {
match item {
router_env::env::Env::Sandbox
| router_env::env::Env::Development
| router_env::env::Env::Integ => Self::Sandbox,
router_env::env::Env::Production => Self::Production,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SantanderPaymentsResponse {
PixQRCode(Box<SantanderPixQRCodePaymentsResponse>),
Boleto(Box<SantanderBoletoPaymentsResponse>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SantanderBoletoPaymentsResponse {
pub environment: Environment,
pub nsu_code: String,
pub nsu_date: String,
pub covenant_code: String,
pub bank_number: String,
pub client_number: Option<id_type::CustomerId>,
pub due_date: String,
pub issue_date: String,
pub participant_code: Option<String>,
pub nominal_value: StringMajorUnit,
pub payer: Payer,
pub beneficiary: Option<Beneficiary>,
pub document_kind: BoletoDocumentKind,
pub discount: Option<Discount>,
pub fine_percentage: Option<String>,
pub fine_quantity_days: Option<String>,
pub interest_percentage: Option<String>,
pub deduction_value: Option<FloatMajorUnit>,
pub protest_type: Option<ProtestType>,
pub protest_quantity_days: Option<i64>,
pub write_off_quantity_days: Option<String>,
pub payment_type: PaymentType,
pub parcels_quantity: Option<i64>,
pub value_type: Option<String>,
pub min_value_or_percentage: Option<f64>,
pub max_value_or_percentage: Option<f64>,
pub iof_percentage: Option<f64>,
pub sharing: Option<Sharing>,
pub key: Option<Key>,
pub tx_id: Option<String>,
pub messages: Option<Vec<String>>,
pub barcode: Option<String>,
pub digitable_line: Option<Secret<String>>,
pub entry_date: Option<String>,
pub qr_code_pix: Option<String>,
pub qr_code_url: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SantanderPixQRCodePaymentsResponse {
pub status: SantanderPaymentStatus,
#[serde(rename = "calendario")]
pub calendar: SantanderCalendar,
#[serde(rename = "txid")]
pub transaction_id: String,
#[serde(rename = "revisao")]
pub revision: i32,
#[serde(rename = "devedor")]
pub debtor: Option<SantanderDebtor>,
pub location: Option<String>,
#[serde(rename = "valor")]
pub value: SantanderValue,
#[serde(rename = "chave")]
pub key: Secret<String>,
#[serde(rename = "solicitacaoPagador")]
pub request_payer: Option<String>,
#[serde(rename = "infoAdicionais")]
pub additional_info: Option<Vec<SantanderAdditionalInfo>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SantanderPixVoidResponse {
#[serde(rename = "calendario")]
pub calendar: SantanderCalendar,
#[serde(rename = "txid")]
pub transaction_id: String,
#[serde(rename = "revisao")]
pub revision: i32,
#[serde(rename = "devedor")]
pub debtor: Option<SantanderDebtor>,
pub location: Option<String>,
pub status: SantanderPaymentStatus,
#[serde(rename = "valor")]
pub value: SantanderValue,
#[serde(rename = "chave")]
pub key: Secret<String>,
#[serde(rename = "solicitacaoPagador")]
pub request_payer: Option<String>,
#[serde(rename = "infoAdicionais")]
pub additional_info: Option<Vec<SantanderAdditionalInfo>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SantanderCalendar {
#[serde(rename = "calendario")]
pub creation: String,
#[serde(rename = "expiracao")]
pub expiration: i32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SantanderPaymentsSyncResponse {
PixQRCode(Box<SantanderPixPSyncResponse>),
Boleto(Box<SantanderBoletoPSyncResponse>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SantanderBoletoPSyncResponse {
pub link: Option<Url>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SantanderPixPSyncResponse {
#[serde(flatten)]
pub base: SantanderPixQRCodePaymentsResponse,
pub pix: Vec<SantanderPix>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SantanderPix {
pub end_to_end_id: Secret<String>,
#[serde(rename = "txid")]
pub transaction_id: Secret<String>,
#[serde(rename = "valor")]
pub value: String,
#[serde(rename = "horario")]
pub time: String,
#[serde(rename = "infoPagador")]
pub info_payer: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SantanderPaymentsCancelRequest {
pub status: Option<SantanderVoidStatus>,
}
impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SantanderPaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response = item.response.clone();
match response {
SantanderPaymentsSyncResponse::PixQRCode(pix_data) => {
let attempt_status = AttemptStatus::from(pix_data.base.status.clone());
match attempt_status {
AttemptStatus::Failure => {
let response = Err(get_error_response(
Box::new(pix_data.base),
item.http_code,
attempt_status,
));
Ok(Self {
response,
..item.data
})
}
_ => {
let connector_metadata = pix_data.pix.first().map(|pix| {
serde_json::json!({
"end_to_end_id": pix.end_to_end_id.clone().expose()
})
});
Ok(Self {
status: AttemptStatus::from(pix_data.base.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
pix_data.base.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
}
SantanderPaymentsSyncResponse::Boleto(boleto_data) => {
let redirection_data = boleto_data.link.clone().map(|url| RedirectForm::Form {
endpoint: url.to_string(),
method: Method::Get,
form_fields: HashMap::new(),
});
Ok(Self {
status: AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
}
}
pub fn get_error_response(
pix_data: Box<SantanderPixQRCodePaymentsResponse>,
status_code: u16,
attempt_status: AttemptStatus,
) -> ErrorResponse {
ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: None,
status_code,
attempt_status: Some(attempt_status),
connector_transaction_id: Some(pix_data.transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SantanderPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response = item.response.clone();
match response {
SantanderPaymentsResponse::PixQRCode(pix_data) => {
let attempt_status = AttemptStatus::from(pix_data.status.clone());
match attempt_status {
AttemptStatus::Failure => {
let response = Err(get_error_response(
Box::new(*pix_data),
item.http_code,
attempt_status,
));
Ok(Self {
response,
..item.data
})
}
_ => Ok(Self {
status: AttemptStatus::from(pix_data.status.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
pix_data.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: get_qr_code_data(&item, &pix_data)?,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/api_keys.rs | crates/diesel_models/src/api_keys.rs | use diesel::{AsChangeset, AsExpression, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::schema::api_keys;
#[derive(
serde::Serialize, serde::Deserialize, Debug, Clone, Identifiable, Queryable, Selectable,
)]
#[diesel(table_name = api_keys, primary_key(key_id), check_for_backend(diesel::pg::Pg))]
pub struct ApiKey {
pub key_id: common_utils::id_type::ApiKeyId,
pub merchant_id: common_utils::id_type::MerchantId,
pub name: String,
pub description: Option<String>,
pub hashed_api_key: HashedApiKey,
pub prefix: String,
pub created_at: PrimitiveDateTime,
pub expires_at: Option<PrimitiveDateTime>,
pub last_used: Option<PrimitiveDateTime>,
}
#[derive(Debug, Insertable)]
#[diesel(table_name = api_keys)]
pub struct ApiKeyNew {
pub key_id: common_utils::id_type::ApiKeyId,
pub merchant_id: common_utils::id_type::MerchantId,
pub name: String,
pub description: Option<String>,
pub hashed_api_key: HashedApiKey,
pub prefix: String,
pub created_at: PrimitiveDateTime,
pub expires_at: Option<PrimitiveDateTime>,
pub last_used: Option<PrimitiveDateTime>,
}
#[derive(Debug)]
pub enum ApiKeyUpdate {
Update {
name: Option<String>,
description: Option<String>,
expires_at: Option<Option<PrimitiveDateTime>>,
last_used: Option<PrimitiveDateTime>,
},
LastUsedUpdate {
last_used: PrimitiveDateTime,
},
}
#[derive(Debug, AsChangeset)]
#[diesel(table_name = api_keys)]
pub(crate) struct ApiKeyUpdateInternal {
pub name: Option<String>,
pub description: Option<String>,
pub expires_at: Option<Option<PrimitiveDateTime>>,
pub last_used: Option<PrimitiveDateTime>,
}
impl From<ApiKeyUpdate> for ApiKeyUpdateInternal {
fn from(api_key_update: ApiKeyUpdate) -> Self {
match api_key_update {
ApiKeyUpdate::Update {
name,
description,
expires_at,
last_used,
} => Self {
name,
description,
expires_at,
last_used,
},
ApiKeyUpdate::LastUsedUpdate { last_used } => Self {
last_used: Some(last_used),
name: None,
description: None,
expires_at: None,
},
}
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, AsExpression, PartialEq)]
#[diesel(sql_type = diesel::sql_types::Text)]
pub struct HashedApiKey(String);
impl HashedApiKey {
pub fn into_inner(self) -> String {
self.0
}
}
impl From<String> for HashedApiKey {
fn from(hashed_api_key: String) -> Self {
Self(hashed_api_key)
}
}
mod diesel_impl {
use diesel::{
backend::Backend,
deserialize::FromSql,
serialize::{Output, ToSql},
sql_types::Text,
Queryable,
};
impl<DB> ToSql<Text, DB> for super::HashedApiKey
where
DB: Backend,
String: ToSql<Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> FromSql<Text, DB> for super::HashedApiKey
where
DB: Backend,
String: FromSql<Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
Ok(Self(String::from_sql(bytes)?))
}
}
impl<DB> Queryable<Text, DB> for super::HashedApiKey
where
DB: Backend,
Self: FromSql<Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
Ok(row)
}
}
}
// Tracking data by process_tracker
#[derive(Default, Debug, Deserialize, Serialize, Clone)]
pub struct ApiKeyExpiryTrackingData {
pub key_id: common_utils::id_type::ApiKeyId,
pub merchant_id: common_utils::id_type::MerchantId,
pub api_key_name: String,
pub prefix: String,
pub api_key_expiry: Option<PrimitiveDateTime>,
// Days on which email reminder about api_key expiry has to be sent, prior to it's expiry.
pub expiry_reminder_days: Vec<u8>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/locker_mock_up.rs | crates/diesel_models/src/locker_mock_up.rs | use diesel::{Identifiable, Insertable, Queryable, Selectable};
use crate::schema::locker_mock_up;
#[derive(Clone, Debug, Eq, Identifiable, Queryable, Selectable, PartialEq)]
#[diesel(table_name = locker_mock_up, primary_key(card_id), check_for_backend(diesel::pg::Pg))]
pub struct LockerMockUp {
pub card_id: String,
pub external_id: String,
pub card_fingerprint: String,
pub card_global_fingerprint: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub card_number: String,
pub card_exp_year: String,
pub card_exp_month: String,
pub name_on_card: Option<String>,
pub nickname: Option<String>,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub duplicate: Option<bool>,
pub card_cvc: Option<String>,
pub payment_method_id: Option<String>,
pub enc_card_data: Option<String>,
}
#[derive(Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = locker_mock_up)]
pub struct LockerMockUpNew {
pub card_id: String,
pub external_id: String,
pub card_fingerprint: String,
pub card_global_fingerprint: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub card_number: String,
pub card_exp_year: String,
pub card_exp_month: String,
pub name_on_card: Option<String>,
pub card_cvc: Option<String>,
pub payment_method_id: Option<String>,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub nickname: Option<String>,
pub enc_card_data: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/errors.rs | crates/diesel_models/src/errors.rs | #[derive(Copy, Clone, Debug, thiserror::Error)]
pub enum DatabaseError {
#[error("An error occurred when obtaining database connection")]
DatabaseConnectionError,
#[error("The requested resource was not found in the database")]
NotFound,
#[error("A unique constraint violation occurred")]
UniqueViolation,
#[error("No fields were provided to be updated")]
NoFieldsToUpdate,
#[error("An error occurred when generating typed SQL query")]
QueryGenerationFailed,
// InsertFailed,
#[error("An unknown error occurred")]
Others,
}
impl From<diesel::result::Error> for DatabaseError {
fn from(error: diesel::result::Error) -> Self {
match error {
diesel::result::Error::DatabaseError(
diesel::result::DatabaseErrorKind::UniqueViolation,
_,
) => Self::UniqueViolation,
diesel::result::Error::NotFound => Self::NotFound,
diesel::result::Error::QueryBuilderError(_) => Self::QueryGenerationFailed,
_ => Self::Others,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/user.rs | crates/diesel_models/src/user.rs | use common_utils::{encryption::Encryption, pii, types::user::LineageContext};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use masking::Secret;
use time::PrimitiveDateTime;
use crate::{diesel_impl::OptionalDieselArray, enums::TotpStatus, schema::users};
pub mod dashboard_metadata;
pub mod sample_data;
pub mod theme;
#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]
#[diesel(table_name = users, primary_key(user_id), check_for_backend(diesel::pg::Pg))]
pub struct User {
pub user_id: String,
pub email: pii::Email,
pub name: Secret<String>,
pub password: Option<Secret<String>>,
pub is_verified: bool,
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
pub totp_status: TotpStatus,
pub totp_secret: Option<Encryption>,
#[diesel(deserialize_as = OptionalDieselArray<Secret<String>>)]
pub totp_recovery_codes: Option<Vec<Secret<String>>>,
pub last_password_modified_at: Option<PrimitiveDateTime>,
pub lineage_context: Option<LineageContext>,
}
#[derive(
router_derive::Setter, Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay,
)]
#[diesel(table_name = users)]
pub struct UserNew {
pub user_id: String,
pub email: pii::Email,
pub name: Secret<String>,
pub password: Option<Secret<String>>,
pub is_verified: bool,
pub created_at: Option<PrimitiveDateTime>,
pub last_modified_at: Option<PrimitiveDateTime>,
pub totp_status: TotpStatus,
pub totp_secret: Option<Encryption>,
pub totp_recovery_codes: Option<Vec<Secret<String>>>,
pub last_password_modified_at: Option<PrimitiveDateTime>,
pub lineage_context: Option<LineageContext>,
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = users)]
pub struct UserUpdateInternal {
name: Option<String>,
password: Option<Secret<String>>,
is_verified: Option<bool>,
last_modified_at: PrimitiveDateTime,
totp_status: Option<TotpStatus>,
totp_secret: Option<Encryption>,
totp_recovery_codes: Option<Vec<Secret<String>>>,
last_password_modified_at: Option<PrimitiveDateTime>,
lineage_context: Option<LineageContext>,
}
#[derive(Debug)]
pub enum UserUpdate {
VerifyUser,
AccountUpdate {
name: Option<String>,
is_verified: Option<bool>,
},
TotpUpdate {
totp_status: Option<TotpStatus>,
totp_secret: Option<Encryption>,
totp_recovery_codes: Option<Vec<Secret<String>>>,
},
PasswordUpdate {
password: Secret<String>,
},
LineageContextUpdate {
lineage_context: LineageContext,
},
}
impl From<UserUpdate> for UserUpdateInternal {
fn from(user_update: UserUpdate) -> Self {
let last_modified_at = common_utils::date_time::now();
match user_update {
UserUpdate::VerifyUser => Self {
name: None,
password: None,
is_verified: Some(true),
last_modified_at,
totp_status: None,
totp_secret: None,
totp_recovery_codes: None,
last_password_modified_at: None,
lineage_context: None,
},
UserUpdate::AccountUpdate { name, is_verified } => Self {
name,
password: None,
is_verified,
last_modified_at,
totp_status: None,
totp_secret: None,
totp_recovery_codes: None,
last_password_modified_at: None,
lineage_context: None,
},
UserUpdate::TotpUpdate {
totp_status,
totp_secret,
totp_recovery_codes,
} => Self {
name: None,
password: None,
is_verified: None,
last_modified_at,
totp_status,
totp_secret,
totp_recovery_codes,
last_password_modified_at: None,
lineage_context: None,
},
UserUpdate::PasswordUpdate { password } => Self {
name: None,
password: Some(password),
is_verified: None,
last_modified_at,
last_password_modified_at: Some(last_modified_at),
totp_status: None,
totp_secret: None,
totp_recovery_codes: None,
lineage_context: None,
},
UserUpdate::LineageContextUpdate { lineage_context } => Self {
name: None,
password: None,
is_verified: None,
last_modified_at,
last_password_modified_at: None,
totp_status: None,
totp_secret: None,
totp_recovery_codes: None,
lineage_context: Some(lineage_context),
},
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/blocklist_fingerprint.rs | crates/diesel_models/src/blocklist_fingerprint.rs | use diesel::{Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use crate::schema::blocklist_fingerprint;
#[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)]
#[diesel(table_name = blocklist_fingerprint)]
pub struct BlocklistFingerprintNew {
pub merchant_id: common_utils::id_type::MerchantId,
pub fingerprint_id: String,
pub data_kind: common_enums::BlocklistDataKind,
pub encrypted_fingerprint: String,
pub created_at: time::PrimitiveDateTime,
}
#[derive(
Clone, Debug, Eq, PartialEq, Queryable, Identifiable, Selectable, Deserialize, Serialize,
)]
#[diesel(table_name = blocklist_fingerprint, primary_key(merchant_id, fingerprint_id), check_for_backend(diesel::pg::Pg))]
pub struct BlocklistFingerprint {
pub merchant_id: common_utils::id_type::MerchantId,
pub fingerprint_id: String,
pub data_kind: common_enums::BlocklistDataKind,
pub encrypted_fingerprint: String,
pub created_at: time::PrimitiveDateTime,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/blocklist.rs | crates/diesel_models/src/blocklist.rs | use diesel::{Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use crate::schema::blocklist;
#[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)]
#[diesel(table_name = blocklist)]
pub struct BlocklistNew {
pub merchant_id: common_utils::id_type::MerchantId,
pub fingerprint_id: String,
pub data_kind: common_enums::BlocklistDataKind,
pub metadata: Option<serde_json::Value>,
pub created_at: time::PrimitiveDateTime,
}
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Deserialize, Serialize,
)]
#[diesel(table_name = blocklist, primary_key(merchant_id, fingerprint_id), check_for_backend(diesel::pg::Pg))]
pub struct Blocklist {
pub merchant_id: common_utils::id_type::MerchantId,
pub fingerprint_id: String,
pub data_kind: common_enums::BlocklistDataKind,
pub metadata: Option<serde_json::Value>,
pub created_at: time::PrimitiveDateTime,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/payment_attempt.rs | crates/diesel_models/src/payment_attempt.rs | #[cfg(feature = "v2")]
use common_types::payments as common_payments_types;
use common_types::primitive_wrappers::{
ExtendedAuthorizationAppliedBool, OvercaptureEnabledBool, RequestExtendedAuthorizationBool,
};
use common_utils::{
id_type, pii,
types::{ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit},
};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::enums as storage_enums;
#[cfg(feature = "v1")]
use crate::schema::payment_attempt;
#[cfg(feature = "v2")]
use crate::{schema_v2::payment_attempt, RequiredFromNullable};
common_utils::impl_to_sql_from_sql_json!(ConnectorMandateReferenceId);
#[derive(
Clone, Debug, serde::Deserialize, serde::Serialize, Eq, PartialEq, diesel::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct ConnectorMandateReferenceId {
pub connector_mandate_id: Option<String>,
pub payment_method_id: Option<String>,
pub mandate_metadata: Option<pii::SecretSerdeValue>,
pub connector_mandate_request_reference_id: Option<String>,
}
impl ConnectorMandateReferenceId {
pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> {
self.connector_mandate_request_reference_id.clone()
}
pub fn is_connector_mandate_id_present(&self) -> bool {
self.connector_mandate_id.is_some()
}
}
common_utils::impl_to_sql_from_sql_json!(NetworkDetails);
#[derive(
Clone, Default, Debug, serde::Deserialize, Eq, PartialEq, serde::Serialize, diesel::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct NetworkDetails {
pub network_advice_code: Option<String>,
}
// ErrorDetails nested structs for V1 payment_attempt
common_utils::impl_to_sql_from_sql_json!(ErrorDetails);
#[derive(
Clone, Default, Debug, serde::Deserialize, Eq, PartialEq, serde::Serialize, diesel::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct ErrorDetails {
pub unified_details: Option<UnifiedErrorDetails>,
pub issuer_details: Option<IssuerErrorDetails>,
pub connector_details: Option<ConnectorErrorDetails>,
}
#[derive(Clone, Default, Debug, serde::Deserialize, Eq, PartialEq, serde::Serialize)]
pub struct UnifiedErrorDetails {
pub category: Option<String>,
pub message: Option<String>,
pub standardised_code: Option<storage_enums::StandardisedCode>,
pub description: Option<String>,
pub user_guidance_message: Option<String>,
pub recommended_action: Option<storage_enums::RecommendedAction>,
}
#[derive(Clone, Default, Debug, serde::Deserialize, Eq, PartialEq, serde::Serialize)]
pub struct IssuerErrorDetails {
pub code: Option<String>,
pub message: Option<String>,
pub network_details: Option<NetworkErrorDetails>,
}
#[derive(Clone, Default, Debug, serde::Deserialize, Eq, PartialEq, serde::Serialize)]
pub struct NetworkErrorDetails {
pub name: Option<storage_enums::CardNetwork>,
pub advice_code: Option<String>,
pub advice_message: Option<String>,
}
#[derive(Clone, Default, Debug, serde::Deserialize, Eq, PartialEq, serde::Serialize)]
pub struct ConnectorErrorDetails {
pub code: Option<String>,
pub message: Option<String>,
pub reason: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable,
)]
#[diesel(table_name = payment_attempt, primary_key(id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentAttempt {
pub payment_id: id_type::GlobalPaymentId,
pub merchant_id: id_type::MerchantId,
pub status: storage_enums::AttemptStatus,
pub connector: Option<String>,
pub error_message: Option<String>,
pub surcharge_amount: Option<MinorUnit>,
pub payment_method_id: Option<id_type::GlobalPaymentMethodId>,
#[diesel(deserialize_as = RequiredFromNullable<storage_enums::AuthenticationType>)]
pub authentication_type: storage_enums::AuthenticationType,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub cancellation_reason: Option<String>,
pub amount_to_capture: Option<MinorUnit>,
pub browser_info: Option<common_utils::types::BrowserInformation>,
pub error_code: Option<String>,
pub payment_token: Option<String>,
pub connector_metadata: Option<pii::SecretSerdeValue>,
pub payment_experience: Option<storage_enums::PaymentExperience>,
pub payment_method_data: Option<pii::SecretSerdeValue>,
pub preprocessing_step_id: Option<String>,
pub error_reason: Option<String>,
pub multiple_capture_count: Option<i16>,
pub connector_response_reference_id: Option<String>,
pub amount_capturable: MinorUnit,
pub updated_by: String,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub encoded_data: Option<masking::Secret<String>>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
#[diesel(deserialize_as = RequiredFromNullable<MinorUnit>)]
pub net_amount: MinorUnit,
pub external_three_ds_authentication_attempted: Option<bool>,
pub authentication_connector: Option<String>,
pub authentication_id: Option<id_type::AuthenticationId>,
pub fingerprint_id: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<masking::Secret<common_payments_types::CustomerAcceptance>>,
pub profile_id: id_type::ProfileId,
pub organization_id: id_type::OrganizationId,
pub card_network: Option<String>,
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>,
pub capture_before: Option<PrimitiveDateTime>,
pub card_discovery: Option<storage_enums::CardDiscovery>,
pub charges: Option<common_types::payments::ConnectorChargeResponseData>,
pub processor_merchant_id: Option<id_type::MerchantId>,
pub created_by: Option<String>,
pub connector_request_reference_id: Option<String>,
pub network_transaction_id: Option<String>,
pub is_overcapture_enabled: Option<OvercaptureEnabledBool>,
pub network_details: Option<NetworkDetails>,
pub is_stored_credential: Option<bool>,
/// stores the authorized amount in case of partial authorization
pub authorized_amount: Option<MinorUnit>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub extended_authorization_last_applied_at: Option<PrimitiveDateTime>,
pub tokenization: Option<common_enums::Tokenization>,
pub encrypted_payment_method_data: Option<common_utils::encryption::Encryption>,
pub error_details: Option<ErrorDetails>,
#[diesel(deserialize_as = RequiredFromNullable<storage_enums::PaymentMethod>)]
pub payment_method_type_v2: storage_enums::PaymentMethod,
pub connector_payment_id: Option<ConnectorTransactionId>,
pub payment_method_subtype: storage_enums::PaymentMethodType,
pub routing_result: Option<serde_json::Value>,
pub authentication_applied: Option<common_enums::AuthenticationType>,
pub external_reference_id: Option<String>,
pub tax_on_surcharge: Option<MinorUnit>,
pub payment_method_billing_address: Option<common_utils::encryption::Encryption>,
pub redirection_data: Option<RedirectForm>,
pub connector_payment_data: Option<String>,
pub connector_token_details: Option<ConnectorTokenDetails>,
pub id: id_type::GlobalAttemptId,
pub feature_metadata: Option<PaymentAttemptFeatureMetadata>,
/// This field can be returned for both approved and refused Mastercard payments.
/// This code provides additional information about the type of transaction or the reason why the payment failed.
/// If the payment failed, the network advice code gives guidance on if and when you can retry the payment.
pub network_advice_code: Option<String>,
/// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed.
pub network_decline_code: Option<String>,
/// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better.
pub network_error_message: Option<String>,
/// A string indicating the group of the payment attempt. Used in split payments flow
pub attempts_group_id: Option<id_type::GlobalAttemptGroupId>,
/// Amount captured for this payment attempt
pub amount_captured: Option<MinorUnit>,
}
#[cfg(feature = "v1")]
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable,
)]
#[diesel(table_name = payment_attempt, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentAttempt {
pub payment_id: id_type::PaymentId,
pub merchant_id: id_type::MerchantId,
pub attempt_id: String,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub save_to_locker: Option<bool>,
pub connector: Option<String>,
pub error_message: Option<String>,
pub offer_amount: Option<MinorUnit>,
pub surcharge_amount: Option<MinorUnit>,
pub tax_amount: Option<MinorUnit>,
pub payment_method_id: Option<String>,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub connector_transaction_id: Option<ConnectorTransactionId>,
pub capture_method: Option<storage_enums::CaptureMethod>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub capture_on: Option<PrimitiveDateTime>,
pub confirm: bool,
pub authentication_type: Option<storage_enums::AuthenticationType>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub cancellation_reason: Option<String>,
pub amount_to_capture: Option<MinorUnit>,
pub mandate_id: Option<String>,
pub browser_info: Option<serde_json::Value>,
pub error_code: Option<String>,
pub payment_token: Option<String>,
pub connector_metadata: Option<serde_json::Value>,
pub payment_experience: Option<storage_enums::PaymentExperience>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_data: Option<serde_json::Value>,
pub business_sub_label: Option<String>,
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
// providing a location to store mandate details intermediately for transaction
pub mandate_details: Option<storage_enums::MandateDataType>,
pub error_reason: Option<String>,
pub multiple_capture_count: Option<i16>,
// reference to the payment at connector side
pub connector_response_reference_id: Option<String>,
pub amount_capturable: MinorUnit,
pub updated_by: String,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub authentication_data: Option<serde_json::Value>,
pub encoded_data: Option<String>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub net_amount: Option<MinorUnit>,
pub external_three_ds_authentication_attempted: Option<bool>,
pub authentication_connector: Option<String>,
pub authentication_id: Option<id_type::AuthenticationId>,
pub mandate_data: Option<storage_enums::MandateDetails>,
pub fingerprint_id: Option<String>,
pub payment_method_billing_address_id: Option<String>,
pub charge_id: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub profile_id: id_type::ProfileId,
pub organization_id: id_type::OrganizationId,
pub card_network: Option<String>,
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
/// INFO: This field is deprecated and replaced by processor_transaction_data
pub connector_transaction_data: Option<String>,
pub connector_mandate_detail: Option<ConnectorMandateReferenceId>,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>,
pub capture_before: Option<PrimitiveDateTime>,
pub processor_transaction_data: Option<String>,
pub card_discovery: Option<storage_enums::CardDiscovery>,
pub charges: Option<common_types::payments::ConnectorChargeResponseData>,
pub issuer_error_code: Option<String>,
pub issuer_error_message: Option<String>,
pub processor_merchant_id: Option<id_type::MerchantId>,
pub created_by: Option<String>,
pub setup_future_usage_applied: Option<storage_enums::FutureUsage>,
pub routing_approach: Option<storage_enums::RoutingApproach>,
pub connector_request_reference_id: Option<String>,
pub network_transaction_id: Option<String>,
pub is_overcapture_enabled: Option<OvercaptureEnabledBool>,
pub network_details: Option<NetworkDetails>,
pub is_stored_credential: Option<bool>,
/// stores the authorized amount in case of partial authorization
pub authorized_amount: Option<MinorUnit>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub extended_authorization_last_applied_at: Option<PrimitiveDateTime>,
pub tokenization: Option<common_enums::Tokenization>,
pub encrypted_payment_method_data: Option<common_utils::encryption::Encryption>,
pub error_details: Option<ErrorDetails>,
}
#[cfg(feature = "v1")]
impl ConnectorTransactionIdTrait for PaymentAttempt {
fn get_optional_connector_transaction_id(&self) -> Option<&String> {
match self
.connector_transaction_id
.as_ref()
.map(|txn_id| txn_id.get_txn_id(self.processor_transaction_data.as_ref()))
.transpose()
{
Ok(txn_id) => txn_id,
// In case hashed data is missing from DB, use the hashed ID as connector transaction ID
Err(_) => self
.connector_transaction_id
.as_ref()
.map(|txn_id| txn_id.get_id()),
}
}
}
#[cfg(feature = "v2")]
impl ConnectorTransactionIdTrait for PaymentAttempt {
fn get_optional_connector_transaction_id(&self) -> Option<&String> {
match self
.connector_payment_id
.as_ref()
.map(|txn_id| txn_id.get_txn_id(self.connector_payment_data.as_ref()))
.transpose()
{
Ok(txn_id) => txn_id,
// In case hashed data is missing from DB, use the hashed ID as connector payment ID
Err(_) => self
.connector_payment_id
.as_ref()
.map(|txn_id| txn_id.get_id()),
}
}
}
#[cfg(feature = "v2")]
#[derive(
Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize, diesel::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct ConnectorTokenDetails {
pub connector_mandate_id: Option<String>,
pub connector_token_request_reference_id: Option<String>,
}
#[cfg(feature = "v2")]
common_utils::impl_to_sql_from_sql_json!(ConnectorTokenDetails);
#[cfg(feature = "v2")]
impl ConnectorTokenDetails {
pub fn get_connector_token_request_reference_id(&self) -> Option<String> {
self.connector_token_request_reference_id.clone()
}
}
#[derive(Clone, Debug, Eq, PartialEq, Queryable, Serialize, Deserialize)]
pub struct PaymentListFilters {
pub connector: Vec<String>,
pub currency: Vec<storage_enums::Currency>,
pub status: Vec<storage_enums::IntentStatus>,
pub payment_method: Vec<storage_enums::PaymentMethod>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = payment_attempt)]
pub struct PaymentAttemptNew {
pub payment_id: id_type::GlobalPaymentId,
pub merchant_id: id_type::MerchantId,
pub attempts_group_id: Option<id_type::GlobalAttemptGroupId>,
pub status: storage_enums::AttemptStatus,
pub error_message: Option<String>,
pub surcharge_amount: Option<MinorUnit>,
pub tax_on_surcharge: Option<MinorUnit>,
pub payment_method_id: Option<id_type::GlobalPaymentMethodId>,
pub authentication_type: storage_enums::AuthenticationType,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub cancellation_reason: Option<String>,
pub amount_to_capture: Option<MinorUnit>,
pub browser_info: Option<common_utils::types::BrowserInformation>,
pub payment_token: Option<String>,
pub error_code: Option<String>,
pub connector_metadata: Option<pii::SecretSerdeValue>,
pub payment_experience: Option<storage_enums::PaymentExperience>,
pub payment_method_data: Option<pii::SecretSerdeValue>,
pub preprocessing_step_id: Option<String>,
pub error_reason: Option<String>,
pub connector_response_reference_id: Option<String>,
pub network_transaction_id: Option<String>,
pub network_details: Option<NetworkDetails>,
pub is_stored_credential: Option<bool>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
pub updated_by: String,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub redirection_data: Option<RedirectForm>,
pub encoded_data: Option<masking::Secret<String>>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub net_amount: MinorUnit,
pub external_three_ds_authentication_attempted: Option<bool>,
pub authentication_connector: Option<String>,
pub authentication_id: Option<id_type::AuthenticationId>,
pub fingerprint_id: Option<String>,
pub payment_method_billing_address: Option<common_utils::encryption::Encryption>,
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<masking::Secret<common_payments_types::CustomerAcceptance>>,
pub profile_id: id_type::ProfileId,
pub organization_id: id_type::OrganizationId,
pub card_network: Option<String>,
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
pub charges: Option<common_types::payments::ConnectorChargeResponseData>,
pub feature_metadata: Option<PaymentAttemptFeatureMetadata>,
pub payment_method_type_v2: storage_enums::PaymentMethod,
pub connector_payment_id: Option<ConnectorTransactionId>,
pub payment_method_subtype: storage_enums::PaymentMethodType,
pub id: id_type::GlobalAttemptId,
pub connector_token_details: Option<ConnectorTokenDetails>,
pub card_discovery: Option<storage_enums::CardDiscovery>,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>,
pub capture_before: Option<PrimitiveDateTime>,
pub connector: Option<String>,
pub network_decline_code: Option<String>,
pub network_advice_code: Option<String>,
pub network_error_message: Option<String>,
pub processor_merchant_id: Option<id_type::MerchantId>,
pub created_by: Option<String>,
pub connector_request_reference_id: Option<String>,
pub authorized_amount: Option<MinorUnit>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub extended_authorization_last_applied_at: Option<PrimitiveDateTime>,
pub tokenization: Option<common_enums::Tokenization>,
/// Amount captured for this payment attempt
pub amount_captured: Option<MinorUnit>,
pub encrypted_payment_method_data: Option<common_utils::encryption::Encryption>,
pub error_details: Option<ErrorDetails>,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = payment_attempt)]
pub struct PaymentAttemptNew {
pub payment_id: id_type::PaymentId,
pub merchant_id: id_type::MerchantId,
pub attempt_id: String,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
// pub auto_capture: Option<bool>,
pub save_to_locker: Option<bool>,
pub connector: Option<String>,
pub error_message: Option<String>,
pub offer_amount: Option<MinorUnit>,
pub surcharge_amount: Option<MinorUnit>,
pub tax_amount: Option<MinorUnit>,
pub payment_method_id: Option<String>,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub capture_method: Option<storage_enums::CaptureMethod>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub capture_on: Option<PrimitiveDateTime>,
pub confirm: bool,
pub authentication_type: Option<storage_enums::AuthenticationType>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub cancellation_reason: Option<String>,
pub amount_to_capture: Option<MinorUnit>,
pub mandate_id: Option<String>,
pub browser_info: Option<serde_json::Value>,
pub payment_token: Option<String>,
pub error_code: Option<String>,
pub connector_metadata: Option<serde_json::Value>,
pub payment_experience: Option<storage_enums::PaymentExperience>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_data: Option<serde_json::Value>,
pub business_sub_label: Option<String>,
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
pub mandate_details: Option<storage_enums::MandateDataType>,
pub error_reason: Option<String>,
pub connector_response_reference_id: Option<String>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
pub updated_by: String,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub authentication_data: Option<serde_json::Value>,
pub encoded_data: Option<String>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub net_amount: Option<MinorUnit>,
pub external_three_ds_authentication_attempted: Option<bool>,
pub authentication_connector: Option<String>,
pub authentication_id: Option<id_type::AuthenticationId>,
pub mandate_data: Option<storage_enums::MandateDetails>,
pub fingerprint_id: Option<String>,
pub payment_method_billing_address_id: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub profile_id: id_type::ProfileId,
pub organization_id: id_type::OrganizationId,
pub card_network: Option<String>,
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
pub connector_mandate_detail: Option<ConnectorMandateReferenceId>,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub capture_before: Option<PrimitiveDateTime>,
pub card_discovery: Option<storage_enums::CardDiscovery>,
pub processor_merchant_id: Option<id_type::MerchantId>,
pub created_by: Option<String>,
pub setup_future_usage_applied: Option<storage_enums::FutureUsage>,
pub routing_approach: Option<storage_enums::RoutingApproach>,
pub connector_request_reference_id: Option<String>,
pub network_transaction_id: Option<String>,
pub network_details: Option<NetworkDetails>,
pub is_stored_credential: Option<bool>,
pub authorized_amount: Option<MinorUnit>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub extended_authorization_last_applied_at: Option<PrimitiveDateTime>,
pub tokenization: Option<common_enums::Tokenization>,
pub encrypted_payment_method_data: Option<common_utils::encryption::Encryption>,
pub error_details: Option<ErrorDetails>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PaymentAttemptUpdate {
Update {
amount: MinorUnit,
currency: storage_enums::Currency,
status: storage_enums::AttemptStatus,
authentication_type: Option<storage_enums::AuthenticationType>,
payment_method: Option<storage_enums::PaymentMethod>,
payment_token: Option<String>,
payment_method_data: Option<serde_json::Value>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
payment_experience: Option<storage_enums::PaymentExperience>,
business_sub_label: Option<String>,
amount_to_capture: Option<MinorUnit>,
capture_method: Option<storage_enums::CaptureMethod>,
surcharge_amount: Option<MinorUnit>,
tax_amount: Option<MinorUnit>,
fingerprint_id: Option<String>,
payment_method_billing_address_id: Option<String>,
network_transaction_id: Option<String>,
updated_by: String,
},
UpdateTrackers {
payment_token: Option<String>,
connector: Option<String>,
straight_through_algorithm: Option<serde_json::Value>,
amount_capturable: Option<MinorUnit>,
surcharge_amount: Option<MinorUnit>,
tax_amount: Option<MinorUnit>,
updated_by: String,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
routing_approach: Option<storage_enums::RoutingApproach>,
is_stored_credential: Option<bool>,
},
AuthenticationTypeUpdate {
authentication_type: storage_enums::AuthenticationType,
updated_by: String,
},
ConfirmUpdate {
amount: MinorUnit,
currency: storage_enums::Currency,
status: storage_enums::AttemptStatus,
authentication_type: Option<storage_enums::AuthenticationType>,
capture_method: Option<storage_enums::CaptureMethod>,
payment_method: Option<storage_enums::PaymentMethod>,
browser_info: Option<serde_json::Value>,
connector: Option<String>,
payment_token: Option<String>,
payment_method_data: Option<serde_json::Value>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
payment_experience: Option<storage_enums::PaymentExperience>,
business_sub_label: Option<String>,
straight_through_algorithm: Option<serde_json::Value>,
error_code: Option<Option<String>>,
error_message: Option<Option<String>>,
surcharge_amount: Option<MinorUnit>,
tax_amount: Option<MinorUnit>,
fingerprint_id: Option<String>,
updated_by: String,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
payment_method_id: Option<String>,
external_three_ds_authentication_attempted: Option<bool>,
authentication_connector: Option<String>,
authentication_id: Option<id_type::AuthenticationId>,
payment_method_billing_address_id: Option<String>,
client_source: Option<String>,
client_version: Option<String>,
customer_acceptance: Option<pii::SecretSerdeValue>,
shipping_cost: Option<MinorUnit>,
order_tax_amount: Option<MinorUnit>,
connector_mandate_detail: Option<ConnectorMandateReferenceId>,
tokenization: Option<common_enums::Tokenization>,
card_discovery: Option<storage_enums::CardDiscovery>,
routing_approach: Option<storage_enums::RoutingApproach>,
connector_request_reference_id: Option<String>,
network_transaction_id: Option<String>,
is_stored_credential: Option<bool>,
request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
},
VoidUpdate {
status: storage_enums::AttemptStatus,
cancellation_reason: Option<String>,
updated_by: String,
},
PaymentMethodDetailsUpdate {
payment_method_id: Option<String>,
updated_by: String,
},
ConnectorMandateDetailUpdate {
connector_mandate_detail: Option<ConnectorMandateReferenceId>,
tokenization: Option<common_enums::Tokenization>,
updated_by: String,
},
BlocklistUpdate {
status: storage_enums::AttemptStatus,
error_code: Option<Option<String>>,
error_message: Option<Option<String>>,
updated_by: String,
},
RejectUpdate {
status: storage_enums::AttemptStatus,
error_code: Option<Option<String>>,
error_message: Option<Option<String>>,
updated_by: String,
},
ResponseUpdate {
status: storage_enums::AttemptStatus,
connector: Option<String>,
connector_transaction_id: Option<String>,
authentication_type: Option<storage_enums::AuthenticationType>,
network_transaction_id: Option<String>,
payment_method_id: Option<String>,
mandate_id: Option<String>,
connector_metadata: Option<serde_json::Value>,
payment_token: Option<String>,
error_code: Option<Option<String>>,
error_message: Option<Option<String>>,
error_reason: Option<Option<String>>,
connector_response_reference_id: Option<String>,
amount_capturable: Option<MinorUnit>,
updated_by: String,
authentication_data: Option<serde_json::Value>,
encoded_data: Option<String>,
unified_code: Option<Option<String>>,
unified_message: Option<Option<String>>,
capture_before: Option<PrimitiveDateTime>,
extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>,
extended_authorization_last_applied_at: Option<PrimitiveDateTime>,
tokenization: Option<common_enums::Tokenization>,
payment_method_data: Option<serde_json::Value>,
encrypted_payment_method_data: Option<common_utils::encryption::Encryption>,
connector_mandate_detail: Option<ConnectorMandateReferenceId>,
charges: Option<common_types::payments::ConnectorChargeResponseData>,
setup_future_usage_applied: Option<storage_enums::FutureUsage>,
is_overcapture_enabled: Option<OvercaptureEnabledBool>,
authorized_amount: Option<MinorUnit>,
error_details: Box<Option<ErrorDetails>>,
},
UnresolvedResponseUpdate {
status: storage_enums::AttemptStatus,
connector: Option<String>,
connector_transaction_id: Option<String>,
payment_method_id: Option<String>,
error_code: Option<Option<String>>,
error_message: Option<Option<String>>,
error_reason: Option<Option<String>>,
connector_response_reference_id: Option<String>,
updated_by: String,
error_details: Box<Option<ErrorDetails>>,
},
StatusUpdate {
status: storage_enums::AttemptStatus,
updated_by: String,
},
ErrorUpdate {
connector: Option<String>,
status: storage_enums::AttemptStatus,
error_code: Option<Option<String>>,
error_message: Option<Option<String>>,
error_reason: Option<Option<String>>,
amount_capturable: Option<MinorUnit>,
updated_by: String,
unified_code: Option<Option<String>>,
unified_message: Option<Option<String>>,
connector_transaction_id: Option<String>,
payment_method_data: Option<serde_json::Value>,
encrypted_payment_method_data: Option<common_utils::encryption::Encryption>,
authentication_type: Option<storage_enums::AuthenticationType>,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/fraud_check.rs | crates/diesel_models/src/fraud_check.rs | use common_enums as storage_enums;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use masking::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{
enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType},
schema::fraud_check,
};
#[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)]
#[diesel(table_name = fraud_check, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct FraudCheck {
pub frm_id: String,
pub payment_id: common_utils::id_type::PaymentId,
pub merchant_id: common_utils::id_type::MerchantId,
pub attempt_id: String,
pub created_at: PrimitiveDateTime,
pub frm_name: String,
pub frm_transaction_id: Option<String>,
pub frm_transaction_type: FraudCheckType,
pub frm_status: FraudCheckStatus,
pub frm_score: Option<i32>,
pub frm_reason: Option<serde_json::Value>,
pub frm_error: Option<String>,
pub payment_details: Option<serde_json::Value>,
pub metadata: Option<serde_json::Value>,
pub modified_at: PrimitiveDateTime,
pub last_step: FraudCheckLastStep,
pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision.
}
#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = fraud_check)]
pub struct FraudCheckNew {
pub frm_id: String,
pub payment_id: common_utils::id_type::PaymentId,
pub merchant_id: common_utils::id_type::MerchantId,
pub attempt_id: String,
pub created_at: PrimitiveDateTime,
pub frm_name: String,
pub frm_transaction_id: Option<String>,
pub frm_transaction_type: FraudCheckType,
pub frm_status: FraudCheckStatus,
pub frm_score: Option<i32>,
pub frm_reason: Option<serde_json::Value>,
pub frm_error: Option<String>,
pub payment_details: Option<serde_json::Value>,
pub metadata: Option<serde_json::Value>,
pub modified_at: PrimitiveDateTime,
pub last_step: FraudCheckLastStep,
pub payment_capture_method: Option<storage_enums::CaptureMethod>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FraudCheckUpdate {
//Refer PaymentAttemptUpdate for other variants implementations
ResponseUpdate {
frm_status: FraudCheckStatus,
frm_transaction_id: Option<String>,
frm_reason: Option<serde_json::Value>,
frm_score: Option<i32>,
metadata: Option<serde_json::Value>,
modified_at: PrimitiveDateTime,
last_step: FraudCheckLastStep,
payment_capture_method: Option<storage_enums::CaptureMethod>,
},
ErrorUpdate {
status: FraudCheckStatus,
error_message: Option<Option<String>>,
},
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = fraud_check)]
pub struct FraudCheckUpdateInternal {
frm_status: Option<FraudCheckStatus>,
frm_transaction_id: Option<String>,
frm_reason: Option<serde_json::Value>,
frm_score: Option<i32>,
frm_error: Option<Option<String>>,
metadata: Option<serde_json::Value>,
last_step: FraudCheckLastStep,
payment_capture_method: Option<storage_enums::CaptureMethod>,
}
impl From<FraudCheckUpdate> for FraudCheckUpdateInternal {
fn from(fraud_check_update: FraudCheckUpdate) -> Self {
match fraud_check_update {
FraudCheckUpdate::ResponseUpdate {
frm_status,
frm_transaction_id,
frm_reason,
frm_score,
metadata,
modified_at: _,
last_step,
payment_capture_method,
} => Self {
frm_status: Some(frm_status),
frm_transaction_id,
frm_reason,
frm_score,
metadata,
last_step,
payment_capture_method,
..Default::default()
},
FraudCheckUpdate::ErrorUpdate {
status,
error_message,
} => Self {
frm_status: Some(status),
frm_error: error_message,
..Default::default()
},
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/callback_mapper.rs | crates/diesel_models/src/callback_mapper.rs | use common_enums::enums as common_enums;
use common_types::callback_mapper::CallbackMapperData;
use diesel::{Identifiable, Insertable, Queryable, Selectable};
use crate::schema::callback_mapper;
#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Insertable)]
#[diesel(table_name = callback_mapper, primary_key(id, type_), check_for_backend(diesel::pg::Pg))]
pub struct CallbackMapper {
pub id: String,
pub type_: common_enums::CallbackMapperIdType,
pub data: CallbackMapperData,
pub created_at: time::PrimitiveDateTime,
pub last_modified_at: time::PrimitiveDateTime,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/lib.rs | crates/diesel_models/src/lib.rs | pub mod address;
pub mod api_keys;
pub mod blocklist_lookup;
pub mod business_profile;
pub mod capture;
pub mod cards_info;
pub mod configs;
pub mod authentication;
pub mod authorization;
pub mod blocklist;
pub mod blocklist_fingerprint;
pub mod callback_mapper;
pub mod customers;
pub mod dispute;
pub mod dynamic_routing_stats;
pub mod enums;
pub mod ephemeral_key;
pub mod errors;
pub mod events;
pub mod file;
#[allow(unused)]
pub mod fraud_check;
pub mod generic_link;
pub mod gsm;
pub mod hyperswitch_ai_interaction;
pub mod invoice;
#[cfg(feature = "kv_store")]
pub mod kv;
pub mod locker_mock_up;
pub mod mandate;
pub mod merchant_account;
pub mod merchant_connector_account;
pub mod merchant_key_store;
pub mod organization;
pub mod payment_attempt;
pub mod payment_intent;
pub mod payment_link;
pub mod payment_method;
pub mod payout_attempt;
pub mod payouts;
pub mod process_tracker;
pub mod query;
pub mod refund;
pub mod relay;
pub mod reverse_lookup;
pub mod role;
pub mod routing_algorithm;
pub mod subscription;
pub mod types;
pub mod unified_translations;
#[cfg(feature = "v2")]
pub mod payment_methods_session;
#[allow(unused_qualifications)]
pub mod schema;
#[allow(unused_qualifications)]
pub mod schema_v2;
pub mod user;
pub mod user_authentication_method;
pub mod user_key_store;
pub mod user_role;
use diesel_impl::{DieselArray, OptionalDieselArray};
#[cfg(feature = "v2")]
use diesel_impl::{RequiredFromNullable, RequiredFromNullableWithDefault};
pub type StorageResult<T> = error_stack::Result<T, errors::DatabaseError>;
pub type PgPooledConn = async_bb8_diesel::Connection<diesel::PgConnection>;
pub use self::{
address::*, api_keys::*, callback_mapper::*, cards_info::*, configs::*, customers::*,
dispute::*, ephemeral_key::*, events::*, file::*, generic_link::*,
hyperswitch_ai_interaction::*, locker_mock_up::*, mandate::*, merchant_account::*,
merchant_connector_account::*, payment_attempt::*, payment_intent::*, payment_method::*,
payout_attempt::*, payouts::*, process_tracker::*, refund::*, reverse_lookup::*,
user_authentication_method::*,
};
/// The types and implementations provided by this module are required for the schema generated by
/// `diesel_cli` 2.0 to work with the types defined in Rust code. This is because
/// [`diesel`][diesel] 2.0 [changed the nullability of array elements][diesel-2.0-array-nullability],
/// which causes [`diesel`][diesel] to deserialize arrays as `Vec<Option<T>>`. To prevent declaring
/// array elements as `Option<T>`, this module provides types and implementations to deserialize
/// arrays as `Vec<T>`, considering only non-null values (`Some(T)`) among the deserialized
/// `Option<T>` values.
///
/// [diesel-2.0-array-nullability]: https://diesel.rs/guides/migration_guide.html#2-0-0-nullability-of-array-elements
#[doc(hidden)]
pub(crate) mod diesel_impl {
#[cfg(feature = "v2")]
use common_utils::{id_type, types};
use diesel::{
deserialize::FromSql,
pg::Pg,
sql_types::{Array, Nullable},
Queryable,
};
#[cfg(feature = "v2")]
use crate::enums;
pub struct DieselArray<T>(Vec<Option<T>>);
impl<T> From<DieselArray<T>> for Vec<T> {
fn from(array: DieselArray<T>) -> Self {
array.0.into_iter().flatten().collect()
}
}
impl<T, U> Queryable<Array<Nullable<U>>, Pg> for DieselArray<T>
where
T: FromSql<U, Pg>,
Vec<Option<T>>: FromSql<Array<Nullable<U>>, Pg>,
{
type Row = Vec<Option<T>>;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
Ok(Self(row))
}
}
pub struct OptionalDieselArray<T>(Option<Vec<Option<T>>>);
impl<T> From<OptionalDieselArray<T>> for Option<Vec<T>> {
fn from(option_array: OptionalDieselArray<T>) -> Self {
option_array
.0
.map(|array| array.into_iter().flatten().collect())
}
}
impl<T, U> Queryable<Nullable<Array<Nullable<U>>>, Pg> for OptionalDieselArray<T>
where
Option<Vec<Option<T>>>: FromSql<Nullable<Array<Nullable<U>>>, Pg>,
{
type Row = Option<Vec<Option<T>>>;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
Ok(Self(row))
}
}
#[cfg(feature = "v2")]
/// If the DB value is null, this wrapper will return an error when deserializing.
///
/// This is useful when you want to ensure that a field is always present, even if the database
/// value is NULL. If the database column contains a NULL value, an error will be returned.
pub struct RequiredFromNullable<T>(T);
#[cfg(feature = "v2")]
impl<T> RequiredFromNullable<T> {
/// Extracts the inner value from the wrapper
pub fn into_inner(self) -> T {
self.0
}
}
#[cfg(feature = "v2")]
impl<T, ST, DB> Queryable<Nullable<ST>, DB> for RequiredFromNullable<T>
where
DB: diesel::backend::Backend,
T: Queryable<ST, DB>,
Option<T::Row>: FromSql<Nullable<ST>, DB>,
ST: diesel::sql_types::SingleValue,
{
type Row = Option<T::Row>;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
match row {
Some(inner_row) => {
let value = T::build(inner_row)?;
Ok(Self(value))
}
None => Err("Cannot deserialize NULL value for required field. Check if the database column that should not be NULL contains a NULL value.".into()),
}
}
}
#[cfg(feature = "v2")]
/// If the DB value is null, this wrapper will provide a default value for the type `T`.
///
/// This is useful when you want to ensure that a field is always present, even if the database
/// value is NULL. The default value is provided by the `Default` trait implementation of `T`.
pub struct RequiredFromNullableWithDefault<T>(T);
#[cfg(feature = "v2")]
impl<T> RequiredFromNullableWithDefault<T> {
/// Extracts the inner value from the wrapper
pub fn into_inner(self) -> T {
self.0
}
}
#[cfg(feature = "v2")]
impl<T, ST, DB> Queryable<Nullable<ST>, DB> for RequiredFromNullableWithDefault<T>
where
DB: diesel::backend::Backend,
T: Queryable<ST, DB>,
T: Default,
Option<T::Row>: FromSql<Nullable<ST>, DB>,
ST: diesel::sql_types::SingleValue,
{
type Row = Option<T::Row>;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
match row {
Some(inner_row) => {
let value = T::build(inner_row)?;
Ok(Self(value))
}
None => Ok(Self(T::default())),
}
}
}
#[cfg(feature = "v2")]
/// Macro to implement From trait for types wrapped in RequiredFromNullable
#[macro_export]
macro_rules! impl_from_required_from_nullable {
($($type:ty),* $(,)?) => {
$(
impl From<$crate::RequiredFromNullable<$type>> for $type {
fn from(wrapper: $crate::RequiredFromNullable<$type>) -> Self {
wrapper.into_inner()
}
}
)*
};
}
#[cfg(feature = "v2")]
/// Macro to implement From trait for types wrapped in RequiredFromNullableWithDefault
#[macro_export]
macro_rules! impl_from_required_from_nullable_with_default {
($($type:ty),* $(,)?) => {
$(
impl From<$crate::RequiredFromNullableWithDefault<$type>> for $type {
fn from(wrapper: $crate::RequiredFromNullableWithDefault<$type>) -> Self {
wrapper.into_inner()
}
}
)*
};
}
#[cfg(feature = "v2")]
crate::impl_from_required_from_nullable_with_default!(enums::DeleteStatus);
#[cfg(feature = "v2")]
crate::impl_from_required_from_nullable!(
enums::AuthenticationType,
types::MinorUnit,
enums::PaymentMethod,
enums::Currency,
id_type::ProfileId,
time::PrimitiveDateTime,
id_type::RefundReferenceId,
);
}
pub(crate) mod metrics {
use router_env::{counter_metric, global_meter, histogram_metric_f64};
global_meter!(GLOBAL_METER, "ROUTER_API");
counter_metric!(DATABASE_CALLS_COUNT, GLOBAL_METER);
histogram_metric_f64!(DATABASE_CALL_TIME, GLOBAL_METER);
}
#[cfg(feature = "tokenization_v2")]
pub mod tokenization;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/dynamic_routing_stats.rs | crates/diesel_models/src/dynamic_routing_stats.rs | use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use crate::schema::dynamic_routing_stats;
#[derive(Clone, Debug, Eq, Insertable, PartialEq)]
#[diesel(table_name = dynamic_routing_stats)]
pub struct DynamicRoutingStatsNew {
pub payment_id: common_utils::id_type::PaymentId,
pub attempt_id: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_id: common_utils::id_type::ProfileId,
pub amount: common_utils::types::MinorUnit,
pub success_based_routing_connector: String,
pub payment_connector: String,
pub currency: Option<common_enums::Currency>,
pub payment_method: Option<common_enums::PaymentMethod>,
pub capture_method: Option<common_enums::CaptureMethod>,
pub authentication_type: Option<common_enums::AuthenticationType>,
pub payment_status: common_enums::AttemptStatus,
pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState,
pub created_at: time::PrimitiveDateTime,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub global_success_based_connector: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Insertable)]
#[diesel(table_name = dynamic_routing_stats, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct DynamicRoutingStats {
pub payment_id: common_utils::id_type::PaymentId,
pub attempt_id: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_id: common_utils::id_type::ProfileId,
pub amount: common_utils::types::MinorUnit,
pub success_based_routing_connector: String,
pub payment_connector: String,
pub currency: Option<common_enums::Currency>,
pub payment_method: Option<common_enums::PaymentMethod>,
pub capture_method: Option<common_enums::CaptureMethod>,
pub authentication_type: Option<common_enums::AuthenticationType>,
pub payment_status: common_enums::AttemptStatus,
pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState,
pub created_at: time::PrimitiveDateTime,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub global_success_based_connector: Option<String>,
}
#[derive(
Clone, Debug, Eq, PartialEq, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize,
)]
#[diesel(table_name = dynamic_routing_stats)]
pub struct DynamicRoutingStatsUpdate {
pub amount: common_utils::types::MinorUnit,
pub success_based_routing_connector: String,
pub payment_connector: String,
pub currency: Option<common_enums::Currency>,
pub payment_method: Option<common_enums::PaymentMethod>,
pub capture_method: Option<common_enums::CaptureMethod>,
pub authentication_type: Option<common_enums::AuthenticationType>,
pub payment_status: common_enums::AttemptStatus,
pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub global_success_based_connector: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/address.rs | crates/diesel_models/src/address.rs | use common_utils::{crypto, encryption::Encryption};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{enums, schema::address};
#[derive(Clone, Debug, Insertable, Serialize, Deserialize, router_derive::DebugAsDisplay)]
#[diesel(table_name = address)]
pub struct AddressNew {
pub address_id: String,
pub city: Option<String>,
pub country: Option<enums::CountryAlpha2>,
pub line1: Option<Encryption>,
pub line2: Option<Encryption>,
pub line3: Option<Encryption>,
pub state: Option<Encryption>,
pub zip: Option<Encryption>,
pub first_name: Option<Encryption>,
pub last_name: Option<Encryption>,
pub phone_number: Option<Encryption>,
pub country_code: Option<String>,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: Option<common_utils::id_type::PaymentId>,
pub created_at: PrimitiveDateTime,
pub modified_at: PrimitiveDateTime,
pub updated_by: String,
pub email: Option<Encryption>,
pub origin_zip: Option<Encryption>,
}
#[derive(Clone, Debug, Queryable, Identifiable, Selectable, Serialize, Deserialize)]
#[diesel(table_name = address, primary_key(address_id), check_for_backend(diesel::pg::Pg))]
pub struct Address {
pub address_id: String,
pub city: Option<String>,
pub country: Option<enums::CountryAlpha2>,
pub line1: Option<Encryption>,
pub line2: Option<Encryption>,
pub line3: Option<Encryption>,
pub state: Option<Encryption>,
pub zip: Option<Encryption>,
pub first_name: Option<Encryption>,
pub last_name: Option<Encryption>,
pub phone_number: Option<Encryption>,
pub country_code: Option<String>,
pub created_at: PrimitiveDateTime,
pub modified_at: PrimitiveDateTime,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: Option<common_utils::id_type::PaymentId>,
pub updated_by: String,
pub email: Option<Encryption>,
pub origin_zip: Option<Encryption>,
}
#[derive(Clone)]
// Intermediate struct to convert HashMap to Address
pub struct EncryptableAddress {
pub line1: crypto::OptionalEncryptableSecretString,
pub line2: crypto::OptionalEncryptableSecretString,
pub line3: crypto::OptionalEncryptableSecretString,
pub state: crypto::OptionalEncryptableSecretString,
pub zip: crypto::OptionalEncryptableSecretString,
pub first_name: crypto::OptionalEncryptableSecretString,
pub last_name: crypto::OptionalEncryptableSecretString,
pub phone_number: crypto::OptionalEncryptableSecretString,
pub email: crypto::OptionalEncryptableEmail,
pub origin_zip: crypto::OptionalEncryptableSecretString,
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = address)]
pub struct AddressUpdateInternal {
pub city: Option<String>,
pub country: Option<enums::CountryAlpha2>,
pub line1: Option<Encryption>,
pub line2: Option<Encryption>,
pub line3: Option<Encryption>,
pub state: Option<Encryption>,
pub zip: Option<Encryption>,
pub first_name: Option<Encryption>,
pub last_name: Option<Encryption>,
pub phone_number: Option<Encryption>,
pub country_code: Option<String>,
pub modified_at: PrimitiveDateTime,
pub updated_by: String,
pub email: Option<Encryption>,
pub origin_zip: Option<Encryption>,
}
impl AddressUpdateInternal {
pub fn create_address(self, source: Address) -> Address {
Address {
city: self.city,
country: self.country,
line1: self.line1,
line2: self.line2,
line3: self.line3,
state: self.state,
zip: self.zip,
first_name: self.first_name,
last_name: self.last_name,
phone_number: self.phone_number,
country_code: self.country_code,
modified_at: self.modified_at,
updated_by: self.updated_by,
origin_zip: self.origin_zip,
..source
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/customers.rs | crates/diesel_models/src/customers.rs | use common_enums::ApiVersion;
use common_utils::{encryption::Encryption, pii, types::Description};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;
#[cfg(feature = "v1")]
use crate::schema::customers;
#[cfg(feature = "v2")]
use crate::{
diesel_impl::RequiredFromNullableWithDefault, enums::DeleteStatus, schema_v2::customers,
};
#[cfg(feature = "v1")]
#[derive(
Clone, Debug, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize, Insertable,
)]
#[diesel(table_name = customers)]
pub struct CustomerNew {
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub name: Option<Encryption>,
pub email: Option<Encryption>,
pub phone: Option<Encryption>,
pub description: Option<Description>,
pub phone_country_code: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_customer: Option<pii::SecretSerdeValue>,
pub created_at: PrimitiveDateTime,
pub modified_at: PrimitiveDateTime,
pub address_id: Option<String>,
pub updated_by: Option<String>,
pub version: ApiVersion,
pub tax_registration_id: Option<Encryption>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
}
#[cfg(feature = "v1")]
impl CustomerNew {
pub fn update_storage_scheme(&mut self, storage_scheme: common_enums::MerchantStorageScheme) {
self.updated_by = Some(storage_scheme.to_string());
}
}
#[cfg(feature = "v1")]
impl From<CustomerNew> for Customer {
fn from(customer_new: CustomerNew) -> Self {
Self {
customer_id: customer_new.customer_id,
merchant_id: customer_new.merchant_id,
name: customer_new.name,
email: customer_new.email,
phone: customer_new.phone,
phone_country_code: customer_new.phone_country_code,
description: customer_new.description,
created_at: customer_new.created_at,
metadata: customer_new.metadata,
connector_customer: customer_new.connector_customer,
modified_at: customer_new.modified_at,
address_id: customer_new.address_id,
default_payment_method_id: None,
updated_by: customer_new.updated_by,
version: customer_new.version,
tax_registration_id: customer_new.tax_registration_id,
created_by: customer_new.created_by,
last_modified_by: customer_new.last_modified_by,
}
}
}
#[cfg(feature = "v2")]
#[derive(
Clone, Debug, Insertable, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize,
)]
#[diesel(table_name = customers, primary_key(id))]
pub struct CustomerNew {
pub merchant_id: common_utils::id_type::MerchantId,
pub name: Option<Encryption>,
pub email: Option<Encryption>,
pub phone: Option<Encryption>,
pub phone_country_code: Option<String>,
pub description: Option<Description>,
pub created_at: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>,
pub modified_at: PrimitiveDateTime,
pub default_payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>,
pub updated_by: Option<String>,
pub version: ApiVersion,
pub tax_registration_id: Option<Encryption>,
pub merchant_reference_id: Option<common_utils::id_type::CustomerId>,
pub default_billing_address: Option<Encryption>,
pub default_shipping_address: Option<Encryption>,
pub status: DeleteStatus,
pub id: common_utils::id_type::GlobalCustomerId,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
}
#[cfg(feature = "v2")]
impl CustomerNew {
pub fn update_storage_scheme(&mut self, storage_scheme: common_enums::MerchantStorageScheme) {
self.updated_by = Some(storage_scheme.to_string());
}
}
#[cfg(feature = "v2")]
impl From<CustomerNew> for Customer {
fn from(customer_new: CustomerNew) -> Self {
Self {
merchant_id: customer_new.merchant_id,
name: customer_new.name,
email: customer_new.email,
phone: customer_new.phone,
phone_country_code: customer_new.phone_country_code,
description: customer_new.description,
created_at: customer_new.created_at,
metadata: customer_new.metadata,
connector_customer: customer_new.connector_customer,
modified_at: customer_new.modified_at,
default_payment_method_id: None,
updated_by: customer_new.updated_by,
tax_registration_id: customer_new.tax_registration_id,
merchant_reference_id: customer_new.merchant_reference_id,
default_billing_address: customer_new.default_billing_address,
default_shipping_address: customer_new.default_shipping_address,
id: customer_new.id,
version: customer_new.version,
status: customer_new.status,
created_by: customer_new.created_by,
last_modified_by: customer_new.last_modified_by,
}
}
}
#[cfg(feature = "v1")]
#[derive(
Clone, Debug, Identifiable, Queryable, Selectable, serde::Deserialize, serde::Serialize,
)]
#[diesel(table_name = customers, primary_key(customer_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct Customer {
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub name: Option<Encryption>,
pub email: Option<Encryption>,
pub phone: Option<Encryption>,
pub phone_country_code: Option<String>,
pub description: Option<Description>,
pub created_at: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_customer: Option<pii::SecretSerdeValue>,
pub modified_at: PrimitiveDateTime,
pub address_id: Option<String>,
pub default_payment_method_id: Option<String>,
pub updated_by: Option<String>,
pub version: ApiVersion,
pub tax_registration_id: Option<Encryption>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(
Clone, Debug, Identifiable, Queryable, Selectable, serde::Serialize, serde::Deserialize,
)]
#[diesel(table_name = customers, primary_key(id))]
pub struct Customer {
pub merchant_id: common_utils::id_type::MerchantId,
pub name: Option<Encryption>,
pub email: Option<Encryption>,
pub phone: Option<Encryption>,
pub phone_country_code: Option<String>,
pub description: Option<Description>,
pub created_at: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>,
pub modified_at: PrimitiveDateTime,
pub default_payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>,
pub updated_by: Option<String>,
pub version: ApiVersion,
pub tax_registration_id: Option<Encryption>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
pub merchant_reference_id: Option<common_utils::id_type::CustomerId>,
pub default_billing_address: Option<Encryption>,
pub default_shipping_address: Option<Encryption>,
#[diesel(deserialize_as = RequiredFromNullableWithDefault<DeleteStatus>)]
pub status: DeleteStatus,
pub id: common_utils::id_type::GlobalCustomerId,
}
#[cfg(feature = "v1")]
#[derive(
Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize,
)]
#[diesel(table_name = customers)]
pub struct CustomerUpdateInternal {
pub name: Option<Encryption>,
pub email: Option<Encryption>,
pub phone: Option<Encryption>,
pub description: Option<Description>,
pub phone_country_code: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub modified_at: PrimitiveDateTime,
pub connector_customer: Option<pii::SecretSerdeValue>,
pub address_id: Option<String>,
pub default_payment_method_id: Option<Option<String>>,
pub updated_by: Option<String>,
pub tax_registration_id: Option<Encryption>,
pub last_modified_by: Option<String>,
}
#[cfg(feature = "v1")]
impl CustomerUpdateInternal {
pub fn apply_changeset(self, source: Customer) -> Customer {
let Self {
name,
email,
phone,
description,
phone_country_code,
metadata,
connector_customer,
address_id,
default_payment_method_id,
tax_registration_id,
last_modified_by,
..
} = self;
Customer {
name: name.map_or(source.name, Some),
email: email.map_or(source.email, Some),
phone: phone.map_or(source.phone, Some),
description: description.map_or(source.description, Some),
phone_country_code: phone_country_code.map_or(source.phone_country_code, Some),
metadata: metadata.map_or(source.metadata, Some),
modified_at: common_utils::date_time::now(),
connector_customer: connector_customer.map_or(source.connector_customer, Some),
address_id: address_id.map_or(source.address_id, Some),
default_payment_method_id: default_payment_method_id
.flatten()
.map_or(source.default_payment_method_id, Some),
tax_registration_id: tax_registration_id.map_or(source.tax_registration_id, Some),
last_modified_by: last_modified_by.or(source.last_modified_by),
..source
}
}
}
#[cfg(feature = "v2")]
#[derive(
Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize,
)]
#[diesel(table_name = customers)]
pub struct CustomerUpdateInternal {
pub name: Option<Encryption>,
pub email: Option<Encryption>,
pub phone: Option<Encryption>,
pub description: Option<Description>,
pub phone_country_code: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub modified_at: PrimitiveDateTime,
pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>,
pub default_payment_method_id: Option<Option<common_utils::id_type::GlobalPaymentMethodId>>,
pub updated_by: Option<String>,
pub default_billing_address: Option<Encryption>,
pub default_shipping_address: Option<Encryption>,
pub status: Option<DeleteStatus>,
pub tax_registration_id: Option<Encryption>,
pub last_modified_by: Option<String>,
}
#[cfg(feature = "v2")]
impl CustomerUpdateInternal {
pub fn apply_changeset(self, source: Customer) -> Customer {
let Self {
name,
email,
phone,
description,
phone_country_code,
metadata,
connector_customer,
default_payment_method_id,
default_billing_address,
default_shipping_address,
status,
tax_registration_id,
last_modified_by,
..
} = self;
Customer {
name: name.map_or(source.name, Some),
email: email.map_or(source.email, Some),
phone: phone.map_or(source.phone, Some),
description: description.map_or(source.description, Some),
phone_country_code: phone_country_code.map_or(source.phone_country_code, Some),
metadata: metadata.map_or(source.metadata, Some),
modified_at: common_utils::date_time::now(),
connector_customer: connector_customer.map_or(source.connector_customer, Some),
default_payment_method_id: default_payment_method_id
.flatten()
.map_or(source.default_payment_method_id, Some),
default_billing_address: default_billing_address
.map_or(source.default_billing_address, Some),
default_shipping_address: default_shipping_address
.map_or(source.default_shipping_address, Some),
status: status.unwrap_or(source.status),
tax_registration_id: tax_registration_id.map_or(source.tax_registration_id, Some),
last_modified_by: last_modified_by.or(source.last_modified_by),
..source
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/user_authentication_method.rs | crates/diesel_models/src/user_authentication_method.rs | use common_utils::encryption::Encryption;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;
use crate::{enums, schema::user_authentication_methods};
#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]
#[diesel(table_name = user_authentication_methods, check_for_backend(diesel::pg::Pg))]
pub struct UserAuthenticationMethod {
pub id: String,
pub auth_id: String,
pub owner_id: String,
pub owner_type: enums::Owner,
pub auth_type: enums::UserAuthType,
pub private_config: Option<Encryption>,
pub public_config: Option<serde_json::Value>,
pub allow_signup: bool,
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
pub email_domain: String,
}
#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = user_authentication_methods)]
pub struct UserAuthenticationMethodNew {
pub id: String,
pub auth_id: String,
pub owner_id: String,
pub owner_type: enums::Owner,
pub auth_type: enums::UserAuthType,
pub private_config: Option<Encryption>,
pub public_config: Option<serde_json::Value>,
pub allow_signup: bool,
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
pub email_domain: String,
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = user_authentication_methods)]
pub struct OrgAuthenticationMethodUpdateInternal {
pub private_config: Option<Encryption>,
pub public_config: Option<serde_json::Value>,
pub last_modified_at: PrimitiveDateTime,
pub email_domain: Option<String>,
}
pub enum UserAuthenticationMethodUpdate {
UpdateConfig {
private_config: Option<Encryption>,
public_config: Option<serde_json::Value>,
},
EmailDomain {
email_domain: String,
},
}
impl From<UserAuthenticationMethodUpdate> for OrgAuthenticationMethodUpdateInternal {
fn from(value: UserAuthenticationMethodUpdate) -> Self {
let last_modified_at = common_utils::date_time::now();
match value {
UserAuthenticationMethodUpdate::UpdateConfig {
private_config,
public_config,
} => Self {
private_config,
public_config,
last_modified_at,
email_domain: None,
},
UserAuthenticationMethodUpdate::EmailDomain { email_domain } => Self {
private_config: None,
public_config: None,
last_modified_at,
email_domain: Some(email_domain),
},
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/capture.rs | crates/diesel_models/src/capture.rs | use common_utils::types::{ConnectorTransactionId, MinorUnit};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{enums as storage_enums, schema::captures};
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize,
)]
#[diesel(table_name = captures, primary_key(capture_id), check_for_backend(diesel::pg::Pg))]
pub struct Capture {
pub capture_id: String,
pub payment_id: common_utils::id_type::PaymentId,
pub merchant_id: common_utils::id_type::MerchantId,
pub status: storage_enums::CaptureStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub connector: String,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub error_reason: Option<String>,
pub tax_amount: Option<MinorUnit>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub authorized_attempt_id: String,
pub connector_capture_id: Option<ConnectorTransactionId>,
pub capture_sequence: i16,
// reference to the capture at connector side
pub connector_response_reference_id: Option<String>,
/// INFO: This field is deprecated and replaced by processor_capture_data
pub connector_capture_data: Option<String>,
pub processor_capture_data: Option<String>,
}
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = captures)]
pub struct CaptureNew {
pub capture_id: String,
pub payment_id: common_utils::id_type::PaymentId,
pub merchant_id: common_utils::id_type::MerchantId,
pub status: storage_enums::CaptureStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub connector: String,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub error_reason: Option<String>,
pub tax_amount: Option<MinorUnit>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub authorized_attempt_id: String,
pub connector_capture_id: Option<ConnectorTransactionId>,
pub capture_sequence: i16,
pub connector_response_reference_id: Option<String>,
/// INFO: This field is deprecated and replaced by processor_capture_data
pub connector_capture_data: Option<String>,
pub processor_capture_data: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CaptureUpdate {
ResponseUpdate {
status: storage_enums::CaptureStatus,
connector_capture_id: Option<ConnectorTransactionId>,
connector_response_reference_id: Option<String>,
processor_capture_data: Option<String>,
},
ErrorUpdate {
status: storage_enums::CaptureStatus,
error_code: Option<String>,
error_message: Option<String>,
error_reason: Option<String>,
},
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = captures)]
pub struct CaptureUpdateInternal {
pub status: Option<storage_enums::CaptureStatus>,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub error_reason: Option<String>,
pub modified_at: Option<PrimitiveDateTime>,
pub connector_capture_id: Option<ConnectorTransactionId>,
pub connector_response_reference_id: Option<String>,
pub processor_capture_data: Option<String>,
}
impl CaptureUpdate {
pub fn apply_changeset(self, source: Capture) -> Capture {
let CaptureUpdateInternal {
status,
error_message,
error_code,
error_reason,
modified_at: _,
connector_capture_id,
connector_response_reference_id,
processor_capture_data,
} = self.into();
Capture {
status: status.unwrap_or(source.status),
error_message: error_message.or(source.error_message),
error_code: error_code.or(source.error_code),
error_reason: error_reason.or(source.error_reason),
modified_at: common_utils::date_time::now(),
connector_capture_id: connector_capture_id.or(source.connector_capture_id),
connector_response_reference_id: connector_response_reference_id
.or(source.connector_response_reference_id),
processor_capture_data: processor_capture_data.or(source.processor_capture_data),
..source
}
}
}
impl From<CaptureUpdate> for CaptureUpdateInternal {
fn from(payment_attempt_child_update: CaptureUpdate) -> Self {
let now = Some(common_utils::date_time::now());
match payment_attempt_child_update {
CaptureUpdate::ResponseUpdate {
status,
connector_capture_id: connector_transaction_id,
connector_response_reference_id,
processor_capture_data,
} => Self {
status: Some(status),
connector_capture_id: connector_transaction_id,
modified_at: now,
connector_response_reference_id,
processor_capture_data,
..Self::default()
},
CaptureUpdate::ErrorUpdate {
status,
error_code,
error_message,
error_reason,
} => Self {
status: Some(status),
error_code,
error_message,
error_reason,
modified_at: now,
..Self::default()
},
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/payment_link.rs | crates/diesel_models/src/payment_link.rs | use common_utils::types::MinorUnit;
use diesel::{Identifiable, Insertable, Queryable, Selectable};
use serde::{self, Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{enums as storage_enums, schema::payment_link};
#[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)]
#[diesel(table_name = payment_link, primary_key(payment_link_id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentLink {
pub payment_link_id: String,
pub payment_id: common_utils::id_type::PaymentId,
pub link_to_pay: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub last_modified_at: PrimitiveDateTime,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub fulfilment_time: Option<PrimitiveDateTime>,
pub custom_merchant_name: Option<String>,
pub payment_link_config: Option<serde_json::Value>,
pub description: Option<String>,
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub secure_link: Option<String>,
}
#[derive(
Clone,
Debug,
Eq,
PartialEq,
Insertable,
serde::Serialize,
serde::Deserialize,
router_derive::DebugAsDisplay,
)]
#[diesel(table_name = payment_link)]
pub struct PaymentLinkNew {
pub payment_link_id: String,
pub payment_id: common_utils::id_type::PaymentId,
pub link_to_pay: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub created_at: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_modified_at: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub fulfilment_time: Option<PrimitiveDateTime>,
pub custom_merchant_name: Option<String>,
pub payment_link_config: Option<serde_json::Value>,
pub description: Option<String>,
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub secure_link: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/dispute.rs | crates/diesel_models/src/dispute.rs | use common_utils::{
custom_serde,
types::{MinorUnit, StringMinorUnit},
};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use masking::Secret;
use serde::Serialize;
use time::PrimitiveDateTime;
use crate::{enums as storage_enums, schema::dispute};
#[derive(Clone, Debug, Insertable, Serialize, router_derive::DebugAsDisplay)]
#[diesel(table_name = dispute)]
#[serde(deny_unknown_fields)]
pub struct DisputeNew {
pub dispute_id: String,
pub amount: StringMinorUnit,
pub currency: String,
pub dispute_stage: storage_enums::DisputeStage,
pub dispute_status: storage_enums::DisputeStatus,
pub payment_id: common_utils::id_type::PaymentId,
pub attempt_id: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub connector_status: String,
pub connector_dispute_id: String,
pub connector_reason: Option<String>,
pub connector_reason_code: Option<String>,
pub challenge_required_by: Option<PrimitiveDateTime>,
pub connector_created_at: Option<PrimitiveDateTime>,
pub connector_updated_at: Option<PrimitiveDateTime>,
pub connector: String,
pub evidence: Option<Secret<serde_json::Value>>,
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub dispute_amount: MinorUnit,
pub organization_id: common_utils::id_type::OrganizationId,
pub dispute_currency: Option<storage_enums::Currency>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Identifiable, Queryable, Selectable)]
#[diesel(table_name = dispute, primary_key(dispute_id), check_for_backend(diesel::pg::Pg))]
pub struct Dispute {
pub dispute_id: String,
pub amount: StringMinorUnit,
pub currency: String,
pub dispute_stage: storage_enums::DisputeStage,
pub dispute_status: storage_enums::DisputeStatus,
pub payment_id: common_utils::id_type::PaymentId,
pub attempt_id: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub connector_status: String,
pub connector_dispute_id: String,
pub connector_reason: Option<String>,
pub connector_reason_code: Option<String>,
pub challenge_required_by: Option<PrimitiveDateTime>,
pub connector_created_at: Option<PrimitiveDateTime>,
pub connector_updated_at: Option<PrimitiveDateTime>,
#[serde(with = "custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub connector: String,
pub evidence: Secret<serde_json::Value>,
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub dispute_amount: MinorUnit,
pub organization_id: common_utils::id_type::OrganizationId,
pub dispute_currency: Option<storage_enums::Currency>,
}
#[derive(Debug)]
pub enum DisputeUpdate {
Update {
dispute_stage: storage_enums::DisputeStage,
dispute_status: storage_enums::DisputeStatus,
connector_status: String,
connector_reason: Option<String>,
connector_reason_code: Option<String>,
challenge_required_by: Option<PrimitiveDateTime>,
connector_updated_at: Option<PrimitiveDateTime>,
},
StatusUpdate {
dispute_status: storage_enums::DisputeStatus,
connector_status: Option<String>,
},
EvidenceUpdate {
evidence: Secret<serde_json::Value>,
},
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = dispute)]
pub struct DisputeUpdateInternal {
dispute_stage: Option<storage_enums::DisputeStage>,
dispute_status: Option<storage_enums::DisputeStatus>,
connector_status: Option<String>,
connector_reason: Option<String>,
connector_reason_code: Option<String>,
challenge_required_by: Option<PrimitiveDateTime>,
connector_updated_at: Option<PrimitiveDateTime>,
modified_at: PrimitiveDateTime,
evidence: Option<Secret<serde_json::Value>>,
}
impl From<DisputeUpdate> for DisputeUpdateInternal {
fn from(merchant_account_update: DisputeUpdate) -> Self {
match merchant_account_update {
DisputeUpdate::Update {
dispute_stage,
dispute_status,
connector_status,
connector_reason,
connector_reason_code,
challenge_required_by,
connector_updated_at,
} => Self {
dispute_stage: Some(dispute_stage),
dispute_status: Some(dispute_status),
connector_status: Some(connector_status),
connector_reason,
connector_reason_code,
challenge_required_by,
connector_updated_at,
modified_at: common_utils::date_time::now(),
evidence: None,
},
DisputeUpdate::StatusUpdate {
dispute_status,
connector_status,
} => Self {
dispute_status: Some(dispute_status),
connector_status,
modified_at: common_utils::date_time::now(),
dispute_stage: None,
connector_reason: None,
connector_reason_code: None,
challenge_required_by: None,
connector_updated_at: None,
evidence: None,
},
DisputeUpdate::EvidenceUpdate { evidence } => Self {
evidence: Some(evidence),
dispute_stage: None,
dispute_status: None,
connector_status: None,
connector_reason: None,
connector_reason_code: None,
challenge_required_by: None,
connector_updated_at: None,
modified_at: common_utils::date_time::now(),
},
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/process_tracker.rs | crates/diesel_models/src/process_tracker.rs | pub use common_enums::{enums::ProcessTrackerRunner, ApiVersion};
use common_utils::ext_traits::Encode;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use error_stack::ResultExt;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{
enums as storage_enums, enums::ApplicationSource, errors, schema::process_tracker,
StorageResult,
};
#[derive(
Clone,
Debug,
Eq,
PartialEq,
Deserialize,
Identifiable,
Queryable,
Selectable,
Serialize,
router_derive::DebugAsDisplay,
)]
#[diesel(table_name = process_tracker, check_for_backend(diesel::pg::Pg))]
pub struct ProcessTracker {
pub id: String,
pub name: Option<String>,
#[diesel(deserialize_as = super::DieselArray<String>)]
pub tag: Vec<String>,
pub runner: Option<String>,
pub retry_count: i32,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub schedule_time: Option<PrimitiveDateTime>,
pub rule: String,
pub tracking_data: serde_json::Value,
pub business_status: String,
pub status: storage_enums::ProcessTrackerStatus,
#[diesel(deserialize_as = super::DieselArray<String>)]
pub event: Vec<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub updated_at: PrimitiveDateTime,
pub version: ApiVersion,
pub application_source: Option<ApplicationSource>,
}
impl ProcessTracker {
#[inline(always)]
pub fn is_valid_business_status(&self, valid_statuses: &[&str]) -> bool {
valid_statuses.iter().any(|&x| x == self.business_status)
}
}
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = process_tracker)]
pub struct ProcessTrackerNew {
pub id: String,
pub name: Option<String>,
pub tag: Vec<String>,
pub runner: Option<String>,
pub retry_count: i32,
pub schedule_time: Option<PrimitiveDateTime>,
pub rule: String,
pub tracking_data: serde_json::Value,
pub business_status: String,
pub status: storage_enums::ProcessTrackerStatus,
pub event: Vec<String>,
pub created_at: PrimitiveDateTime,
pub updated_at: PrimitiveDateTime,
pub version: ApiVersion,
pub application_source: Option<ApplicationSource>,
}
impl ProcessTrackerNew {
#[allow(clippy::too_many_arguments)]
pub fn new<T>(
process_tracker_id: impl Into<String>,
task: impl Into<String>,
runner: ProcessTrackerRunner,
tag: impl IntoIterator<Item = impl Into<String>>,
tracking_data: T,
retry_count: Option<i32>,
schedule_time: PrimitiveDateTime,
api_version: ApiVersion,
application_source: ApplicationSource,
) -> StorageResult<Self>
where
T: Serialize + std::fmt::Debug,
{
let current_time = common_utils::date_time::now();
Ok(Self {
id: process_tracker_id.into(),
name: Some(task.into()),
tag: tag.into_iter().map(Into::into).collect(),
runner: Some(runner.to_string()),
retry_count: retry_count.unwrap_or(0),
schedule_time: Some(schedule_time),
rule: String::new(),
tracking_data: tracking_data
.encode_to_value()
.change_context(errors::DatabaseError::Others)
.attach_printable("Failed to serialize process tracker tracking data")?,
business_status: String::from(business_status::PENDING),
status: storage_enums::ProcessTrackerStatus::New,
event: vec![],
created_at: current_time,
updated_at: current_time,
version: api_version,
application_source: Some(application_source),
})
}
}
#[derive(Debug)]
pub enum ProcessTrackerUpdate {
Update {
name: Option<String>,
retry_count: Option<i32>,
schedule_time: Option<PrimitiveDateTime>,
tracking_data: Option<serde_json::Value>,
business_status: Option<String>,
status: Option<storage_enums::ProcessTrackerStatus>,
updated_at: Option<PrimitiveDateTime>,
},
StatusUpdate {
status: storage_enums::ProcessTrackerStatus,
business_status: Option<String>,
},
StatusRetryUpdate {
status: storage_enums::ProcessTrackerStatus,
retry_count: i32,
schedule_time: PrimitiveDateTime,
},
}
#[derive(Debug, Clone, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = process_tracker)]
pub struct ProcessTrackerUpdateInternal {
name: Option<String>,
retry_count: Option<i32>,
schedule_time: Option<PrimitiveDateTime>,
tracking_data: Option<serde_json::Value>,
business_status: Option<String>,
status: Option<storage_enums::ProcessTrackerStatus>,
updated_at: Option<PrimitiveDateTime>,
}
impl Default for ProcessTrackerUpdateInternal {
fn default() -> Self {
Self {
name: Option::default(),
retry_count: Option::default(),
schedule_time: Option::default(),
tracking_data: Option::default(),
business_status: Option::default(),
status: Option::default(),
updated_at: Some(common_utils::date_time::now()),
}
}
}
impl From<ProcessTrackerUpdate> for ProcessTrackerUpdateInternal {
fn from(process_tracker_update: ProcessTrackerUpdate) -> Self {
match process_tracker_update {
ProcessTrackerUpdate::Update {
name,
retry_count,
schedule_time,
tracking_data,
business_status,
status,
updated_at,
} => Self {
name,
retry_count,
schedule_time,
tracking_data,
business_status,
status,
updated_at,
},
ProcessTrackerUpdate::StatusUpdate {
status,
business_status,
} => Self {
status: Some(status),
business_status,
..Default::default()
},
ProcessTrackerUpdate::StatusRetryUpdate {
status,
retry_count,
schedule_time,
} => Self {
status: Some(status),
retry_count: Some(retry_count),
schedule_time: Some(schedule_time),
..Default::default()
},
}
}
}
#[cfg(test)]
mod tests {
use common_utils::ext_traits::StringExt;
use super::ProcessTrackerRunner;
#[test]
fn test_enum_to_string() {
let string_format = "PAYMENTS_SYNC_WORKFLOW".to_string();
let enum_format: ProcessTrackerRunner =
string_format.parse_enum("ProcessTrackerRunner").unwrap();
assert_eq!(enum_format, ProcessTrackerRunner::PaymentsSyncWorkflow);
}
}
pub mod business_status {
/// Indicates that an irrecoverable error occurred during the workflow execution.
pub const GLOBAL_FAILURE: &str = "GLOBAL_FAILURE";
/// Task successfully completed by consumer.
/// A task that reaches this status should not be retried (rescheduled for execution) later.
pub const COMPLETED_BY_PT: &str = "COMPLETED_BY_PT";
/// An error occurred during the workflow execution which prevents further execution and
/// retries.
/// A task that reaches this status should not be retried (rescheduled for execution) later.
pub const FAILURE: &str = "FAILURE";
/// The resource associated with the task was removed, due to which further retries can/should
/// not be done.
pub const REVOKED: &str = "Revoked";
/// The task was executed for the maximum possible number of times without a successful outcome.
/// A task that reaches this status should not be retried (rescheduled for execution) later.
pub const RETRIES_EXCEEDED: &str = "RETRIES_EXCEEDED";
/// The outgoing webhook was successfully delivered in the initial attempt.
/// Further retries of the task are not required.
pub const INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL: &str = "INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL";
/// Indicates that an error occurred during the workflow execution.
/// This status is typically set by the workflow error handler.
/// A task that reaches this status should not be retried (rescheduled for execution) later.
pub const GLOBAL_ERROR: &str = "GLOBAL_ERROR";
/// The resource associated with the task has been significantly modified since the task was
/// created, due to which further retries of the current task are not required.
/// A task that reaches this status should not be retried (rescheduled for execution) later.
pub const RESOURCE_STATUS_MISMATCH: &str = "RESOURCE_STATUS_MISMATCH";
/// Business status set for newly created tasks.
pub const PENDING: &str = "Pending";
/// For the PCR Workflow
///
/// This status indicates the completion of a execute task
pub const EXECUTE_WORKFLOW_COMPLETE: &str = "COMPLETED_EXECUTE_TASK";
/// This status indicates the failure of a execute task
pub const EXECUTE_WORKFLOW_FAILURE: &str = "FAILED_EXECUTE_TASK";
/// This status indicates that the execute task was completed to trigger the psync task
pub const EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC: &str = "COMPLETED_EXECUTE_TASK_TO_TRIGGER_PSYNC";
/// This status indicates that the execute task was completed to trigger the review task
pub const EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW: &str =
"COMPLETED_EXECUTE_TASK_TO_TRIGGER_REVIEW";
/// This status indicates that the requeue was triggered for execute task
pub const EXECUTE_WORKFLOW_REQUEUE: &str = "TRIGGER_REQUEUE_FOR_EXECUTE_WORKFLOW";
/// This status indicates the completion of a psync task
pub const PSYNC_WORKFLOW_COMPLETE: &str = "COMPLETED_PSYNC_TASK";
/// This status indicates that the psync task was completed to trigger the review task
pub const PSYNC_WORKFLOW_COMPLETE_FOR_REVIEW: &str = "COMPLETED_PSYNC_TASK_TO_TRIGGER_REVIEW";
/// This status indicates that the requeue was triggered for psync task
pub const PSYNC_WORKFLOW_REQUEUE: &str = "TRIGGER_REQUEUE_FOR_PSYNC_WORKFLOW";
/// This status indicates the completion of a review task
pub const REVIEW_WORKFLOW_COMPLETE: &str = "COMPLETED_REVIEW_TASK";
/// For the CALCULATE_WORKFLOW
///
/// This status indicates an invoice is queued
pub const CALCULATE_WORKFLOW_QUEUED: &str = "CALCULATE_WORKFLOW_QUEUED";
/// This status indicates an invoice has been declined due to hard decline
pub const CALCULATE_WORKFLOW_FINISH: &str = "FAILED_DUE_TO_HARD_DECLINE_ERROR";
/// This status indicates that the invoice is scheduled with the best available token
pub const CALCULATE_WORKFLOW_SCHEDULED: &str = "CALCULATE_WORKFLOW_SCHEDULED";
/// This status indicates the invoice is in payment sync state
pub const CALCULATE_WORKFLOW_PROCESSING: &str = "CALCULATE_WORKFLOW_PROCESSING";
/// This status indicates the workflow has completed successfully when the invoice is paid
pub const CALCULATE_WORKFLOW_COMPLETE: &str = "CALCULATE_WORKFLOW_COMPLETE";
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/ephemeral_key.rs | crates/diesel_models/src/ephemeral_key.rs | #[cfg(feature = "v2")]
use masking::{PeekInterface, Secret};
#[cfg(feature = "v2")]
pub struct ClientSecretTypeNew {
pub id: common_utils::id_type::ClientSecretId,
pub merchant_id: common_utils::id_type::MerchantId,
pub secret: Secret<String>,
pub resource_id: common_utils::types::authentication::ResourceId,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ClientSecretType {
pub id: common_utils::id_type::ClientSecretId,
pub merchant_id: common_utils::id_type::MerchantId,
pub resource_id: common_utils::types::authentication::ResourceId,
pub created_at: time::PrimitiveDateTime,
pub expires: time::PrimitiveDateTime,
pub secret: Secret<String>,
}
#[cfg(feature = "v2")]
impl ClientSecretType {
pub fn generate_secret_key(&self) -> String {
format!("cs_{}", self.secret.peek())
}
}
pub struct EphemeralKeyNew {
pub id: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: common_utils::id_type::CustomerId,
pub secret: String,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct EphemeralKey {
pub id: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: common_utils::id_type::CustomerId,
pub created_at: i64,
pub expires: i64,
pub secret: String,
}
impl common_utils::events::ApiEventMetric for EphemeralKey {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Miscellaneous)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/payout_attempt.rs | crates/diesel_models/src/payout_attempt.rs | use common_utils::{
payout_method_utils, pii,
types::{UnifiedCode, UnifiedMessage},
};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{self, Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{enums as storage_enums, schema::payout_attempt};
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize,
)]
#[diesel(table_name = payout_attempt, primary_key(payout_attempt_id), check_for_backend(diesel::pg::Pg))]
pub struct PayoutAttempt {
pub payout_attempt_id: String,
pub payout_id: common_utils::id_type::PayoutId,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub merchant_id: common_utils::id_type::MerchantId,
pub address_id: Option<String>,
pub connector: Option<String>,
pub connector_payout_id: Option<String>,
pub payout_token: Option<String>,
pub status: storage_enums::PayoutStatus,
pub is_eligible: Option<bool>,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub last_modified_at: PrimitiveDateTime,
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub routing_info: Option<serde_json::Value>,
pub unified_code: Option<UnifiedCode>,
pub unified_message: Option<UnifiedMessage>,
pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>,
pub merchant_order_reference_id: Option<String>,
pub payout_connector_metadata: Option<pii::SecretSerdeValue>,
}
#[derive(
Clone,
Debug,
Eq,
PartialEq,
Insertable,
serde::Serialize,
serde::Deserialize,
router_derive::DebugAsDisplay,
router_derive::Setter,
)]
#[diesel(table_name = payout_attempt)]
pub struct PayoutAttemptNew {
pub payout_attempt_id: String,
pub payout_id: common_utils::id_type::PayoutId,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub merchant_id: common_utils::id_type::MerchantId,
pub address_id: Option<String>,
pub connector: Option<String>,
pub connector_payout_id: Option<String>,
pub payout_token: Option<String>,
pub status: storage_enums::PayoutStatus,
pub is_eligible: Option<bool>,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub last_modified_at: PrimitiveDateTime,
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub routing_info: Option<serde_json::Value>,
pub unified_code: Option<UnifiedCode>,
pub unified_message: Option<UnifiedMessage>,
pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>,
pub merchant_order_reference_id: Option<String>,
pub payout_connector_metadata: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PayoutAttemptUpdate {
StatusUpdate {
connector_payout_id: Option<String>,
status: storage_enums::PayoutStatus,
error_message: Option<String>,
error_code: Option<String>,
is_eligible: Option<bool>,
unified_code: Option<UnifiedCode>,
unified_message: Option<UnifiedMessage>,
payout_connector_metadata: Option<pii::SecretSerdeValue>,
},
PayoutTokenUpdate {
payout_token: String,
},
BusinessUpdate {
business_country: Option<storage_enums::CountryAlpha2>,
business_label: Option<String>,
address_id: Option<String>,
customer_id: Option<common_utils::id_type::CustomerId>,
},
UpdateRouting {
connector: String,
routing_info: Option<serde_json::Value>,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
},
AdditionalPayoutMethodDataUpdate {
additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>,
},
ManualUpdate {
status: Option<storage_enums::PayoutStatus>,
error_code: Option<String>,
error_message: Option<String>,
unified_code: Option<UnifiedCode>,
unified_message: Option<UnifiedMessage>,
connector_payout_id: Option<String>,
},
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = payout_attempt)]
pub struct PayoutAttemptUpdateInternal {
pub payout_token: Option<String>,
pub connector_payout_id: Option<String>,
pub status: Option<storage_enums::PayoutStatus>,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub is_eligible: Option<bool>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub connector: Option<String>,
pub routing_info: Option<serde_json::Value>,
pub last_modified_at: PrimitiveDateTime,
pub address_id: Option<String>,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub unified_code: Option<UnifiedCode>,
pub unified_message: Option<UnifiedMessage>,
pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>,
pub merchant_order_reference_id: Option<String>,
pub payout_connector_metadata: Option<pii::SecretSerdeValue>,
}
impl Default for PayoutAttemptUpdateInternal {
fn default() -> Self {
Self {
payout_token: None,
connector_payout_id: None,
status: None,
error_message: None,
error_code: None,
is_eligible: None,
business_country: None,
business_label: None,
connector: None,
routing_info: None,
merchant_connector_id: None,
last_modified_at: common_utils::date_time::now(),
address_id: None,
customer_id: None,
unified_code: None,
unified_message: None,
additional_payout_method_data: None,
merchant_order_reference_id: None,
payout_connector_metadata: None,
}
}
}
impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {
fn from(payout_update: PayoutAttemptUpdate) -> Self {
match payout_update {
PayoutAttemptUpdate::PayoutTokenUpdate { payout_token } => Self {
payout_token: Some(payout_token),
..Default::default()
},
PayoutAttemptUpdate::StatusUpdate {
connector_payout_id,
status,
error_message,
error_code,
is_eligible,
unified_code,
unified_message,
payout_connector_metadata,
} => Self {
connector_payout_id,
status: Some(status),
error_message,
error_code,
is_eligible,
unified_code,
unified_message,
payout_connector_metadata,
..Default::default()
},
PayoutAttemptUpdate::BusinessUpdate {
business_country,
business_label,
address_id,
customer_id,
} => Self {
business_country,
business_label,
address_id,
customer_id,
..Default::default()
},
PayoutAttemptUpdate::UpdateRouting {
connector,
routing_info,
merchant_connector_id,
} => Self {
connector: Some(connector),
routing_info,
merchant_connector_id,
..Default::default()
},
PayoutAttemptUpdate::AdditionalPayoutMethodDataUpdate {
additional_payout_method_data,
} => Self {
additional_payout_method_data,
..Default::default()
},
PayoutAttemptUpdate::ManualUpdate {
status,
error_code,
error_message,
unified_code,
unified_message,
connector_payout_id,
} => Self {
status,
error_code,
error_message,
unified_code,
unified_message,
connector_payout_id,
..Default::default()
},
}
}
}
impl PayoutAttemptUpdate {
pub fn apply_changeset(self, source: PayoutAttempt) -> PayoutAttempt {
let PayoutAttemptUpdateInternal {
payout_token,
connector_payout_id,
status,
error_message,
error_code,
is_eligible,
business_country,
business_label,
connector,
routing_info,
last_modified_at,
address_id,
customer_id,
merchant_connector_id,
unified_code,
unified_message,
additional_payout_method_data,
merchant_order_reference_id,
payout_connector_metadata,
} = self.into();
PayoutAttempt {
payout_token: payout_token.or(source.payout_token),
connector_payout_id: connector_payout_id.or(source.connector_payout_id),
status: status.unwrap_or(source.status),
error_message: error_message.or(source.error_message),
error_code: error_code.or(source.error_code),
is_eligible: is_eligible.or(source.is_eligible),
business_country: business_country.or(source.business_country),
business_label: business_label.or(source.business_label),
connector: connector.or(source.connector),
routing_info: routing_info.or(source.routing_info),
last_modified_at,
address_id: address_id.or(source.address_id),
customer_id: customer_id.or(source.customer_id),
merchant_connector_id: merchant_connector_id.or(source.merchant_connector_id),
unified_code: unified_code.or(source.unified_code),
unified_message: unified_message.or(source.unified_message),
additional_payout_method_data: additional_payout_method_data
.or(source.additional_payout_method_data),
merchant_order_reference_id: merchant_order_reference_id
.or(source.merchant_order_reference_id),
payout_connector_metadata: payout_connector_metadata
.or(source.payout_connector_metadata),
..source
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/organization.rs | crates/diesel_models/src/organization.rs | use common_utils::{id_type, pii};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
#[cfg(feature = "v1")]
use crate::schema::organization;
#[cfg(feature = "v2")]
use crate::schema_v2::organization;
pub trait OrganizationBridge {
fn get_organization_id(&self) -> id_type::OrganizationId;
fn get_organization_name(&self) -> Option<String>;
fn set_organization_name(&mut self, organization_name: String);
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]
#[diesel(
table_name = organization,
primary_key(org_id),
check_for_backend(diesel::pg::Pg)
)]
pub struct Organization {
org_id: id_type::OrganizationId,
org_name: Option<String>,
pub organization_details: Option<pii::SecretSerdeValue>,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
#[allow(dead_code)]
id: Option<id_type::OrganizationId>,
#[allow(dead_code)]
organization_name: Option<String>,
pub version: common_enums::ApiVersion,
pub organization_type: Option<common_enums::OrganizationType>,
pub platform_merchant_id: Option<id_type::MerchantId>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]
#[diesel(
table_name = organization,
primary_key(id),
check_for_backend(diesel::pg::Pg)
)]
pub struct Organization {
pub organization_details: Option<pii::SecretSerdeValue>,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
id: id_type::OrganizationId,
organization_name: Option<String>,
pub version: common_enums::ApiVersion,
pub organization_type: Option<common_enums::OrganizationType>,
pub platform_merchant_id: Option<id_type::MerchantId>,
}
#[cfg(feature = "v1")]
impl Organization {
pub fn new(org_new: OrganizationNew) -> Self {
let OrganizationNew {
org_id,
org_name,
organization_details,
metadata,
created_at,
modified_at,
id: _,
organization_name: _,
version,
organization_type,
platform_merchant_id,
} = org_new;
Self {
id: Some(org_id.clone()),
organization_name: org_name.clone(),
org_id,
org_name,
organization_details,
metadata,
created_at,
modified_at,
version,
organization_type: Some(organization_type),
platform_merchant_id,
}
}
pub fn get_organization_type(&self) -> common_enums::OrganizationType {
self.organization_type.unwrap_or_default()
}
}
#[cfg(feature = "v2")]
impl Organization {
pub fn new(org_new: OrganizationNew) -> Self {
let OrganizationNew {
id,
organization_name,
organization_details,
metadata,
created_at,
modified_at,
version,
organization_type,
platform_merchant_id,
} = org_new;
Self {
id,
organization_name,
organization_details,
metadata,
created_at,
modified_at,
version,
organization_type: Some(organization_type),
platform_merchant_id,
}
}
pub fn get_organization_type(&self) -> common_enums::OrganizationType {
self.organization_type.unwrap_or_default()
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Insertable)]
#[diesel(table_name = organization, primary_key(org_id))]
pub struct OrganizationNew {
org_id: id_type::OrganizationId,
org_name: Option<String>,
id: id_type::OrganizationId,
organization_name: Option<String>,
pub organization_details: Option<pii::SecretSerdeValue>,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub version: common_enums::ApiVersion,
pub organization_type: common_enums::OrganizationType,
pub platform_merchant_id: Option<id_type::MerchantId>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Insertable)]
#[diesel(table_name = organization, primary_key(id))]
pub struct OrganizationNew {
id: id_type::OrganizationId,
organization_name: Option<String>,
pub organization_details: Option<pii::SecretSerdeValue>,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub version: common_enums::ApiVersion,
pub organization_type: common_enums::OrganizationType,
pub platform_merchant_id: Option<id_type::MerchantId>,
}
#[cfg(feature = "v1")]
impl OrganizationNew {
pub fn new(
id: id_type::OrganizationId,
organization_type: common_enums::OrganizationType,
organization_name: Option<String>,
) -> Self {
Self {
org_id: id.clone(),
org_name: organization_name.clone(),
id,
organization_name,
organization_details: None,
metadata: None,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
version: common_types::consts::API_VERSION,
organization_type,
platform_merchant_id: None,
}
}
}
#[cfg(feature = "v2")]
impl OrganizationNew {
pub fn new(
id: id_type::OrganizationId,
organization_type: common_enums::OrganizationType,
organization_name: Option<String>,
) -> Self {
Self {
id,
organization_name,
organization_details: None,
metadata: None,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
version: common_types::consts::API_VERSION,
organization_type,
platform_merchant_id: None,
}
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, AsChangeset)]
#[diesel(table_name = organization)]
pub struct OrganizationUpdateInternal {
org_name: Option<String>,
organization_name: Option<String>,
organization_details: Option<pii::SecretSerdeValue>,
metadata: Option<pii::SecretSerdeValue>,
modified_at: time::PrimitiveDateTime,
platform_merchant_id: Option<id_type::MerchantId>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, AsChangeset)]
#[diesel(table_name = organization)]
pub struct OrganizationUpdateInternal {
organization_name: Option<String>,
organization_details: Option<pii::SecretSerdeValue>,
metadata: Option<pii::SecretSerdeValue>,
modified_at: time::PrimitiveDateTime,
platform_merchant_id: Option<id_type::MerchantId>,
}
pub enum OrganizationUpdate {
Update {
organization_name: Option<String>,
organization_details: Option<pii::SecretSerdeValue>,
metadata: Option<pii::SecretSerdeValue>,
platform_merchant_id: Option<id_type::MerchantId>,
},
}
#[cfg(feature = "v1")]
impl From<OrganizationUpdate> for OrganizationUpdateInternal {
fn from(value: OrganizationUpdate) -> Self {
match value {
OrganizationUpdate::Update {
organization_name,
organization_details,
metadata,
platform_merchant_id,
} => Self {
org_name: organization_name.clone(),
organization_name,
organization_details,
metadata,
modified_at: common_utils::date_time::now(),
platform_merchant_id,
},
}
}
}
#[cfg(feature = "v2")]
impl From<OrganizationUpdate> for OrganizationUpdateInternal {
fn from(value: OrganizationUpdate) -> Self {
match value {
OrganizationUpdate::Update {
organization_name,
organization_details,
metadata,
platform_merchant_id,
} => Self {
organization_name,
organization_details,
metadata,
modified_at: common_utils::date_time::now(),
platform_merchant_id,
},
}
}
}
#[cfg(feature = "v1")]
impl OrganizationBridge for Organization {
fn get_organization_id(&self) -> id_type::OrganizationId {
self.org_id.clone()
}
fn get_organization_name(&self) -> Option<String> {
self.org_name.clone()
}
fn set_organization_name(&mut self, organization_name: String) {
self.org_name = Some(organization_name);
}
}
#[cfg(feature = "v1")]
impl OrganizationBridge for OrganizationNew {
fn get_organization_id(&self) -> id_type::OrganizationId {
self.org_id.clone()
}
fn get_organization_name(&self) -> Option<String> {
self.org_name.clone()
}
fn set_organization_name(&mut self, organization_name: String) {
self.org_name = Some(organization_name);
}
}
#[cfg(feature = "v2")]
impl OrganizationBridge for Organization {
fn get_organization_id(&self) -> id_type::OrganizationId {
self.id.clone()
}
fn get_organization_name(&self) -> Option<String> {
self.organization_name.clone()
}
fn set_organization_name(&mut self, organization_name: String) {
self.organization_name = Some(organization_name);
}
}
#[cfg(feature = "v2")]
impl OrganizationBridge for OrganizationNew {
fn get_organization_id(&self) -> id_type::OrganizationId {
self.id.clone()
}
fn get_organization_name(&self) -> Option<String> {
self.organization_name.clone()
}
fn set_organization_name(&mut self, organization_name: String) {
self.organization_name = Some(organization_name);
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/payment_intent.rs | crates/diesel_models/src/payment_intent.rs | use common_enums::{PaymentMethodType, RequestIncrementalAuthorization};
use common_types::primitive_wrappers::{
EnablePartialAuthorizationBool, RequestExtendedAuthorizationBool,
};
use common_utils::{encryption::Encryption, pii, types::MinorUnit};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use masking::ExposeInterface;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
#[cfg(feature = "v1")]
use crate::schema::payment_intent;
#[cfg(feature = "v2")]
use crate::schema_v2::payment_intent;
#[cfg(feature = "v2")]
use crate::types::{FeatureMetadata, OrderDetailsWithAmount};
#[cfg(feature = "v2")]
use crate::RequiredFromNullable;
use crate::{business_profile::PaymentLinkBackgroundImageConfig, enums as storage_enums};
#[cfg(feature = "v2")]
#[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)]
#[diesel(table_name = payment_intent, primary_key(id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentIntent {
pub merchant_id: common_utils::id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: MinorUnit,
#[diesel(deserialize_as = RequiredFromNullable<storage_enums::Currency>)]
pub currency: storage_enums::Currency,
pub amount_captured: Option<MinorUnit>,
pub customer_id: Option<common_utils::id_type::GlobalCustomerId>,
pub description: Option<common_utils::types::Description>,
pub return_url: Option<common_utils::types::Url>,
pub metadata: Option<pii::SecretSerdeValue>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>,
#[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)]
pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>,
pub allowed_payment_method_types: Option<pii::SecretSerdeValue>,
pub connector_metadata: Option<pii::SecretSerdeValue>,
pub feature_metadata: Option<FeatureMetadata>,
pub attempt_count: i16,
#[diesel(deserialize_as = RequiredFromNullable<common_utils::id_type::ProfileId>)]
pub profile_id: common_utils::id_type::ProfileId,
pub payment_link_id: Option<String>,
pub updated_by: String,
pub surcharge_applicable: Option<bool>,
pub request_incremental_authorization: Option<RequestIncrementalAuthorization>,
pub authorization_count: Option<i32>,
#[diesel(deserialize_as = RequiredFromNullable<PrimitiveDateTime>)]
pub session_expiry: PrimitiveDateTime,
pub request_external_three_ds_authentication: Option<bool>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
pub customer_details: Option<Encryption>,
pub shipping_cost: Option<MinorUnit>,
pub organization_id: common_utils::id_type::OrganizationId,
pub tax_details: Option<TaxDetails>,
pub skip_external_tax_calculation: Option<bool>,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
pub platform_merchant_id: Option<common_utils::id_type::MerchantId>,
pub force_3ds_challenge: Option<bool>,
pub force_3ds_challenge_trigger: Option<bool>,
pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,
pub created_by: Option<String>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_payment_id_from_merchant: Option<bool>,
pub payment_channel: Option<common_enums::PaymentChannel>,
pub tax_status: Option<common_enums::TaxStatus>,
pub discount_amount: Option<MinorUnit>,
pub shipping_amount_tax: Option<MinorUnit>,
pub duty_amount: Option<MinorUnit>,
pub order_date: Option<PrimitiveDateTime>,
pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>,
pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>,
pub mit_category: Option<storage_enums::MitCategory>,
pub billing_descriptor: Option<common_types::payments::BillingDescriptor>,
pub tokenization: Option<common_enums::Tokenization>,
pub partner_merchant_identifier_details:
Option<common_types::payments::PartnerMerchantIdentifierDetails>,
pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>,
pub billing_address: Option<Encryption>,
pub shipping_address: Option<Encryption>,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub authentication_type: Option<common_enums::AuthenticationType>,
pub prerouting_algorithm: Option<serde_json::Value>,
pub surcharge_amount: Option<MinorUnit>,
pub tax_on_surcharge: Option<MinorUnit>,
// Denotes the action(approve or reject) taken by merchant in case of manual review.
// Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment
pub frm_merchant_decision: Option<common_enums::MerchantDecision>,
pub statement_descriptor: Option<common_utils::types::StatementDescriptor>,
pub enable_payment_link: Option<bool>,
pub apply_mit_exemption: Option<bool>,
pub customer_present: Option<bool>,
pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub payment_link_config: Option<PaymentLinkConfigRequestForPayments>,
pub id: common_utils::id_type::GlobalPaymentId,
pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>,
pub active_attempts_group_id: Option<common_utils::id_type::GlobalAttemptGroupId>,
pub active_attempt_id_type: Option<common_enums::ActiveAttemptIDType>,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)]
#[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentIntent {
pub payment_id: common_utils::id_type::PaymentId,
pub merchant_id: common_utils::id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub amount_captured: Option<MinorUnit>,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub description: Option<String>,
pub return_url: Option<String>,
pub metadata: Option<serde_json::Value>,
pub connector_id: Option<String>,
pub shipping_address_id: Option<String>,
pub billing_address_id: Option<String>,
pub statement_descriptor_name: Option<String>,
pub statement_descriptor_suffix: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub off_session: Option<bool>,
pub client_secret: Option<String>,
pub active_attempt_id: String,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub order_details: Option<Vec<pii::SecretSerdeValue>>,
pub allowed_payment_method_types: Option<serde_json::Value>,
pub connector_metadata: Option<serde_json::Value>,
pub feature_metadata: Option<serde_json::Value>,
pub attempt_count: i16,
pub profile_id: Option<common_utils::id_type::ProfileId>,
// Denotes the action(approve or reject) taken by merchant in case of manual review.
// Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment
pub merchant_decision: Option<String>,
pub payment_link_id: Option<String>,
pub payment_confirm_source: Option<storage_enums::PaymentSource>,
pub updated_by: String,
pub surcharge_applicable: Option<bool>,
pub request_incremental_authorization: Option<RequestIncrementalAuthorization>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
pub session_expiry: Option<PrimitiveDateTime>,
pub fingerprint_id: Option<String>,
pub request_external_three_ds_authentication: Option<bool>,
pub charges: Option<pii::SecretSerdeValue>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
pub customer_details: Option<Encryption>,
pub billing_details: Option<Encryption>,
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryption>,
pub is_payment_processor_token_flow: Option<bool>,
pub shipping_cost: Option<MinorUnit>,
pub organization_id: common_utils::id_type::OrganizationId,
pub tax_details: Option<TaxDetails>,
pub skip_external_tax_calculation: Option<bool>,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
pub platform_merchant_id: Option<common_utils::id_type::MerchantId>,
pub force_3ds_challenge: Option<bool>,
pub force_3ds_challenge_trigger: Option<bool>,
pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,
pub created_by: Option<String>,
pub is_iframe_redirection_enabled: Option<bool>,
pub extended_return_url: Option<String>,
pub is_payment_id_from_merchant: Option<bool>,
pub payment_channel: Option<common_enums::PaymentChannel>,
pub tax_status: Option<common_enums::TaxStatus>,
pub discount_amount: Option<MinorUnit>,
pub shipping_amount_tax: Option<MinorUnit>,
pub duty_amount: Option<MinorUnit>,
pub order_date: Option<PrimitiveDateTime>,
pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>,
pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>,
pub mit_category: Option<storage_enums::MitCategory>,
pub billing_descriptor: Option<common_types::payments::BillingDescriptor>,
pub tokenization: Option<common_enums::Tokenization>,
pub partner_merchant_identifier_details:
Option<common_types::payments::PartnerMerchantIdentifierDetails>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression, PartialEq)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct PaymentLinkConfigRequestForPayments {
/// custom theme for the payment link
pub theme: Option<String>,
/// merchant display logo
pub logo: Option<String>,
/// Custom merchant name for payment link
pub seller_name: Option<String>,
/// Custom layout for sdk
pub sdk_layout: Option<String>,
/// Display only the sdk for payment link
pub display_sdk_only: Option<bool>,
/// Enable saved payment method option for payment link
pub enabled_saved_payment_method: Option<bool>,
/// Hide card nickname field option for payment link
pub hide_card_nickname_field: Option<bool>,
/// Show card form by default for payment link
pub show_card_form_by_default: Option<bool>,
/// Dynamic details related to merchant to be rendered in payment link
pub transaction_details: Option<Vec<PaymentLinkTransactionDetails>>,
/// Configurations for the background image for details section
pub background_image: Option<PaymentLinkBackgroundImageConfig>,
/// Custom layout for details section
pub details_layout: Option<common_enums::PaymentLinkDetailsLayout>,
/// Text for payment link's handle confirm button
pub payment_button_text: Option<String>,
/// Skip the status screen after payment completion
pub skip_status_screen: Option<bool>,
/// Text for customizing message for card terms
pub custom_message_for_card_terms: Option<String>,
/// Text for customizing message for different Payment Method Types
pub custom_message_for_payment_method_types:
Option<common_types::payments::PaymentMethodsConfig>,
/// Custom background colour for payment link's handle confirm button
pub payment_button_colour: Option<String>,
/// Custom text colour for payment link's handle confirm button
pub payment_button_text_colour: Option<String>,
/// Custom background colour for the payment link
pub background_colour: Option<String>,
/// SDK configuration rules
pub sdk_ui_rules:
Option<std::collections::HashMap<String, std::collections::HashMap<String, String>>>,
/// Payment link configuration rules
pub payment_link_ui_rules:
Option<std::collections::HashMap<String, std::collections::HashMap<String, String>>>,
/// Flag to enable the button only when the payment form is ready for submission
pub enable_button_only_on_form_ready: Option<bool>,
/// Optional header for the SDK's payment form
pub payment_form_header_text: Option<String>,
/// Label type in the SDK's payment form
pub payment_form_label_type: Option<common_enums::PaymentLinkSdkLabelType>,
/// Boolean for controlling whether or not to show the explicit consent for storing cards
pub show_card_terms: Option<common_enums::PaymentLinkShowSdkTerms>,
/// Boolean to control payment button text for setup mandate calls
pub is_setup_mandate_flow: Option<bool>,
/// Hex color for the CVC icon during error state
pub color_icon_card_cvc_error: Option<String>,
}
common_utils::impl_to_sql_from_sql_json!(PaymentLinkConfigRequestForPayments);
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)]
pub struct PaymentLinkTransactionDetails {
/// Key for the transaction details
pub key: String,
/// Value for the transaction details
pub value: String,
/// UI configuration for the transaction details
pub ui_configuration: Option<TransactionDetailsUiConfiguration>,
}
common_utils::impl_to_sql_from_sql_json!(PaymentLinkTransactionDetails);
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)]
pub struct TransactionDetailsUiConfiguration {
/// Position of the key-value pair in the UI
pub position: Option<i8>,
/// Whether the key should be bold
pub is_key_bold: Option<bool>,
/// Whether the value should be bold
pub is_value_bold: Option<bool>,
}
common_utils::impl_to_sql_from_sql_json!(TransactionDetailsUiConfiguration);
#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct TaxDetails {
/// This is the tax related information that is calculated irrespective of any payment method.
/// This is calculated when the order is created with shipping details
pub default: Option<DefaultTax>,
/// This is the tax related information that is calculated based on the payment method
/// This is calculated when calling the /calculate_tax API
pub payment_method_type: Option<PaymentMethodTypeTax>,
}
impl TaxDetails {
/// Get the tax amount
/// If default tax is present, return the default tax amount
/// If default tax is not present, return the tax amount based on the payment method if it matches the provided payment method type
pub fn get_tax_amount(&self, payment_method: Option<PaymentMethodType>) -> Option<MinorUnit> {
self.payment_method_type
.as_ref()
.zip(payment_method)
.filter(|(payment_method_type_tax, payment_method)| {
payment_method_type_tax.pmt == *payment_method
})
.map(|(payment_method_type_tax, _)| payment_method_type_tax.order_tax_amount)
.or_else(|| self.get_default_tax_amount())
}
/// Get the default tax amount
pub fn get_default_tax_amount(&self) -> Option<MinorUnit> {
self.default
.as_ref()
.map(|default_tax_details| default_tax_details.order_tax_amount)
}
}
common_utils::impl_to_sql_from_sql_json!(TaxDetails);
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PaymentMethodTypeTax {
pub order_tax_amount: MinorUnit,
pub pmt: PaymentMethodType,
}
#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct DefaultTax {
pub order_tax_amount: MinorUnit,
}
#[cfg(feature = "v2")]
#[derive(
Clone, Debug, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize,
)]
#[diesel(table_name = payment_intent)]
pub struct PaymentIntentNew {
pub merchant_id: common_utils::id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: MinorUnit,
pub currency: storage_enums::Currency,
pub amount_captured: Option<MinorUnit>,
pub customer_id: Option<common_utils::id_type::GlobalCustomerId>,
pub description: Option<common_utils::types::Description>,
pub return_url: Option<common_utils::types::Url>,
pub metadata: Option<pii::SecretSerdeValue>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>,
#[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)]
pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>,
pub allowed_payment_method_types: Option<pii::SecretSerdeValue>,
pub connector_metadata: Option<pii::SecretSerdeValue>,
pub feature_metadata: Option<FeatureMetadata>,
pub attempt_count: i16,
pub profile_id: common_utils::id_type::ProfileId,
pub payment_link_id: Option<String>,
pub updated_by: String,
pub surcharge_applicable: Option<bool>,
pub request_incremental_authorization: Option<RequestIncrementalAuthorization>,
pub authorization_count: Option<i32>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub session_expiry: PrimitiveDateTime,
pub request_external_three_ds_authentication: Option<bool>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
pub customer_details: Option<Encryption>,
pub shipping_cost: Option<MinorUnit>,
pub organization_id: common_utils::id_type::OrganizationId,
pub tax_details: Option<TaxDetails>,
pub skip_external_tax_calculation: Option<bool>,
pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>,
pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>,
pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>,
pub billing_address: Option<Encryption>,
pub shipping_address: Option<Encryption>,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub authentication_type: Option<common_enums::AuthenticationType>,
pub prerouting_algorithm: Option<serde_json::Value>,
pub surcharge_amount: Option<MinorUnit>,
pub tax_on_surcharge: Option<MinorUnit>,
pub frm_merchant_decision: Option<common_enums::MerchantDecision>,
pub statement_descriptor: Option<common_utils::types::StatementDescriptor>,
pub enable_payment_link: Option<bool>,
pub apply_mit_exemption: Option<bool>,
pub id: common_utils::id_type::GlobalPaymentId,
pub platform_merchant_id: Option<common_utils::id_type::MerchantId>,
pub force_3ds_challenge: Option<bool>,
pub force_3ds_challenge_trigger: Option<bool>,
pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,
pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub created_by: Option<String>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_payment_id_from_merchant: Option<bool>,
pub payment_channel: Option<common_enums::PaymentChannel>,
pub tax_status: Option<common_enums::TaxStatus>,
pub discount_amount: Option<MinorUnit>,
pub shipping_amount_tax: Option<MinorUnit>,
pub duty_amount: Option<MinorUnit>,
pub order_date: Option<PrimitiveDateTime>,
pub mit_category: Option<storage_enums::MitCategory>,
pub tokenization: Option<common_enums::Tokenization>,
pub active_attempts_group_id: Option<common_utils::id_type::GlobalAttemptGroupId>,
pub active_attempt_id_type: Option<common_enums::ActiveAttemptIDType>,
}
#[cfg(feature = "v1")]
#[derive(
Clone, Debug, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize,
)]
#[diesel(table_name = payment_intent)]
pub struct PaymentIntentNew {
pub payment_id: common_utils::id_type::PaymentId,
pub merchant_id: common_utils::id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub amount_captured: Option<MinorUnit>,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub description: Option<String>,
pub return_url: Option<String>,
pub metadata: Option<serde_json::Value>,
pub connector_id: Option<String>,
pub shipping_address_id: Option<String>,
pub billing_address_id: Option<String>,
pub statement_descriptor_name: Option<String>,
pub statement_descriptor_suffix: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub off_session: Option<bool>,
pub client_secret: Option<String>,
pub active_attempt_id: String,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub order_details: Option<Vec<pii::SecretSerdeValue>>,
pub allowed_payment_method_types: Option<serde_json::Value>,
pub connector_metadata: Option<serde_json::Value>,
pub feature_metadata: Option<serde_json::Value>,
pub attempt_count: i16,
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub merchant_decision: Option<String>,
pub payment_link_id: Option<String>,
pub payment_confirm_source: Option<storage_enums::PaymentSource>,
pub updated_by: String,
pub surcharge_applicable: Option<bool>,
pub request_incremental_authorization: Option<RequestIncrementalAuthorization>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub session_expiry: Option<PrimitiveDateTime>,
pub fingerprint_id: Option<String>,
pub request_external_three_ds_authentication: Option<bool>,
pub charges: Option<pii::SecretSerdeValue>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
pub customer_details: Option<Encryption>,
pub billing_details: Option<Encryption>,
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryption>,
pub is_payment_processor_token_flow: Option<bool>,
pub shipping_cost: Option<MinorUnit>,
pub organization_id: common_utils::id_type::OrganizationId,
pub tax_details: Option<TaxDetails>,
pub skip_external_tax_calculation: Option<bool>,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
pub platform_merchant_id: Option<common_utils::id_type::MerchantId>,
pub force_3ds_challenge: Option<bool>,
pub force_3ds_challenge_trigger: Option<bool>,
pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,
pub created_by: Option<String>,
pub is_iframe_redirection_enabled: Option<bool>,
pub extended_return_url: Option<String>,
pub is_payment_id_from_merchant: Option<bool>,
pub payment_channel: Option<common_enums::PaymentChannel>,
pub tax_status: Option<common_enums::TaxStatus>,
pub discount_amount: Option<MinorUnit>,
pub order_date: Option<PrimitiveDateTime>,
pub shipping_amount_tax: Option<MinorUnit>,
pub duty_amount: Option<MinorUnit>,
pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>,
pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>,
pub mit_category: Option<storage_enums::MitCategory>,
pub billing_descriptor: Option<common_types::payments::BillingDescriptor>,
pub tokenization: Option<common_enums::Tokenization>,
pub partner_merchant_identifier_details:
Option<common_types::payments::PartnerMerchantIdentifierDetails>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PaymentIntentUpdate {
/// Update the payment intent details on payment intent confirmation, before calling the connector
ConfirmIntent {
status: storage_enums::IntentStatus,
active_attempt_id: common_utils::id_type::GlobalAttemptId,
updated_by: String,
},
/// Update the payment intent details on payment intent confirmation, after calling the connector
ConfirmIntentPostUpdate {
status: storage_enums::IntentStatus,
amount_captured: Option<MinorUnit>,
updated_by: String,
},
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PaymentIntentUpdate {
ResponseUpdate {
status: storage_enums::IntentStatus,
amount_captured: Option<MinorUnit>,
fingerprint_id: Option<String>,
updated_by: String,
incremental_authorization_allowed: Option<bool>,
feature_metadata: Option<masking::Secret<serde_json::Value>>,
},
MetadataUpdate {
metadata: serde_json::Value,
updated_by: String,
},
Update(Box<PaymentIntentUpdateFields>),
PaymentCreateUpdate {
return_url: Option<String>,
status: Option<storage_enums::IntentStatus>,
customer_id: Option<common_utils::id_type::CustomerId>,
shipping_address_id: Option<String>,
billing_address_id: Option<String>,
customer_details: Option<Encryption>,
updated_by: String,
},
MerchantStatusUpdate {
status: storage_enums::IntentStatus,
shipping_address_id: Option<String>,
billing_address_id: Option<String>,
updated_by: String,
},
PGStatusUpdate {
status: storage_enums::IntentStatus,
updated_by: String,
incremental_authorization_allowed: Option<bool>,
feature_metadata: Option<masking::Secret<serde_json::Value>>,
},
PaymentAttemptAndAttemptCountUpdate {
active_attempt_id: String,
attempt_count: i16,
updated_by: String,
},
StatusAndAttemptUpdate {
status: storage_enums::IntentStatus,
active_attempt_id: String,
attempt_count: i16,
updated_by: String,
},
ApproveUpdate {
status: storage_enums::IntentStatus,
merchant_decision: Option<String>,
updated_by: String,
},
RejectUpdate {
status: storage_enums::IntentStatus,
merchant_decision: Option<String>,
updated_by: String,
},
SurchargeApplicableUpdate {
surcharge_applicable: Option<bool>,
updated_by: String,
},
IncrementalAuthorizationAmountUpdate {
amount: MinorUnit,
},
AuthorizationCountUpdate {
authorization_count: i32,
},
CompleteAuthorizeUpdate {
shipping_address_id: Option<String>,
},
ManualUpdate {
status: Option<storage_enums::IntentStatus>,
updated_by: String,
},
SessionResponseUpdate {
tax_details: TaxDetails,
shipping_address_id: Option<String>,
updated_by: String,
shipping_details: Option<Encryption>,
},
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentIntentUpdateFields {
pub amount: MinorUnit,
pub currency: storage_enums::Currency,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub status: storage_enums::IntentStatus,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub shipping_address: Option<Encryption>,
pub billing_address: Option<Encryption>,
pub return_url: Option<String>,
pub description: Option<String>,
pub statement_descriptor: Option<String>,
pub order_details: Option<Vec<pii::SecretSerdeValue>>,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_confirm_source: Option<storage_enums::PaymentSource>,
pub updated_by: String,
pub session_expiry: Option<PrimitiveDateTime>,
pub request_external_three_ds_authentication: Option<bool>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
pub customer_details: Option<Encryption>,
pub merchant_order_reference_id: Option<String>,
pub is_payment_processor_token_flow: Option<bool>,
pub force_3ds_challenge: Option<bool>,
pub is_iframe_redirection_enabled: Option<bool>,
pub payment_channel: Option<Option<common_enums::PaymentChannel>>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentIntentUpdateFields {
pub amount: MinorUnit,
pub currency: storage_enums::Currency,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub status: storage_enums::IntentStatus,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub shipping_address_id: Option<String>,
pub billing_address_id: Option<String>,
pub return_url: Option<String>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub description: Option<String>,
pub statement_descriptor_name: Option<String>,
pub statement_descriptor_suffix: Option<String>,
pub order_details: Option<Vec<pii::SecretSerdeValue>>,
pub metadata: Option<serde_json::Value>,
pub payment_confirm_source: Option<storage_enums::PaymentSource>,
pub updated_by: String,
pub session_expiry: Option<PrimitiveDateTime>,
pub fingerprint_id: Option<String>,
pub request_external_three_ds_authentication: Option<bool>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
pub customer_details: Option<Encryption>,
pub billing_details: Option<Encryption>,
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryption>,
pub is_payment_processor_token_flow: Option<bool>,
pub tax_details: Option<TaxDetails>,
pub force_3ds_challenge: Option<bool>,
pub is_iframe_redirection_enabled: Option<bool>,
pub payment_channel: Option<common_enums::PaymentChannel>,
pub feature_metadata: Option<masking::Secret<serde_json::Value>>,
pub tax_status: Option<common_enums::TaxStatus>,
pub discount_amount: Option<MinorUnit>,
pub order_date: Option<PrimitiveDateTime>,
pub shipping_amount_tax: Option<MinorUnit>,
pub duty_amount: Option<MinorUnit>,
pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>,
pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>,
}
// TODO: uncomment fields as necessary
#[cfg(feature = "v2")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = payment_intent)]
pub struct PaymentIntentUpdateInternal {
pub status: Option<storage_enums::IntentStatus>,
pub prerouting_algorithm: Option<serde_json::Value>,
pub amount_captured: Option<MinorUnit>,
pub modified_at: PrimitiveDateTime,
pub active_attempt_id: Option<Option<common_utils::id_type::GlobalAttemptId>>,
pub active_attempts_group_id: Option<common_utils::id_type::GlobalAttemptGroupId>,
pub active_attempt_id_type: Option<common_enums::ActiveAttemptIDType>,
pub amount: Option<MinorUnit>,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/cards_info.rs | crates/diesel_models/src/cards_info.rs | use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;
use crate::{enums as storage_enums, schema::cards_info};
#[derive(
Clone,
Debug,
Queryable,
Identifiable,
Selectable,
serde::Deserialize,
serde::Serialize,
Insertable,
)]
#[diesel(table_name = cards_info, primary_key(card_iin), check_for_backend(diesel::pg::Pg))]
pub struct CardInfo {
pub card_iin: String,
pub card_issuer: Option<String>,
pub card_network: Option<storage_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_subtype: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code_id: Option<String>,
pub bank_code: Option<String>,
pub country_code: Option<String>,
pub date_created: PrimitiveDateTime,
pub last_updated: Option<PrimitiveDateTime>,
pub last_updated_provider: Option<String>,
}
#[derive(
Clone, Debug, PartialEq, Eq, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize,
)]
#[diesel(table_name = cards_info)]
pub struct UpdateCardInfo {
pub card_issuer: Option<String>,
pub card_network: Option<storage_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_subtype: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code_id: Option<String>,
pub bank_code: Option<String>,
pub country_code: Option<String>,
pub last_updated: Option<PrimitiveDateTime>,
pub last_updated_provider: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/merchant_account.rs | crates/diesel_models/src/merchant_account.rs | use common_utils::{encryption::Encryption, pii};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use crate::enums as storage_enums;
#[cfg(feature = "v1")]
use crate::schema::merchant_account;
#[cfg(feature = "v2")]
use crate::schema_v2::merchant_account;
/// Note: The order of fields in the struct is important.
/// This should be in the same order as the fields in the schema.rs file, otherwise the code will not compile
/// If two adjacent columns have the same type, then the compiler will not throw any error, but the fields read / written will be interchanged
#[cfg(feature = "v1")]
#[derive(
Clone,
Debug,
serde::Deserialize,
Identifiable,
serde::Serialize,
Queryable,
Selectable,
router_derive::DebugAsDisplay,
)]
#[diesel(table_name = merchant_account, primary_key(merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct MerchantAccount {
merchant_id: common_utils::id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub merchant_name: Option<Encryption>,
pub merchant_details: Option<Encryption>,
pub webhook_details: Option<crate::business_profile::WebhookDetails>,
pub sub_merchants_enabled: Option<bool>,
pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub publishable_key: Option<String>,
pub storage_scheme: storage_enums::MerchantStorageScheme,
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub primary_business_details: serde_json::Value,
pub intent_fulfillment_time: Option<i64>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub is_recon_enabled: bool,
pub default_profile: Option<common_utils::id_type::ProfileId>,
pub recon_status: storage_enums::ReconStatus,
pub payment_link_config: Option<serde_json::Value>,
pub pm_collect_link_config: Option<serde_json::Value>,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub id: Option<common_utils::id_type::MerchantId>,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: Option<common_enums::MerchantAccountType>,
}
#[cfg(feature = "v1")]
pub struct MerchantAccountSetter {
pub merchant_id: common_utils::id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub merchant_name: Option<Encryption>,
pub merchant_details: Option<Encryption>,
pub webhook_details: Option<crate::business_profile::WebhookDetails>,
pub sub_merchants_enabled: Option<bool>,
pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub publishable_key: Option<String>,
pub storage_scheme: storage_enums::MerchantStorageScheme,
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub primary_business_details: serde_json::Value,
pub intent_fulfillment_time: Option<i64>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub is_recon_enabled: bool,
pub default_profile: Option<common_utils::id_type::ProfileId>,
pub recon_status: storage_enums::ReconStatus,
pub payment_link_config: Option<serde_json::Value>,
pub pm_collect_link_config: Option<serde_json::Value>,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
#[cfg(feature = "v1")]
impl From<MerchantAccountSetter> for MerchantAccount {
fn from(item: MerchantAccountSetter) -> Self {
Self {
id: Some(item.merchant_id.clone()),
merchant_id: item.merchant_id,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
payment_response_hash_key: item.payment_response_hash_key,
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
merchant_name: item.merchant_name,
merchant_details: item.merchant_details,
webhook_details: item.webhook_details,
sub_merchants_enabled: item.sub_merchants_enabled,
parent_merchant_id: item.parent_merchant_id,
publishable_key: item.publishable_key,
storage_scheme: item.storage_scheme,
locker_id: item.locker_id,
metadata: item.metadata,
routing_algorithm: item.routing_algorithm,
primary_business_details: item.primary_business_details,
intent_fulfillment_time: item.intent_fulfillment_time,
created_at: item.created_at,
modified_at: item.modified_at,
frm_routing_algorithm: item.frm_routing_algorithm,
payout_routing_algorithm: item.payout_routing_algorithm,
organization_id: item.organization_id,
is_recon_enabled: item.is_recon_enabled,
default_profile: item.default_profile,
recon_status: item.recon_status,
payment_link_config: item.payment_link_config,
pm_collect_link_config: item.pm_collect_link_config,
version: item.version,
is_platform_account: item.is_platform_account,
product_type: item.product_type,
merchant_account_type: Some(item.merchant_account_type),
}
}
}
/// Note: The order of fields in the struct is important.
/// This should be in the same order as the fields in the schema.rs file, otherwise the code will not compile
/// If two adjacent columns have the same type, then the compiler will not throw any error, but the fields read / written will be interchanged
#[cfg(feature = "v2")]
#[derive(
Clone,
Debug,
serde::Deserialize,
Identifiable,
serde::Serialize,
Queryable,
router_derive::DebugAsDisplay,
Selectable,
)]
#[diesel(table_name = merchant_account, primary_key(id), check_for_backend(diesel::pg::Pg))]
pub struct MerchantAccount {
pub merchant_name: Option<Encryption>,
pub merchant_details: Option<Encryption>,
pub publishable_key: Option<String>,
pub storage_scheme: storage_enums::MerchantStorageScheme,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub organization_id: common_utils::id_type::OrganizationId,
pub recon_status: storage_enums::ReconStatus,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub id: common_utils::id_type::MerchantId,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: Option<common_enums::MerchantAccountType>,
}
#[cfg(feature = "v2")]
impl From<MerchantAccountSetter> for MerchantAccount {
fn from(item: MerchantAccountSetter) -> Self {
Self {
id: item.id,
merchant_name: item.merchant_name,
merchant_details: item.merchant_details,
publishable_key: item.publishable_key,
storage_scheme: item.storage_scheme,
metadata: item.metadata,
created_at: item.created_at,
modified_at: item.modified_at,
organization_id: item.organization_id,
recon_status: item.recon_status,
version: item.version,
is_platform_account: item.is_platform_account,
product_type: item.product_type,
merchant_account_type: Some(item.merchant_account_type),
}
}
}
#[cfg(feature = "v2")]
pub struct MerchantAccountSetter {
pub id: common_utils::id_type::MerchantId,
pub merchant_name: Option<Encryption>,
pub merchant_details: Option<Encryption>,
pub publishable_key: Option<String>,
pub storage_scheme: storage_enums::MerchantStorageScheme,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub organization_id: common_utils::id_type::OrganizationId,
pub recon_status: storage_enums::ReconStatus,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
impl MerchantAccount {
#[cfg(feature = "v1")]
/// Get the unique identifier of MerchantAccount
pub fn get_id(&self) -> &common_utils::id_type::MerchantId {
&self.merchant_id
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &common_utils::id_type::MerchantId {
&self.id
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_account)]
pub struct MerchantAccountNew {
pub merchant_id: common_utils::id_type::MerchantId,
pub merchant_name: Option<Encryption>,
pub merchant_details: Option<Encryption>,
pub return_url: Option<String>,
pub webhook_details: Option<crate::business_profile::WebhookDetails>,
pub sub_merchants_enabled: Option<bool>,
pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub enable_payment_response_hash: Option<bool>,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: Option<bool>,
pub publishable_key: Option<String>,
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub primary_business_details: serde_json::Value,
pub intent_fulfillment_time: Option<i64>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub is_recon_enabled: bool,
pub default_profile: Option<common_utils::id_type::ProfileId>,
pub recon_status: storage_enums::ReconStatus,
pub payment_link_config: Option<serde_json::Value>,
pub pm_collect_link_config: Option<serde_json::Value>,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub id: Option<common_utils::id_type::MerchantId>,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_account)]
pub struct MerchantAccountNew {
pub merchant_name: Option<Encryption>,
pub merchant_details: Option<Encryption>,
pub publishable_key: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub organization_id: common_utils::id_type::OrganizationId,
pub recon_status: storage_enums::ReconStatus,
pub id: common_utils::id_type::MerchantId,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_account)]
pub struct MerchantAccountUpdateInternal {
pub merchant_name: Option<Encryption>,
pub merchant_details: Option<Encryption>,
pub publishable_key: Option<String>,
pub storage_scheme: Option<storage_enums::MerchantStorageScheme>,
pub metadata: Option<pii::SecretSerdeValue>,
pub modified_at: time::PrimitiveDateTime,
pub organization_id: Option<common_utils::id_type::OrganizationId>,
pub recon_status: Option<storage_enums::ReconStatus>,
pub is_platform_account: Option<bool>,
pub product_type: Option<common_enums::MerchantProductType>,
}
#[cfg(feature = "v2")]
impl MerchantAccountUpdateInternal {
pub fn apply_changeset(self, source: MerchantAccount) -> MerchantAccount {
let Self {
merchant_name,
merchant_details,
publishable_key,
storage_scheme,
metadata,
modified_at,
organization_id,
recon_status,
is_platform_account,
product_type,
} = self;
MerchantAccount {
merchant_name: merchant_name.or(source.merchant_name),
merchant_details: merchant_details.or(source.merchant_details),
publishable_key: publishable_key.or(source.publishable_key),
storage_scheme: storage_scheme.unwrap_or(source.storage_scheme),
metadata: metadata.or(source.metadata),
created_at: source.created_at,
modified_at,
organization_id: organization_id.unwrap_or(source.organization_id),
recon_status: recon_status.unwrap_or(source.recon_status),
version: source.version,
id: source.id,
is_platform_account: is_platform_account.unwrap_or(source.is_platform_account),
product_type: product_type.or(source.product_type),
merchant_account_type: source.merchant_account_type,
}
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_account)]
pub struct MerchantAccountUpdateInternal {
pub merchant_name: Option<Encryption>,
pub merchant_details: Option<Encryption>,
pub return_url: Option<String>,
pub webhook_details: Option<crate::business_profile::WebhookDetails>,
pub sub_merchants_enabled: Option<bool>,
pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub enable_payment_response_hash: Option<bool>,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: Option<bool>,
pub publishable_key: Option<String>,
pub storage_scheme: Option<storage_enums::MerchantStorageScheme>,
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub primary_business_details: Option<serde_json::Value>,
pub modified_at: time::PrimitiveDateTime,
pub intent_fulfillment_time: Option<i64>,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub organization_id: Option<common_utils::id_type::OrganizationId>,
pub is_recon_enabled: Option<bool>,
pub default_profile: Option<Option<common_utils::id_type::ProfileId>>,
pub recon_status: Option<storage_enums::ReconStatus>,
pub payment_link_config: Option<serde_json::Value>,
pub pm_collect_link_config: Option<serde_json::Value>,
pub is_platform_account: Option<bool>,
pub product_type: Option<common_enums::MerchantProductType>,
}
#[cfg(feature = "v1")]
impl MerchantAccountUpdateInternal {
pub fn apply_changeset(self, source: MerchantAccount) -> MerchantAccount {
let Self {
merchant_name,
merchant_details,
return_url,
webhook_details,
sub_merchants_enabled,
parent_merchant_id,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
publishable_key,
storage_scheme,
locker_id,
metadata,
routing_algorithm,
primary_business_details,
modified_at,
intent_fulfillment_time,
frm_routing_algorithm,
payout_routing_algorithm,
organization_id,
is_recon_enabled,
default_profile,
recon_status,
payment_link_config,
pm_collect_link_config,
is_platform_account,
product_type,
} = self;
MerchantAccount {
merchant_id: source.merchant_id,
return_url: return_url.or(source.return_url),
enable_payment_response_hash: enable_payment_response_hash
.unwrap_or(source.enable_payment_response_hash),
payment_response_hash_key: payment_response_hash_key
.or(source.payment_response_hash_key),
redirect_to_merchant_with_http_post: redirect_to_merchant_with_http_post
.unwrap_or(source.redirect_to_merchant_with_http_post),
merchant_name: merchant_name.or(source.merchant_name),
merchant_details: merchant_details.or(source.merchant_details),
webhook_details: webhook_details.or(source.webhook_details),
sub_merchants_enabled: sub_merchants_enabled.or(source.sub_merchants_enabled),
parent_merchant_id: parent_merchant_id.or(source.parent_merchant_id),
publishable_key: publishable_key.or(source.publishable_key),
storage_scheme: storage_scheme.unwrap_or(source.storage_scheme),
locker_id: locker_id.or(source.locker_id),
metadata: metadata.or(source.metadata),
routing_algorithm: routing_algorithm.or(source.routing_algorithm),
primary_business_details: primary_business_details
.unwrap_or(source.primary_business_details),
intent_fulfillment_time: intent_fulfillment_time.or(source.intent_fulfillment_time),
created_at: source.created_at,
modified_at,
frm_routing_algorithm: frm_routing_algorithm.or(source.frm_routing_algorithm),
payout_routing_algorithm: payout_routing_algorithm.or(source.payout_routing_algorithm),
organization_id: organization_id.unwrap_or(source.organization_id),
is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled),
default_profile: default_profile.unwrap_or(source.default_profile),
recon_status: recon_status.unwrap_or(source.recon_status),
payment_link_config: payment_link_config.or(source.payment_link_config),
pm_collect_link_config: pm_collect_link_config.or(source.pm_collect_link_config),
version: source.version,
is_platform_account: is_platform_account.unwrap_or(source.is_platform_account),
id: source.id,
product_type: product_type.or(source.product_type),
merchant_account_type: source.merchant_account_type,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/enums.rs | crates/diesel_models/src/enums.rs | #[doc(hidden)]
pub mod diesel_exports {
pub use super::{
DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus,
DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind,
DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus,
DbCardDiscovery as CardDiscovery, DbConnectorStatus as ConnectorStatus,
DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency,
DbDashboardMetadata as DashboardMetadata, DbDeleteStatus as DeleteStatus,
DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus,
DbEventClass as EventClass, DbEventObjectType as EventObjectType, DbEventType as EventType,
DbFraudCheckStatus as FraudCheckStatus, DbFraudCheckType as FraudCheckType,
DbFutureUsage as FutureUsage, DbGenericLinkType as GenericLinkType,
DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus,
DbMandateType as MandateType, DbMerchantStorageScheme as MerchantStorageScheme,
DbOrderFulfillmentTimeOrigin as OrderFulfillmentTimeOrigin,
DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentSource as PaymentSource,
DbPaymentType as PaymentType, DbPayoutStatus as PayoutStatus, DbPayoutType as PayoutType,
DbProcessTrackerStatus as ProcessTrackerStatus, DbReconStatus as ReconStatus,
DbRefundStatus as RefundStatus, DbRefundType as RefundType, DbRelayStatus as RelayStatus,
DbRelayType as RelayType,
DbRequestIncrementalAuthorization as RequestIncrementalAuthorization,
DbRevenueRecoveryAlgorithmType as RevenueRecoveryAlgorithmType, DbRoleScope as RoleScope,
DbRoutingAlgorithmKind as RoutingAlgorithmKind, DbRoutingApproach as RoutingApproach,
DbScaExemptionType as ScaExemptionType,
DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState,
DbTokenizationFlag as TokenizationFlag, DbTotpStatus as TotpStatus,
DbTransactionType as TransactionType, DbUserRoleVersion as UserRoleVersion,
DbUserStatus as UserStatus, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt,
};
}
pub use common_enums::*;
use common_utils::pii;
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
pub use common_utils::tokenization;
use diesel::{deserialize::FromSqlRow, expression::AsExpression, sql_types::Jsonb};
use router_derive::diesel_enum;
use time::PrimitiveDateTime;
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
)]
#[diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RoutingAlgorithmKind {
Single,
Priority,
VolumeSplit,
Advanced,
Dynamic,
ThreeDsDecisionRule,
}
// Refund
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[diesel_enum(storage_type = "db_enum")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum RefundType {
InstantRefund,
RegularRefund,
RetryRefund,
}
// Mandate
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
Default,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
)]
#[diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum MandateType {
SingleUse,
#[default]
MultiUse,
}
#[derive(
serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
pub struct MandateDetails {
pub update_mandate_id: Option<String>,
}
common_utils::impl_to_sql_from_sql_json!(MandateDetails);
#[derive(
serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
pub enum MandateDataType {
SingleUse(MandateAmountData),
MultiUse(Option<MandateAmountData>),
}
common_utils::impl_to_sql_from_sql_json!(MandateDataType);
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct MandateAmountData {
pub amount: common_utils::types::MinorUnit,
pub currency: Currency,
pub start_date: Option<PrimitiveDateTime>,
pub end_date: Option<PrimitiveDateTime>,
pub metadata: Option<pii::SecretSerdeValue>,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum FraudCheckType {
PreFrm,
PostFrm,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[diesel_enum(storage_type = "text")]
#[strum(serialize_all = "snake_case")]
pub enum FraudCheckLastStep {
#[default]
Processing,
CheckoutOrSale,
TransactionOrRecordRefund,
Fulfillment,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum UserStatus {
Active,
#[default]
InvitationSent,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum DashboardMetadata {
ProductionAgreement,
SetupProcessor,
ConfigureEndpoint,
SetupComplete,
FirstProcessorConnected,
SecondProcessorConnected,
ConfiguredRouting,
TestPayment,
IntegrationMethod,
ConfigurationType,
IntegrationCompleted,
StripeConnected,
PaypalConnected,
SpRoutingConfigured,
Feedback,
ProdIntent,
SpTestPayment,
DownloadWoocom,
ConfigureWoocom,
SetupWoocomWebhook,
IsMultipleConfiguration,
IsChangePasswordRequired,
OnboardingSurvey,
ReconStatus,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum TotpStatus {
Set,
InProgress,
#[default]
NotSet,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::EnumString,
strum::Display,
)]
#[diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum UserRoleVersion {
#[default]
V1,
V2,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/user_key_store.rs | crates/diesel_models/src/user_key_store.rs | use common_utils::encryption::Encryption;
use diesel::{Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;
use crate::schema::user_key_store;
#[derive(
Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Selectable,
)]
#[diesel(table_name = user_key_store, primary_key(user_id), check_for_backend(diesel::pg::Pg))]
pub struct UserKeyStore {
pub user_id: String,
pub key: Encryption,
pub created_at: PrimitiveDateTime,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Insertable)]
#[diesel(table_name = user_key_store)]
pub struct UserKeyStoreNew {
pub user_id: String,
pub key: Encryption,
pub created_at: PrimitiveDateTime,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/generic_link.rs | crates/diesel_models/src/generic_link.rs | use common_utils::{
consts,
link_utils::{
EnabledPaymentMethod, GenericLinkStatus, GenericLinkUiConfig, PaymentMethodCollectStatus,
PayoutLinkData, PayoutLinkStatus,
},
};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::{Duration, PrimitiveDateTime};
use crate::{enums as storage_enums, schema::generic_link};
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize,
)]
#[diesel(table_name = generic_link, primary_key(link_id), check_for_backend(diesel::pg::Pg))]
pub struct GenericLink {
pub link_id: String,
pub primary_reference: String,
pub merchant_id: common_utils::id_type::MerchantId,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub last_modified_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub expiry: PrimitiveDateTime,
pub link_data: serde_json::Value,
pub link_status: GenericLinkStatus,
pub link_type: storage_enums::GenericLinkType,
pub url: Secret<String>,
pub return_url: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GenericLinkState {
pub link_id: String,
pub primary_reference: String,
pub merchant_id: common_utils::id_type::MerchantId,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub last_modified_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub expiry: PrimitiveDateTime,
pub link_data: GenericLinkData,
pub link_status: GenericLinkStatus,
pub link_type: storage_enums::GenericLinkType,
pub url: Secret<String>,
pub return_url: Option<String>,
}
#[derive(
Clone,
Debug,
Eq,
PartialEq,
Insertable,
serde::Serialize,
serde::Deserialize,
router_derive::DebugAsDisplay,
)]
#[diesel(table_name = generic_link)]
pub struct GenericLinkNew {
pub link_id: String,
pub primary_reference: String,
pub merchant_id: common_utils::id_type::MerchantId,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub created_at: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_modified_at: Option<PrimitiveDateTime>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub expiry: PrimitiveDateTime,
pub link_data: serde_json::Value,
pub link_status: GenericLinkStatus,
pub link_type: storage_enums::GenericLinkType,
pub url: Secret<String>,
pub return_url: Option<String>,
}
impl Default for GenericLinkNew {
fn default() -> Self {
let now = common_utils::date_time::now();
Self {
link_id: String::default(),
primary_reference: String::default(),
merchant_id: common_utils::id_type::MerchantId::default(),
created_at: Some(now),
last_modified_at: Some(now),
expiry: now + Duration::seconds(consts::DEFAULT_SESSION_EXPIRY),
link_data: serde_json::Value::default(),
link_status: GenericLinkStatus::default(),
link_type: common_enums::GenericLinkType::default(),
url: Secret::default(),
return_url: Option::default(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GenericLinkData {
PaymentMethodCollect(PaymentMethodCollectLinkData),
PayoutLink(PayoutLinkData),
}
impl GenericLinkData {
pub fn get_payment_method_collect_data(&self) -> Result<&PaymentMethodCollectLinkData, String> {
match self {
Self::PaymentMethodCollect(pm) => Ok(pm),
_ => Err("Invalid link type for fetching payment method collect data".to_string()),
}
}
pub fn get_payout_link_data(&self) -> Result<&PayoutLinkData, String> {
match self {
Self::PayoutLink(pl) => Ok(pl),
_ => Err("Invalid link type for fetching payout link data".to_string()),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PaymentMethodCollectLink {
pub link_id: String,
pub primary_reference: String,
pub merchant_id: common_utils::id_type::MerchantId,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub last_modified_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub expiry: PrimitiveDateTime,
pub link_data: PaymentMethodCollectLinkData,
pub link_status: PaymentMethodCollectStatus,
pub link_type: storage_enums::GenericLinkType,
pub url: Secret<String>,
pub return_url: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentMethodCollectLinkData {
pub pm_collect_link_id: String,
pub customer_id: common_utils::id_type::CustomerId,
pub link: Secret<String>,
pub client_secret: Secret<String>,
pub session_expiry: u32,
#[serde(flatten)]
pub ui_config: GenericLinkUiConfig,
pub enabled_payment_methods: Option<Vec<EnabledPaymentMethod>>,
}
#[derive(Clone, Debug, Identifiable, Queryable, Serialize, Deserialize)]
#[diesel(table_name = generic_link)]
#[diesel(primary_key(link_id))]
pub struct PayoutLink {
pub link_id: String,
pub primary_reference: common_utils::id_type::PayoutId,
pub merchant_id: common_utils::id_type::MerchantId,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub last_modified_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub expiry: PrimitiveDateTime,
pub link_data: PayoutLinkData,
pub link_status: PayoutLinkStatus,
pub link_type: storage_enums::GenericLinkType,
pub url: Secret<String>,
pub return_url: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PayoutLinkUpdate {
StatusUpdate { link_status: PayoutLinkStatus },
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = generic_link)]
pub struct GenericLinkUpdateInternal {
pub link_status: Option<GenericLinkStatus>,
}
impl From<PayoutLinkUpdate> for GenericLinkUpdateInternal {
fn from(generic_link_update: PayoutLinkUpdate) -> Self {
match generic_link_update {
PayoutLinkUpdate::StatusUpdate { link_status } => Self {
link_status: Some(GenericLinkStatus::PayoutLink(link_status)),
},
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/subscription.rs | crates/diesel_models/src/subscription.rs | use common_utils::{generate_id_with_default_len, pii::SecretSerdeValue};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::schema::subscription;
#[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)]
#[diesel(table_name = subscription)]
pub struct SubscriptionNew {
id: common_utils::id_type::SubscriptionId,
status: String,
billing_processor: Option<String>,
payment_method_id: Option<String>,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
client_secret: Option<String>,
connector_subscription_id: Option<String>,
merchant_id: common_utils::id_type::MerchantId,
customer_id: common_utils::id_type::CustomerId,
metadata: Option<SecretSerdeValue>,
created_at: time::PrimitiveDateTime,
modified_at: time::PrimitiveDateTime,
profile_id: common_utils::id_type::ProfileId,
merchant_reference_id: Option<String>,
plan_id: Option<String>,
item_price_id: Option<String>,
}
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Deserialize, Serialize,
)]
#[diesel(table_name = subscription, primary_key(id), check_for_backend(diesel::pg::Pg))]
pub struct Subscription {
pub id: common_utils::id_type::SubscriptionId,
pub status: String,
pub billing_processor: Option<String>,
pub payment_method_id: Option<String>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub client_secret: Option<String>,
pub connector_subscription_id: Option<String>,
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: common_utils::id_type::CustomerId,
pub metadata: Option<serde_json::Value>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_reference_id: Option<String>,
pub plan_id: Option<String>,
pub item_price_id: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, AsChangeset, router_derive::DebugAsDisplay, Deserialize)]
#[diesel(table_name = subscription)]
pub struct SubscriptionUpdate {
pub connector_subscription_id: Option<String>,
pub payment_method_id: Option<String>,
pub status: Option<String>,
pub modified_at: time::PrimitiveDateTime,
pub plan_id: Option<String>,
pub item_price_id: Option<String>,
}
impl SubscriptionNew {
#[allow(clippy::too_many_arguments)]
pub fn new(
id: common_utils::id_type::SubscriptionId,
status: String,
billing_processor: Option<String>,
payment_method_id: Option<String>,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
client_secret: Option<String>,
connector_subscription_id: Option<String>,
merchant_id: common_utils::id_type::MerchantId,
customer_id: common_utils::id_type::CustomerId,
metadata: Option<SecretSerdeValue>,
profile_id: common_utils::id_type::ProfileId,
merchant_reference_id: Option<String>,
plan_id: Option<String>,
item_price_id: Option<String>,
) -> Self {
let now = common_utils::date_time::now();
Self {
id,
status,
billing_processor,
payment_method_id,
merchant_connector_id,
client_secret,
connector_subscription_id,
merchant_id,
customer_id,
metadata,
created_at: now,
modified_at: now,
profile_id,
merchant_reference_id,
plan_id,
item_price_id,
}
}
pub fn generate_and_set_client_secret(&mut self) -> Secret<String> {
let client_secret =
generate_id_with_default_len(&format!("{}_secret", self.id.get_string_repr()));
self.client_secret = Some(client_secret.clone());
Secret::new(client_secret)
}
}
impl SubscriptionUpdate {
pub fn new(
connector_subscription_id: Option<String>,
payment_method_id: Option<Secret<String>>,
status: Option<String>,
plan_id: Option<String>,
item_price_id: Option<String>,
) -> Self {
Self {
connector_subscription_id,
payment_method_id: payment_method_id.map(|pmid| pmid.peek().clone()),
status,
modified_at: common_utils::date_time::now(),
plan_id,
item_price_id,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/user_role.rs | crates/diesel_models/src/user_role.rs | use std::hash::Hash;
use common_enums::EntityType;
use common_utils::{consts, id_type};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;
use crate::{enums, schema::user_roles};
#[derive(Clone, Debug, Identifiable, Queryable, Selectable, Eq)]
#[diesel(table_name = user_roles, check_for_backend(diesel::pg::Pg))]
pub struct UserRole {
pub id: i32,
pub user_id: String,
pub merchant_id: Option<id_type::MerchantId>,
pub role_id: String,
pub org_id: Option<id_type::OrganizationId>,
pub status: enums::UserStatus,
pub created_by: String,
pub last_modified_by: String,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub profile_id: Option<id_type::ProfileId>,
pub entity_id: Option<String>,
pub entity_type: Option<EntityType>,
pub version: enums::UserRoleVersion,
pub tenant_id: id_type::TenantId,
}
impl UserRole {
pub fn get_entity_id_and_type(&self) -> Option<(String, EntityType)> {
match (self.version, self.entity_type, self.role_id.as_str()) {
(enums::UserRoleVersion::V1, None, consts::ROLE_ID_ORGANIZATION_ADMIN) => {
let org_id = self.org_id.clone()?.get_string_repr().to_string();
Some((org_id, EntityType::Organization))
}
(enums::UserRoleVersion::V1, None, _) => {
let merchant_id = self.merchant_id.clone()?.get_string_repr().to_string();
Some((merchant_id, EntityType::Merchant))
}
(enums::UserRoleVersion::V1, Some(_), _) => {
self.entity_id.clone().zip(self.entity_type)
}
(enums::UserRoleVersion::V2, _, _) => self.entity_id.clone().zip(self.entity_type),
}
}
}
impl Hash for UserRole {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.user_id.hash(state);
if let Some((entity_id, entity_type)) = self.get_entity_id_and_type() {
entity_id.hash(state);
entity_type.hash(state);
}
}
}
impl PartialEq for UserRole {
fn eq(&self, other: &Self) -> bool {
match (
self.get_entity_id_and_type(),
other.get_entity_id_and_type(),
) {
(
Some((self_entity_id, self_entity_type)),
Some((other_entity_id, other_entity_type)),
) => {
self.user_id == other.user_id
&& self_entity_id == other_entity_id
&& self_entity_type == other_entity_type
}
_ => self.user_id == other.user_id,
}
}
}
#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = user_roles)]
pub struct UserRoleNew {
pub user_id: String,
pub merchant_id: Option<id_type::MerchantId>,
pub role_id: String,
pub org_id: Option<id_type::OrganizationId>,
pub status: enums::UserStatus,
pub created_by: String,
pub last_modified_by: String,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub profile_id: Option<id_type::ProfileId>,
pub entity_id: Option<String>,
pub entity_type: Option<EntityType>,
pub version: enums::UserRoleVersion,
pub tenant_id: id_type::TenantId,
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = user_roles)]
pub struct UserRoleUpdateInternal {
role_id: Option<String>,
status: Option<enums::UserStatus>,
last_modified_by: Option<String>,
last_modified: PrimitiveDateTime,
}
#[derive(Clone)]
pub enum UserRoleUpdate {
UpdateStatus {
status: enums::UserStatus,
modified_by: String,
},
UpdateRole {
role_id: String,
modified_by: String,
},
}
impl From<UserRoleUpdate> for UserRoleUpdateInternal {
fn from(value: UserRoleUpdate) -> Self {
let last_modified = common_utils::date_time::now();
match value {
UserRoleUpdate::UpdateRole {
role_id,
modified_by,
} => Self {
role_id: Some(role_id),
last_modified_by: Some(modified_by),
status: None,
last_modified,
},
UserRoleUpdate::UpdateStatus {
status,
modified_by,
} => Self {
status: Some(status),
last_modified,
last_modified_by: Some(modified_by),
role_id: None,
},
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/invoice.rs | crates/diesel_models/src/invoice.rs | use common_enums::{connector_enums::Connector, InvoiceStatus};
use common_utils::{id_type::GenerateId, pii::SecretSerdeValue, types::MinorUnit};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use crate::schema::invoice;
#[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)]
#[diesel(table_name = invoice, check_for_backend(diesel::pg::Pg))]
pub struct InvoiceNew {
pub id: common_utils::id_type::InvoiceId,
pub subscription_id: common_utils::id_type::SubscriptionId,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
pub payment_intent_id: Option<common_utils::id_type::PaymentId>,
pub payment_method_id: Option<String>,
pub customer_id: common_utils::id_type::CustomerId,
pub amount: MinorUnit,
pub currency: String,
pub status: InvoiceStatus,
pub provider_name: Connector,
pub metadata: Option<SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
}
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Deserialize, Serialize,
)]
#[diesel(
table_name = invoice,
primary_key(id),
check_for_backend(diesel::pg::Pg)
)]
pub struct Invoice {
pub id: common_utils::id_type::InvoiceId,
pub subscription_id: common_utils::id_type::SubscriptionId,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
pub payment_intent_id: Option<common_utils::id_type::PaymentId>,
pub payment_method_id: Option<String>,
pub customer_id: common_utils::id_type::CustomerId,
pub amount: MinorUnit,
pub currency: String,
pub status: InvoiceStatus,
pub provider_name: Connector,
pub metadata: Option<SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
}
#[derive(Clone, Debug, Eq, PartialEq, AsChangeset, Deserialize)]
#[diesel(table_name = invoice)]
pub struct InvoiceUpdate {
pub status: Option<InvoiceStatus>,
pub payment_method_id: Option<String>,
pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
pub modified_at: time::PrimitiveDateTime,
pub payment_intent_id: Option<common_utils::id_type::PaymentId>,
pub amount: Option<MinorUnit>,
pub currency: Option<String>,
}
impl InvoiceNew {
#[allow(clippy::too_many_arguments)]
pub fn new(
subscription_id: common_utils::id_type::SubscriptionId,
merchant_id: common_utils::id_type::MerchantId,
profile_id: common_utils::id_type::ProfileId,
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
payment_intent_id: Option<common_utils::id_type::PaymentId>,
payment_method_id: Option<String>,
customer_id: common_utils::id_type::CustomerId,
amount: MinorUnit,
currency: String,
status: InvoiceStatus,
provider_name: Connector,
metadata: Option<SecretSerdeValue>,
connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
) -> Self {
let id = common_utils::id_type::InvoiceId::generate();
let now = common_utils::date_time::now();
Self {
id,
subscription_id,
merchant_id,
profile_id,
merchant_connector_id,
payment_intent_id,
payment_method_id,
customer_id,
amount,
currency,
status,
provider_name,
metadata,
created_at: now,
modified_at: now,
connector_invoice_id,
}
}
}
impl InvoiceUpdate {
pub fn new(
amount: Option<MinorUnit>,
currency: Option<String>,
payment_method_id: Option<String>,
status: Option<InvoiceStatus>,
connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
payment_intent_id: Option<common_utils::id_type::PaymentId>,
) -> Self {
Self {
status,
payment_method_id,
connector_invoice_id,
modified_at: common_utils::date_time::now(),
payment_intent_id,
amount,
currency,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/relay.rs | crates/diesel_models/src/relay.rs | use common_utils::pii;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;
use crate::{enums as storage_enums, schema::relay};
#[derive(
Clone,
Debug,
Eq,
Identifiable,
Queryable,
Selectable,
PartialEq,
serde::Serialize,
serde::Deserialize,
)]
#[diesel(table_name = relay)]
pub struct Relay {
pub id: common_utils::id_type::RelayId,
pub connector_resource_id: String,
pub connector_id: common_utils::id_type::MerchantConnectorAccountId,
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_id: common_utils::id_type::MerchantId,
pub relay_type: storage_enums::RelayType,
pub request_data: Option<pii::SecretSerdeValue>,
pub status: storage_enums::RelayStatus,
pub connector_reference_id: Option<String>,
pub error_code: Option<String>,
pub error_message: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub response_data: Option<pii::SecretSerdeValue>,
}
#[derive(
Clone,
Debug,
Eq,
PartialEq,
Insertable,
router_derive::DebugAsDisplay,
serde::Serialize,
serde::Deserialize,
router_derive::Setter,
)]
#[diesel(table_name = relay)]
pub struct RelayNew {
pub id: common_utils::id_type::RelayId,
pub connector_resource_id: String,
pub connector_id: common_utils::id_type::MerchantConnectorAccountId,
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_id: common_utils::id_type::MerchantId,
pub relay_type: storage_enums::RelayType,
pub request_data: Option<pii::SecretSerdeValue>,
pub status: storage_enums::RelayStatus,
pub connector_reference_id: Option<String>,
pub error_code: Option<String>,
pub error_message: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub response_data: Option<pii::SecretSerdeValue>,
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = relay)]
pub struct RelayUpdateInternal {
pub connector_reference_id: Option<String>,
pub status: Option<storage_enums::RelayStatus>,
pub error_code: Option<String>,
pub error_message: Option<String>,
pub modified_at: PrimitiveDateTime,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/file.rs | crates/diesel_models/src/file.rs | use common_utils::custom_serde;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use masking::{Deserialize, Serialize};
use crate::schema::file_metadata;
#[derive(Clone, Debug, Deserialize, Insertable, Serialize, router_derive::DebugAsDisplay)]
#[diesel(table_name = file_metadata)]
#[serde(deny_unknown_fields)]
pub struct FileMetadataNew {
pub file_id: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub file_name: Option<String>,
pub file_size: i32,
pub file_type: String,
pub provider_file_id: Option<String>,
pub file_upload_provider: Option<common_enums::FileUploadProvider>,
pub available: bool,
pub connector_label: Option<String>,
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[derive(Clone, Debug, Deserialize, Serialize, Identifiable, Queryable, Selectable)]
#[diesel(table_name = file_metadata, primary_key(file_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct FileMetadata {
#[serde(skip_serializing)]
pub file_id: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub file_name: Option<String>,
pub file_size: i32,
pub file_type: String,
pub provider_file_id: Option<String>,
pub file_upload_provider: Option<common_enums::FileUploadProvider>,
pub available: bool,
#[serde(with = "custom_serde::iso8601")]
pub created_at: time::PrimitiveDateTime,
pub connector_label: Option<String>,
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[derive(Debug)]
pub enum FileMetadataUpdate {
Update {
provider_file_id: Option<String>,
file_upload_provider: Option<common_enums::FileUploadProvider>,
available: bool,
profile_id: Option<common_utils::id_type::ProfileId>,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
},
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = file_metadata)]
pub struct FileMetadataUpdateInternal {
provider_file_id: Option<String>,
file_upload_provider: Option<common_enums::FileUploadProvider>,
available: bool,
profile_id: Option<common_utils::id_type::ProfileId>,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
impl From<FileMetadataUpdate> for FileMetadataUpdateInternal {
fn from(merchant_account_update: FileMetadataUpdate) -> Self {
match merchant_account_update {
FileMetadataUpdate::Update {
provider_file_id,
file_upload_provider,
available,
profile_id,
merchant_connector_id,
} => Self {
provider_file_id,
file_upload_provider,
available,
profile_id,
merchant_connector_id,
},
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/types.rs | crates/diesel_models/src/types.rs | #[cfg(feature = "v2")]
use common_enums::enums::PaymentConnectorTransmission;
#[cfg(feature = "v2")]
use common_utils::id_type;
use common_utils::{hashing::HashedString, pii, types::MinorUnit};
use diesel::{
sql_types::{Json, Jsonb},
AsExpression, FromSqlRow,
};
use masking::{Secret, WithType};
use serde::{self, Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, FromSqlRow, AsExpression)]
#[diesel(sql_type = Jsonb)]
pub struct OrderDetailsWithAmount {
/// Name of the product that is being purchased
pub product_name: String,
/// The quantity of the product to be purchased
pub quantity: u16,
/// the amount per quantity of product
pub amount: MinorUnit,
// Does the order includes shipping
pub requires_shipping: Option<bool>,
/// The image URL of the product
pub product_img_link: Option<String>,
/// ID of the product that is being purchased
pub product_id: Option<String>,
/// Category of the product that is being purchased
pub category: Option<String>,
/// Sub category of the product that is being purchased
pub sub_category: Option<String>,
/// Brand of the product that is being purchased
pub brand: Option<String>,
/// Type of the product that is being purchased
pub product_type: Option<common_enums::ProductType>,
/// The tax code for the product
pub product_tax_code: Option<String>,
/// tax rate applicable to the product
pub tax_rate: Option<f64>,
/// total tax amount applicable to the product
pub total_tax_amount: Option<MinorUnit>,
/// description of the product
pub description: Option<String>,
/// stock keeping unit of the product
pub sku: Option<String>,
/// universal product code of the product
pub upc: Option<String>,
/// commodity code of the product
pub commodity_code: Option<String>,
/// unit of measure of the product
pub unit_of_measure: Option<String>,
/// total amount of the product
pub total_amount: Option<MinorUnit>,
/// discount amount on the unit
pub unit_discount_amount: Option<MinorUnit>,
}
impl masking::SerializableSecret for OrderDetailsWithAmount {}
common_utils::impl_to_sql_from_sql_json!(OrderDetailsWithAmount);
#[cfg(feature = "v2")]
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)]
#[diesel(sql_type = Json)]
pub struct FeatureMetadata {
/// Redirection response coming in request as metadata field only for redirection scenarios
pub redirect_response: Option<RedirectResponse>,
/// Additional tags to be used for global search
pub search_tags: Option<Vec<HashedString<WithType>>>,
/// Recurring payment details required for apple pay Merchant Token
pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>,
/// revenue recovery data for payment intent
pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>,
}
#[cfg(feature = "v2")]
impl FeatureMetadata {
pub fn get_payment_method_sub_type(&self) -> Option<common_enums::PaymentMethodType> {
self.payment_revenue_recovery_metadata
.as_ref()
.map(|rrm| rrm.payment_method_subtype)
}
pub fn get_payment_method_type(&self) -> Option<common_enums::PaymentMethod> {
self.payment_revenue_recovery_metadata
.as_ref()
.map(|recovery_metadata| recovery_metadata.payment_method_type)
}
pub fn get_billing_merchant_connector_account_id(
&self,
) -> Option<id_type::MerchantConnectorAccountId> {
self.payment_revenue_recovery_metadata
.as_ref()
.map(|recovery_metadata| recovery_metadata.billing_connector_id.clone())
}
// TODO: Check search_tags for relevant payment method type
// TODO: Check redirect_response metadata if applicable
// TODO: Check apple_pay_recurring_details metadata if applicable
}
#[cfg(feature = "v1")]
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)]
#[diesel(sql_type = Json)]
pub struct FeatureMetadata {
/// Redirection response coming in request as metadata field only for redirection scenarios
pub redirect_response: Option<RedirectResponse>,
/// Additional tags to be used for global search
pub search_tags: Option<Vec<HashedString<WithType>>>,
/// Recurring payment details required for apple pay Merchant Token
pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>,
/// The system that the gateway is integrated with, e.g., `Direct`(through hyperswitch), `UnifiedConnectorService`(through ucs), etc.
pub gateway_system: Option<common_enums::GatewaySystem>,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)]
#[diesel(sql_type = Json)]
pub struct ApplePayRecurringDetails {
/// A description of the recurring payment that Apple Pay displays to the user in the payment sheet
pub payment_description: String,
/// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count
pub regular_billing: ApplePayRegularBillingDetails,
/// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment
pub billing_agreement: Option<String>,
/// A URL to a web page where the user can update or delete the payment method for the recurring payment
pub management_url: common_utils::types::Url,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)]
#[diesel(sql_type = Json)]
pub struct ApplePayRegularBillingDetails {
/// The label that Apple Pay displays to the user in the payment sheet with the recurring details
pub label: String,
/// The date of the first payment
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub recurring_payment_start_date: Option<time::PrimitiveDateTime>,
/// The date of the final payment
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub recurring_payment_end_date: Option<time::PrimitiveDateTime>,
/// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval
pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>,
/// The number of interval units that make up the total payment interval
pub recurring_payment_interval_count: Option<i32>,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)]
#[diesel(sql_type = Json)]
#[serde(rename_all = "snake_case")]
pub enum RecurringPaymentIntervalUnit {
Year,
Month,
Day,
Hour,
Minute,
}
common_utils::impl_to_sql_from_sql_json!(ApplePayRecurringDetails);
common_utils::impl_to_sql_from_sql_json!(ApplePayRegularBillingDetails);
common_utils::impl_to_sql_from_sql_json!(RecurringPaymentIntervalUnit);
common_utils::impl_to_sql_from_sql_json!(FeatureMetadata);
#[derive(Default, Debug, Eq, PartialEq, Deserialize, Serialize, Clone)]
pub struct RedirectResponse {
pub param: Option<Secret<String>>,
pub json_payload: Option<pii::SecretSerdeValue>,
}
impl masking::SerializableSecret for RedirectResponse {}
common_utils::impl_to_sql_from_sql_json!(RedirectResponse);
#[cfg(feature = "v2")]
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct PaymentRevenueRecoveryMetadata {
/// Total number of billing connector + recovery retries for a payment intent.
pub total_retry_count: u16,
/// Flag for the payment connector's call
pub payment_connector_transmission: PaymentConnectorTransmission,
/// Billing Connector Id to update the invoices
pub billing_connector_id: id_type::MerchantConnectorAccountId,
/// Payment Connector Id to retry the payments
pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId,
/// Billing Connector Payment Details
pub billing_connector_payment_details: BillingConnectorPaymentDetails,
///Payment Method Type
pub payment_method_type: common_enums::enums::PaymentMethod,
/// PaymentMethod Subtype
pub payment_method_subtype: common_enums::enums::PaymentMethodType,
/// The name of the payment connector through which the payment attempt was made.
pub connector: common_enums::connector_enums::Connector,
/// Time at which next invoice will be created
pub invoice_next_billing_time: Option<time::PrimitiveDateTime>,
/// Time at which invoice started
pub invoice_billing_started_at_time: Option<time::PrimitiveDateTime>,
/// Extra Payment Method Details that are needed to be stored
pub billing_connector_payment_method_details: Option<BillingConnectorPaymentMethodDetails>,
/// First Payment Attempt Payment Gateway Error Code
pub first_payment_attempt_pg_error_code: Option<String>,
/// First Payment Attempt Network Error Code
pub first_payment_attempt_network_decline_code: Option<String>,
/// First Payment Attempt Network Advice Code
pub first_payment_attempt_network_advice_code: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[cfg(feature = "v2")]
pub struct BillingConnectorPaymentDetails {
/// Payment Processor Token to process the Revenue Recovery Payment
pub payment_processor_token: String,
/// Billing Connector's Customer Id
pub connector_customer_id: String,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case", tag = "type", content = "value")]
pub enum BillingConnectorPaymentMethodDetails {
Card(BillingConnectorAdditionalCardInfo),
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct BillingConnectorAdditionalCardInfo {
/// Card Network
pub card_network: Option<common_enums::enums::CardNetwork>,
/// Card Issuer
pub card_issuer: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/merchant_connector_account.rs | crates/diesel_models/src/merchant_connector_account.rs | #[cfg(feature = "v2")]
use std::collections::HashMap;
use std::fmt::Debug;
use common_utils::{encryption::Encryption, id_type, pii};
#[cfg(feature = "v2")]
use diesel::{sql_types::Jsonb, AsExpression};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use crate::enums as storage_enums;
#[cfg(feature = "v1")]
use crate::schema::merchant_connector_account;
#[cfg(feature = "v2")]
use crate::schema_v2::merchant_connector_account;
#[cfg(feature = "v1")]
#[derive(
Clone,
Debug,
serde::Serialize,
serde::Deserialize,
Identifiable,
Queryable,
Selectable,
router_derive::DebugAsDisplay,
)]
#[diesel(table_name = merchant_connector_account, primary_key(merchant_connector_id), check_for_backend(diesel::pg::Pg))]
pub struct MerchantConnectorAccount {
pub merchant_id: id_type::MerchantId,
pub connector_name: String,
pub connector_account_details: Encryption,
pub test_mode: Option<bool>,
pub disabled: Option<bool>,
pub merchant_connector_id: id_type::MerchantConnectorAccountId,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>,
pub connector_type: storage_enums::ConnectorType,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_label: Option<String>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub business_sub_label: Option<String>,
pub frm_configs: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub connector_webhook_details: Option<pii::SecretSerdeValue>,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub frm_config: Option<Vec<pii::SecretSerdeValue>>,
pub profile_id: Option<id_type::ProfileId>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: storage_enums::ConnectorStatus,
pub additional_merchant_data: Option<Encryption>,
pub connector_wallets_details: Option<Encryption>,
pub version: common_enums::ApiVersion,
pub id: Option<id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v1")]
impl MerchantConnectorAccount {
pub fn get_id(&self) -> id_type::MerchantConnectorAccountId {
self.merchant_connector_id.clone()
}
}
#[cfg(feature = "v2")]
use crate::RequiredFromNullable;
#[cfg(feature = "v2")]
#[derive(
Clone,
Debug,
serde::Serialize,
serde::Deserialize,
Identifiable,
Queryable,
Selectable,
router_derive::DebugAsDisplay,
)]
#[diesel(table_name = merchant_connector_account, check_for_backend(diesel::pg::Pg))]
pub struct MerchantConnectorAccount {
pub merchant_id: id_type::MerchantId,
pub connector_name: common_enums::connector_enums::Connector,
pub connector_account_details: Encryption,
pub disabled: Option<bool>,
#[diesel(deserialize_as = super::OptionalDieselArray<common_types::payment_methods::PaymentMethodsEnabled>)]
pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>,
pub connector_type: storage_enums::ConnectorType,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_label: Option<String>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub connector_webhook_details: Option<pii::SecretSerdeValue>,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub frm_config: Option<Vec<pii::SecretSerdeValue>>,
#[diesel(deserialize_as = RequiredFromNullable<id_type::ProfileId>)]
pub profile_id: id_type::ProfileId,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: storage_enums::ConnectorStatus,
pub additional_merchant_data: Option<Encryption>,
pub connector_wallets_details: Option<Encryption>,
pub version: common_enums::ApiVersion,
pub id: id_type::MerchantConnectorAccountId,
pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>,
}
#[cfg(feature = "v2")]
impl MerchantConnectorAccount {
pub fn get_id(&self) -> id_type::MerchantConnectorAccountId {
self.id.clone()
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_connector_account)]
pub struct MerchantConnectorAccountNew {
pub merchant_id: Option<id_type::MerchantId>,
pub connector_type: Option<storage_enums::ConnectorType>,
pub connector_name: Option<String>,
pub connector_account_details: Option<Encryption>,
pub test_mode: Option<bool>,
pub disabled: Option<bool>,
pub merchant_connector_id: id_type::MerchantConnectorAccountId,
pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_label: Option<String>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub business_sub_label: Option<String>,
pub frm_configs: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub connector_webhook_details: Option<pii::SecretSerdeValue>,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub frm_config: Option<Vec<pii::SecretSerdeValue>>,
pub profile_id: Option<id_type::ProfileId>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: storage_enums::ConnectorStatus,
pub additional_merchant_data: Option<Encryption>,
pub connector_wallets_details: Option<Encryption>,
pub version: common_enums::ApiVersion,
pub id: Option<id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_connector_account)]
pub struct MerchantConnectorAccountNew {
pub merchant_id: Option<id_type::MerchantId>,
pub connector_type: Option<storage_enums::ConnectorType>,
pub connector_name: Option<common_enums::connector_enums::Connector>,
pub connector_account_details: Option<Encryption>,
pub disabled: Option<bool>,
#[diesel(deserialize_as = super::OptionalDieselArray<common_types::payment_methods::PaymentMethodsEnabled>)]
pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_label: Option<String>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub connector_webhook_details: Option<pii::SecretSerdeValue>,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub frm_config: Option<Vec<pii::SecretSerdeValue>>,
pub profile_id: id_type::ProfileId,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: storage_enums::ConnectorStatus,
pub additional_merchant_data: Option<Encryption>,
pub connector_wallets_details: Option<Encryption>,
pub version: common_enums::ApiVersion,
pub id: id_type::MerchantConnectorAccountId,
pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_connector_account)]
pub struct MerchantConnectorAccountUpdateInternal {
pub connector_type: Option<storage_enums::ConnectorType>,
pub connector_name: Option<String>,
pub connector_account_details: Option<Encryption>,
pub connector_label: Option<String>,
pub test_mode: Option<bool>,
pub disabled: Option<bool>,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>,
pub frm_configs: Option<pii::SecretSerdeValue>,
pub metadata: Option<pii::SecretSerdeValue>,
pub modified_at: Option<time::PrimitiveDateTime>,
pub connector_webhook_details: Option<pii::SecretSerdeValue>,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub frm_config: Option<Vec<pii::SecretSerdeValue>>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: Option<storage_enums::ConnectorStatus>,
pub connector_wallets_details: Option<Encryption>,
pub additional_merchant_data: Option<Encryption>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_connector_account)]
pub struct MerchantConnectorAccountUpdateInternal {
pub connector_type: Option<storage_enums::ConnectorType>,
pub connector_account_details: Option<Encryption>,
pub connector_label: Option<String>,
pub disabled: Option<bool>,
#[diesel(deserialize_as = super::OptionalDieselArray<common_types::payment_methods::PaymentMethodsEnabled>)]
pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>,
pub metadata: Option<pii::SecretSerdeValue>,
pub modified_at: Option<time::PrimitiveDateTime>,
pub connector_webhook_details: Option<pii::SecretSerdeValue>,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub frm_config: Option<Vec<pii::SecretSerdeValue>>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: Option<storage_enums::ConnectorStatus>,
pub connector_wallets_details: Option<Encryption>,
pub additional_merchant_data: Option<Encryption>,
pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>,
}
#[cfg(feature = "v1")]
impl MerchantConnectorAccountUpdateInternal {
pub fn create_merchant_connector_account(
self,
source: MerchantConnectorAccount,
) -> MerchantConnectorAccount {
MerchantConnectorAccount {
merchant_id: source.merchant_id,
connector_type: self.connector_type.unwrap_or(source.connector_type),
connector_account_details: self
.connector_account_details
.unwrap_or(source.connector_account_details),
test_mode: self.test_mode,
disabled: self.disabled,
merchant_connector_id: self
.merchant_connector_id
.unwrap_or(source.merchant_connector_id),
payment_methods_enabled: self.payment_methods_enabled,
frm_config: self.frm_config,
modified_at: self.modified_at.unwrap_or(source.modified_at),
pm_auth_config: self.pm_auth_config,
status: self.status.unwrap_or(source.status),
..source
}
}
}
#[cfg(feature = "v2")]
impl MerchantConnectorAccountUpdateInternal {
pub fn create_merchant_connector_account(
self,
source: MerchantConnectorAccount,
) -> MerchantConnectorAccount {
MerchantConnectorAccount {
connector_type: self.connector_type.unwrap_or(source.connector_type),
connector_account_details: self
.connector_account_details
.unwrap_or(source.connector_account_details),
disabled: self.disabled,
payment_methods_enabled: self.payment_methods_enabled,
frm_config: self.frm_config,
modified_at: self.modified_at.unwrap_or(source.modified_at),
pm_auth_config: self.pm_auth_config,
status: self.status.unwrap_or(source.status),
feature_metadata: self.feature_metadata,
..source
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, AsExpression)]
#[diesel(sql_type = Jsonb)]
pub struct MerchantConnectorAccountFeatureMetadata {
pub revenue_recovery: Option<RevenueRecoveryMetadata>,
}
#[cfg(feature = "v2")]
common_utils::impl_to_sql_from_sql_json!(MerchantConnectorAccountFeatureMetadata);
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct RevenueRecoveryMetadata {
/// The maximum number of retries allowed for an invoice. This limit is set by the merchant for each `billing connector`.Once this limit is reached, no further retries will be attempted.
pub max_retry_count: u16,
/// Maximum number of `billing connector` retries before revenue recovery can start executing retries.
pub billing_connector_retry_threshold: u16,
/// Billing account reference id is payment gateway id at billing connector end.
/// Merchants need to provide a mapping between these merchant connector account and the corresponding
/// account reference IDs for each `billing connector`.
pub billing_account_reference: BillingAccountReference,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BillingAccountReference(pub HashMap<id_type::MerchantConnectorAccountId, String>);
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/blocklist_lookup.rs | crates/diesel_models/src/blocklist_lookup.rs | use diesel::{Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use crate::schema::blocklist_lookup;
#[derive(Default, Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)]
#[diesel(table_name = blocklist_lookup)]
pub struct BlocklistLookupNew {
pub merchant_id: common_utils::id_type::MerchantId,
pub fingerprint: String,
}
#[derive(
Default,
Clone,
Debug,
Eq,
PartialEq,
Identifiable,
Queryable,
Selectable,
Deserialize,
Serialize,
)]
#[diesel(table_name = blocklist_lookup, primary_key(merchant_id, fingerprint), check_for_backend(diesel::pg::Pg))]
pub struct BlocklistLookup {
pub merchant_id: common_utils::id_type::MerchantId,
pub fingerprint: String,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/payment_method.rs | crates/diesel_models/src/payment_method.rs | use std::collections::HashMap;
use common_enums::MerchantStorageScheme;
use common_utils::{
encryption::Encryption,
errors::{CustomResult, ParsingError},
pii,
};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use error_stack::ResultExt;
#[cfg(feature = "v1")]
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
#[cfg(feature = "v1")]
use crate::{enums as storage_enums, schema::payment_methods};
#[cfg(feature = "v2")]
use crate::{enums as storage_enums, schema_v2::payment_methods};
#[cfg(feature = "v1")]
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize,
)]
#[diesel(table_name = payment_methods, primary_key(payment_method_id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentMethod {
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_method_id: String,
#[diesel(deserialize_as = super::OptionalDieselArray<storage_enums::Currency>)]
pub accepted_currency: Option<Vec<storage_enums::Currency>>,
pub scheme: Option<String>,
pub token: Option<String>,
pub cardholder_name: Option<Secret<String>>,
pub issuer_name: Option<String>,
pub issuer_country: Option<String>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub payer_country: Option<Vec<String>>,
pub is_stored: Option<bool>,
pub swift_code: Option<String>,
pub direct_debit_token: Option<String>,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_issuer: Option<String>,
pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<serde_json::Value>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub client_secret: Option<String>,
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
pub network_token_payment_method_data: Option<Encryption>,
pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub vault_type: Option<storage_enums::VaultType>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)]
#[diesel(table_name = payment_methods, primary_key(id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentMethod {
pub customer_id: common_utils::id_type::GlobalCustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<CommonMandateReference>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub client_secret: Option<String>,
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
pub network_token_payment_method_data: Option<Encryption>,
pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub vault_type: Option<storage_enums::VaultType>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
pub locker_fingerprint_id: Option<String>,
pub payment_method_type_v2: Option<storage_enums::PaymentMethod>,
pub payment_method_subtype: Option<storage_enums::PaymentMethodType>,
pub id: common_utils::id_type::GlobalPaymentMethodId,
pub external_vault_token_data: Option<Encryption>,
}
impl PaymentMethod {
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &String {
&self.payment_method_id
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId {
&self.id
}
}
#[cfg(feature = "v1")]
#[derive(
Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize,
)]
#[diesel(table_name = payment_methods)]
pub struct PaymentMethodNew {
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_method_id: String,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_issuer: Option<String>,
pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
pub accepted_currency: Option<Vec<storage_enums::Currency>>,
pub scheme: Option<String>,
pub token: Option<String>,
pub cardholder_name: Option<Secret<String>>,
pub issuer_name: Option<String>,
pub issuer_country: Option<String>,
pub payer_country: Option<Vec<String>>,
pub is_stored: Option<bool>,
pub swift_code: Option<String>,
pub direct_debit_token: Option<String>,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<serde_json::Value>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub client_secret: Option<String>,
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
pub network_token_payment_method_data: Option<Encryption>,
pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub vault_type: Option<storage_enums::VaultType>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = payment_methods)]
pub struct PaymentMethodNew {
pub customer_id: common_utils::id_type::GlobalCustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<CommonMandateReference>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub client_secret: Option<String>,
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
pub network_token_payment_method_data: Option<Encryption>,
pub external_vault_token_data: Option<Encryption>,
pub locker_fingerprint_id: Option<String>,
pub payment_method_type_v2: Option<storage_enums::PaymentMethod>,
pub payment_method_subtype: Option<storage_enums::PaymentMethodType>,
pub id: common_utils::id_type::GlobalPaymentMethodId,
pub vault_type: Option<storage_enums::VaultType>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
}
impl PaymentMethodNew {
pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) {
self.updated_by = Some(storage_scheme.to_string());
}
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &String {
&self.payment_method_id
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId {
&self.id
}
}
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct TokenizeCoreWorkflow {
pub lookup_key: String,
pub pm: storage_enums::PaymentMethod,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize)]
pub enum PaymentMethodUpdate {
MetadataUpdateAndLastUsed {
metadata: Option<serde_json::Value>,
last_used_at: PrimitiveDateTime,
last_modified_by: Option<String>,
},
UpdatePaymentMethodDataAndLastUsed {
payment_method_data: Option<Encryption>,
scheme: Option<String>,
last_used_at: PrimitiveDateTime,
last_modified_by: Option<String>,
},
PaymentMethodDataUpdate {
payment_method_data: Option<Encryption>,
last_modified_by: Option<String>,
},
LastUsedUpdate {
last_used_at: PrimitiveDateTime,
},
NetworkTransactionIdAndStatusUpdate {
network_transaction_id: Option<String>,
status: Option<storage_enums::PaymentMethodStatus>,
last_modified_by: Option<String>,
},
StatusUpdate {
status: Option<storage_enums::PaymentMethodStatus>,
last_modified_by: Option<String>,
},
AdditionalDataUpdate {
payment_method_data: Option<Encryption>,
status: Option<storage_enums::PaymentMethodStatus>,
locker_id: Option<String>,
payment_method: Option<storage_enums::PaymentMethod>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
payment_method_issuer: Option<String>,
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: Option<Encryption>,
last_modified_by: Option<String>,
},
ConnectorMandateDetailsUpdate {
connector_mandate_details: Option<serde_json::Value>,
last_modified_by: Option<String>,
},
NetworkTokenDataUpdate {
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: Option<Encryption>,
last_modified_by: Option<String>,
},
ConnectorNetworkTransactionIdAndMandateDetailsUpdate {
connector_mandate_details: Option<pii::SecretSerdeValue>,
network_transaction_id: Option<Secret<String>>,
last_modified_by: Option<String>,
},
PaymentMethodBatchUpdate {
connector_mandate_details: Option<pii::SecretSerdeValue>,
network_transaction_id: Option<String>,
status: Option<storage_enums::PaymentMethodStatus>,
payment_method_data: Option<Encryption>,
last_modified_by: Option<String>,
},
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize, Deserialize)]
pub enum PaymentMethodUpdate {
UpdatePaymentMethodDataAndLastUsed {
payment_method_data: Option<Encryption>,
scheme: Option<String>,
last_used_at: PrimitiveDateTime,
last_modified_by: Option<String>,
},
PaymentMethodDataUpdate {
payment_method_data: Option<Encryption>,
last_modified_by: Option<String>,
},
LastUsedUpdate {
last_used_at: PrimitiveDateTime,
},
NetworkTransactionIdAndStatusUpdate {
network_transaction_id: Option<String>,
status: Option<storage_enums::PaymentMethodStatus>,
last_modified_by: Option<String>,
},
StatusUpdate {
status: Option<storage_enums::PaymentMethodStatus>,
last_modified_by: Option<String>,
},
GenericUpdate {
payment_method_data: Option<Encryption>,
status: Option<storage_enums::PaymentMethodStatus>,
locker_id: Option<String>,
payment_method_type_v2: Option<storage_enums::PaymentMethod>,
payment_method_subtype: Option<storage_enums::PaymentMethodType>,
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: Option<Encryption>,
locker_fingerprint_id: Option<String>,
connector_mandate_details: Option<CommonMandateReference>,
external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
last_modified_by: Option<String>,
},
ConnectorMandateDetailsUpdate {
connector_mandate_details: Option<CommonMandateReference>,
last_modified_by: Option<String>,
},
}
impl PaymentMethodUpdate {
pub fn convert_to_payment_method_update(
self,
storage_scheme: MerchantStorageScheme,
) -> PaymentMethodUpdateInternal {
let mut update_internal: PaymentMethodUpdateInternal = self.into();
update_internal.updated_by = Some(storage_scheme.to_string());
update_internal
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = payment_methods)]
pub struct PaymentMethodUpdateInternal {
payment_method_data: Option<Encryption>,
last_used_at: Option<PrimitiveDateTime>,
network_transaction_id: Option<String>,
status: Option<storage_enums::PaymentMethodStatus>,
locker_id: Option<String>,
payment_method_type_v2: Option<storage_enums::PaymentMethod>,
connector_mandate_details: Option<CommonMandateReference>,
updated_by: Option<String>,
payment_method_subtype: Option<storage_enums::PaymentMethodType>,
last_modified: PrimitiveDateTime,
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: Option<Encryption>,
locker_fingerprint_id: Option<String>,
external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
last_modified_by: Option<String>,
}
#[cfg(feature = "v2")]
impl PaymentMethodUpdateInternal {
pub fn apply_changeset(self, source: PaymentMethod) -> PaymentMethod {
let Self {
payment_method_data,
last_used_at,
network_transaction_id,
status,
locker_id,
payment_method_type_v2,
connector_mandate_details,
updated_by,
payment_method_subtype,
last_modified,
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
locker_fingerprint_id,
external_vault_source,
last_modified_by,
} = self;
PaymentMethod {
customer_id: source.customer_id,
merchant_id: source.merchant_id,
created_at: source.created_at,
last_modified,
payment_method_data: payment_method_data.or(source.payment_method_data),
locker_id: locker_id.or(source.locker_id),
last_used_at: last_used_at.unwrap_or(source.last_used_at),
connector_mandate_details: connector_mandate_details
.or(source.connector_mandate_details),
customer_acceptance: source.customer_acceptance,
status: status.unwrap_or(source.status),
network_transaction_id: network_transaction_id.or(source.network_transaction_id),
client_secret: source.client_secret,
payment_method_billing_address: source.payment_method_billing_address,
updated_by: updated_by.or(source.updated_by),
locker_fingerprint_id: locker_fingerprint_id.or(source.locker_fingerprint_id),
payment_method_type_v2: payment_method_type_v2.or(source.payment_method_type_v2),
payment_method_subtype: payment_method_subtype.or(source.payment_method_subtype),
id: source.id,
version: source.version,
network_token_requestor_reference_id: network_token_requestor_reference_id
.or(source.network_token_requestor_reference_id),
network_token_locker_id: network_token_locker_id.or(source.network_token_locker_id),
network_token_payment_method_data: network_token_payment_method_data
.or(source.network_token_payment_method_data),
external_vault_source: external_vault_source.or(source.external_vault_source),
external_vault_token_data: source.external_vault_token_data,
vault_type: source.vault_type,
created_by: source.created_by,
last_modified_by: last_modified_by.or(source.last_modified_by),
}
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = payment_methods)]
pub struct PaymentMethodUpdateInternal {
metadata: Option<serde_json::Value>,
payment_method_data: Option<Encryption>,
last_used_at: Option<PrimitiveDateTime>,
network_transaction_id: Option<String>,
status: Option<storage_enums::PaymentMethodStatus>,
locker_id: Option<String>,
network_token_requestor_reference_id: Option<String>,
payment_method: Option<storage_enums::PaymentMethod>,
connector_mandate_details: Option<serde_json::Value>,
updated_by: Option<String>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
payment_method_issuer: Option<String>,
last_modified: PrimitiveDateTime,
network_token_locker_id: Option<String>,
network_token_payment_method_data: Option<Encryption>,
scheme: Option<String>,
last_modified_by: Option<String>,
}
#[cfg(feature = "v1")]
impl PaymentMethodUpdateInternal {
pub fn apply_changeset(self, source: PaymentMethod) -> PaymentMethod {
let Self {
metadata,
payment_method_data,
last_used_at,
network_transaction_id,
status,
locker_id,
network_token_requestor_reference_id,
payment_method,
connector_mandate_details,
updated_by,
payment_method_type,
payment_method_issuer,
last_modified,
network_token_locker_id,
network_token_payment_method_data,
scheme,
last_modified_by,
} = self;
PaymentMethod {
customer_id: source.customer_id,
merchant_id: source.merchant_id,
payment_method_id: source.payment_method_id,
accepted_currency: source.accepted_currency,
scheme: scheme.or(source.scheme),
token: source.token,
cardholder_name: source.cardholder_name,
issuer_name: source.issuer_name,
issuer_country: source.issuer_country,
payer_country: source.payer_country,
is_stored: source.is_stored,
swift_code: source.swift_code,
direct_debit_token: source.direct_debit_token,
created_at: source.created_at,
last_modified,
payment_method: payment_method.or(source.payment_method),
payment_method_type: payment_method_type.or(source.payment_method_type),
payment_method_issuer: payment_method_issuer.or(source.payment_method_issuer),
payment_method_issuer_code: source.payment_method_issuer_code,
metadata: metadata.map_or(source.metadata, |v| Some(v.into())),
payment_method_data: payment_method_data.or(source.payment_method_data),
locker_id: locker_id.or(source.locker_id),
last_used_at: last_used_at.unwrap_or(source.last_used_at),
connector_mandate_details: connector_mandate_details
.or(source.connector_mandate_details),
customer_acceptance: source.customer_acceptance,
status: status.unwrap_or(source.status),
network_transaction_id: network_transaction_id.or(source.network_transaction_id),
client_secret: source.client_secret,
payment_method_billing_address: source.payment_method_billing_address,
updated_by: updated_by.or(source.updated_by),
version: source.version,
network_token_requestor_reference_id: network_token_requestor_reference_id
.or(source.network_token_requestor_reference_id),
network_token_locker_id: network_token_locker_id.or(source.network_token_locker_id),
network_token_payment_method_data: network_token_payment_method_data
.or(source.network_token_payment_method_data),
external_vault_source: source.external_vault_source,
vault_type: source.vault_type,
created_by: source.created_by,
last_modified_by: last_modified_by.or(source.last_modified_by),
}
}
}
#[cfg(feature = "v1")]
impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
fn from(payment_method_update: PaymentMethodUpdate) -> Self {
match payment_method_update {
PaymentMethodUpdate::MetadataUpdateAndLastUsed {
metadata,
last_used_at,
last_modified_by,
} => Self {
metadata,
payment_method_data: None,
last_used_at: Some(last_used_at),
network_transaction_id: None,
status: None,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
},
PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data,
last_modified_by,
} => Self {
metadata: None,
payment_method_data,
last_used_at: None,
network_transaction_id: None,
status: None,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
},
PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
metadata: None,
payment_method_data: None,
last_used_at: Some(last_used_at),
network_transaction_id: None,
status: None,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
last_modified_by: None,
},
PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed {
payment_method_data,
scheme,
last_used_at,
last_modified_by,
} => Self {
metadata: None,
payment_method_data,
last_used_at: Some(last_used_at),
network_transaction_id: None,
status: None,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme,
last_modified_by,
},
PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
status,
last_modified_by,
} => Self {
metadata: None,
payment_method_data: None,
last_used_at: None,
network_transaction_id,
status,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
},
PaymentMethodUpdate::StatusUpdate {
status,
last_modified_by,
} => Self {
metadata: None,
payment_method_data: None,
last_used_at: None,
network_transaction_id: None,
status,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
},
PaymentMethodUpdate::AdditionalDataUpdate {
payment_method_data,
status,
locker_id,
network_token_requestor_reference_id,
payment_method,
payment_method_type,
payment_method_issuer,
network_token_locker_id,
network_token_payment_method_data,
last_modified_by,
} => Self {
metadata: None,
payment_method_data,
last_used_at: None,
network_transaction_id: None,
status,
locker_id,
network_token_requestor_reference_id,
payment_method,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer,
payment_method_type,
last_modified: common_utils::date_time::now(),
network_token_locker_id,
network_token_payment_method_data,
scheme: None,
last_modified_by,
},
PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details,
last_modified_by,
} => Self {
metadata: None,
payment_method_data: None,
last_used_at: None,
status: None,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details,
network_transaction_id: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
},
PaymentMethodUpdate::NetworkTokenDataUpdate {
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
last_modified_by,
} => Self {
metadata: None,
payment_method_data: None,
last_used_at: None,
status: None,
locker_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_transaction_id: None,
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
scheme: None,
last_modified_by,
},
PaymentMethodUpdate::ConnectorNetworkTransactionIdAndMandateDetailsUpdate {
connector_mandate_details,
network_transaction_id,
last_modified_by,
} => Self {
connector_mandate_details: connector_mandate_details
.map(|mandate_details| mandate_details.expose()),
network_transaction_id: network_transaction_id.map(|txn_id| txn_id.expose()),
last_modified: common_utils::date_time::now(),
status: None,
metadata: None,
payment_method_data: None,
last_used_at: None,
locker_id: None,
payment_method: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
network_token_requestor_reference_id: None,
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
},
PaymentMethodUpdate::PaymentMethodBatchUpdate {
connector_mandate_details,
network_transaction_id,
status,
payment_method_data,
last_modified_by,
} => Self {
metadata: None,
last_used_at: None,
status,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: connector_mandate_details
.map(|mandate_details| mandate_details.expose()),
network_transaction_id,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
payment_method_data,
last_modified_by,
},
}
}
}
#[cfg(feature = "v2")]
impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
fn from(payment_method_update: PaymentMethodUpdate) -> Self {
match payment_method_update {
PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data,
last_modified_by,
} => Self {
payment_method_data,
last_used_at: None,
network_transaction_id: None,
status: None,
locker_id: None,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/schema.rs | crates/diesel_models/src/schema.rs | // @generated automatically by Diesel CLI.
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
address (address_id) {
#[max_length = 64]
address_id -> Varchar,
#[max_length = 128]
city -> Nullable<Varchar>,
country -> Nullable<CountryAlpha2>,
line1 -> Nullable<Bytea>,
line2 -> Nullable<Bytea>,
line3 -> Nullable<Bytea>,
state -> Nullable<Bytea>,
zip -> Nullable<Bytea>,
first_name -> Nullable<Bytea>,
last_name -> Nullable<Bytea>,
phone_number -> Nullable<Bytea>,
#[max_length = 8]
country_code -> Nullable<Varchar>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_id -> Nullable<Varchar>,
#[max_length = 32]
updated_by -> Varchar,
email -> Nullable<Bytea>,
origin_zip -> Nullable<Bytea>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
api_keys (key_id) {
#[max_length = 64]
key_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
name -> Varchar,
#[max_length = 256]
description -> Nullable<Varchar>,
#[max_length = 128]
hashed_api_key -> Varchar,
#[max_length = 16]
prefix -> Varchar,
created_at -> Timestamp,
expires_at -> Nullable<Timestamp>,
last_used -> Nullable<Timestamp>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
authentication (authentication_id) {
#[max_length = 64]
authentication_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
authentication_connector -> Nullable<Varchar>,
#[max_length = 64]
connector_authentication_id -> Nullable<Varchar>,
authentication_data -> Nullable<Jsonb>,
#[max_length = 64]
payment_method_id -> Varchar,
#[max_length = 64]
authentication_type -> Nullable<Varchar>,
#[max_length = 64]
authentication_status -> Varchar,
#[max_length = 64]
authentication_lifecycle_status -> Varchar,
created_at -> Timestamp,
modified_at -> Timestamp,
error_message -> Nullable<Text>,
#[max_length = 64]
error_code -> Nullable<Varchar>,
connector_metadata -> Nullable<Jsonb>,
maximum_supported_version -> Nullable<Jsonb>,
#[max_length = 64]
threeds_server_transaction_id -> Nullable<Varchar>,
#[max_length = 64]
cavv -> Nullable<Varchar>,
#[max_length = 64]
authentication_flow_type -> Nullable<Varchar>,
message_version -> Nullable<Jsonb>,
#[max_length = 64]
eci -> Nullable<Varchar>,
#[max_length = 64]
trans_status -> Nullable<Varchar>,
#[max_length = 64]
acquirer_bin -> Nullable<Varchar>,
#[max_length = 64]
acquirer_merchant_id -> Nullable<Varchar>,
three_ds_method_data -> Nullable<Varchar>,
three_ds_method_url -> Nullable<Varchar>,
acs_url -> Nullable<Varchar>,
challenge_request -> Nullable<Varchar>,
acs_reference_number -> Nullable<Varchar>,
acs_trans_id -> Nullable<Varchar>,
acs_signed_content -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 255]
payment_id -> Nullable<Varchar>,
#[max_length = 128]
merchant_connector_id -> Nullable<Varchar>,
#[max_length = 64]
ds_trans_id -> Nullable<Varchar>,
#[max_length = 128]
directory_server_id -> Nullable<Varchar>,
#[max_length = 64]
acquirer_country_code -> Nullable<Varchar>,
service_details -> Nullable<Jsonb>,
#[max_length = 32]
organization_id -> Varchar,
#[max_length = 128]
authentication_client_secret -> Nullable<Varchar>,
force_3ds_challenge -> Nullable<Bool>,
psd2_sca_exemption_type -> Nullable<ScaExemptionType>,
#[max_length = 2048]
return_url -> Nullable<Varchar>,
amount -> Nullable<Int8>,
currency -> Nullable<Currency>,
billing_address -> Nullable<Bytea>,
shipping_address -> Nullable<Bytea>,
browser_info -> Nullable<Jsonb>,
email -> Nullable<Bytea>,
#[max_length = 128]
profile_acquirer_id -> Nullable<Varchar>,
challenge_code -> Nullable<Varchar>,
challenge_cancel -> Nullable<Varchar>,
challenge_code_reason -> Nullable<Varchar>,
message_extension -> Nullable<Jsonb>,
#[max_length = 255]
challenge_request_key -> Nullable<Varchar>,
customer_details -> Nullable<Bytea>,
earliest_supported_version -> Nullable<Jsonb>,
latest_supported_version -> Nullable<Jsonb>,
#[max_length = 8]
mcc -> Nullable<Varchar>,
#[max_length = 64]
platform -> Nullable<Varchar>,
#[max_length = 255]
device_type -> Nullable<Varchar>,
#[max_length = 255]
device_brand -> Nullable<Varchar>,
#[max_length = 255]
device_os -> Nullable<Varchar>,
#[max_length = 255]
device_display -> Nullable<Varchar>,
#[max_length = 255]
browser_name -> Nullable<Varchar>,
#[max_length = 255]
browser_version -> Nullable<Varchar>,
#[max_length = 255]
scheme_name -> Nullable<Varchar>,
exemption_requested -> Nullable<Bool>,
exemption_accepted -> Nullable<Bool>,
#[max_length = 255]
issuer_id -> Nullable<Varchar>,
#[max_length = 16]
issuer_country -> Nullable<Varchar>,
#[max_length = 8]
merchant_country_code -> Nullable<Varchar>,
#[max_length = 16]
billing_country -> Nullable<Varchar>,
#[max_length = 16]
shipping_country -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist (merchant_id, fingerprint_id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
fingerprint_id -> Varchar,
data_kind -> BlocklistDataKind,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist_fingerprint (merchant_id, fingerprint_id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
fingerprint_id -> Varchar,
data_kind -> BlocklistDataKind,
encrypted_fingerprint -> Text,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist_lookup (merchant_id, fingerprint) {
#[max_length = 64]
merchant_id -> Varchar,
fingerprint -> Text,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
business_profile (profile_id) {
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_name -> Varchar,
created_at -> Timestamp,
modified_at -> Timestamp,
return_url -> Nullable<Text>,
enable_payment_response_hash -> Bool,
#[max_length = 255]
payment_response_hash_key -> Nullable<Varchar>,
redirect_to_merchant_with_http_post -> Bool,
webhook_details -> Nullable<Json>,
metadata -> Nullable<Json>,
routing_algorithm -> Nullable<Json>,
intent_fulfillment_time -> Nullable<Int8>,
frm_routing_algorithm -> Nullable<Jsonb>,
payout_routing_algorithm -> Nullable<Jsonb>,
is_recon_enabled -> Bool,
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
payment_link_config -> Nullable<Jsonb>,
session_expiry -> Nullable<Int8>,
authentication_connector_details -> Nullable<Jsonb>,
payout_link_config -> Nullable<Jsonb>,
is_extended_card_info_enabled -> Nullable<Bool>,
extended_card_info_config -> Nullable<Jsonb>,
is_connector_agnostic_mit_enabled -> Nullable<Bool>,
use_billing_as_payment_method_billing -> Nullable<Bool>,
collect_shipping_details_from_wallet_connector -> Nullable<Bool>,
collect_billing_details_from_wallet_connector -> Nullable<Bool>,
outgoing_webhook_custom_http_headers -> Nullable<Bytea>,
always_collect_billing_details_from_wallet_connector -> Nullable<Bool>,
always_collect_shipping_details_from_wallet_connector -> Nullable<Bool>,
#[max_length = 64]
tax_connector_id -> Nullable<Varchar>,
is_tax_connector_enabled -> Nullable<Bool>,
version -> ApiVersion,
dynamic_routing_algorithm -> Nullable<Json>,
is_network_tokenization_enabled -> Bool,
is_auto_retries_enabled -> Nullable<Bool>,
max_auto_retries_enabled -> Nullable<Int2>,
always_request_extended_authorization -> Nullable<Bool>,
is_click_to_pay_enabled -> Bool,
authentication_product_ids -> Nullable<Jsonb>,
card_testing_guard_config -> Nullable<Jsonb>,
card_testing_secret_key -> Nullable<Bytea>,
is_clear_pan_retries_enabled -> Bool,
force_3ds_challenge -> Nullable<Bool>,
is_debit_routing_enabled -> Bool,
merchant_business_country -> Nullable<CountryAlpha2>,
#[max_length = 64]
id -> Nullable<Varchar>,
is_iframe_redirection_enabled -> Nullable<Bool>,
is_pre_network_tokenization_enabled -> Nullable<Bool>,
three_ds_decision_rule_algorithm -> Nullable<Jsonb>,
acquirer_config_map -> Nullable<Jsonb>,
#[max_length = 16]
merchant_category_code -> Nullable<Varchar>,
#[max_length = 32]
merchant_country_code -> Nullable<Varchar>,
dispute_polling_interval -> Nullable<Int4>,
is_manual_retry_enabled -> Nullable<Bool>,
always_enable_overcapture -> Nullable<Bool>,
#[max_length = 64]
billing_processor_id -> Nullable<Varchar>,
is_external_vault_enabled -> Nullable<Bool>,
external_vault_connector_details -> Nullable<Jsonb>,
is_l2_l3_enabled -> Nullable<Bool>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
callback_mapper (id, type_) {
#[max_length = 128]
id -> Varchar,
#[sql_name = "type"]
#[max_length = 64]
type_ -> Varchar,
data -> Jsonb,
created_at -> Timestamp,
last_modified_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
captures (capture_id) {
#[max_length = 64]
capture_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
status -> CaptureStatus,
amount -> Int8,
currency -> Nullable<Currency>,
#[max_length = 255]
connector -> Varchar,
#[max_length = 255]
error_message -> Nullable<Varchar>,
#[max_length = 255]
error_code -> Nullable<Varchar>,
#[max_length = 255]
error_reason -> Nullable<Varchar>,
tax_amount -> Nullable<Int8>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
authorized_attempt_id -> Varchar,
#[max_length = 128]
connector_capture_id -> Nullable<Varchar>,
capture_sequence -> Int2,
#[max_length = 128]
connector_response_reference_id -> Nullable<Varchar>,
#[max_length = 512]
connector_capture_data -> Nullable<Varchar>,
processor_capture_data -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
cards_info (card_iin) {
#[max_length = 16]
card_iin -> Varchar,
card_issuer -> Nullable<Text>,
card_network -> Nullable<Text>,
card_type -> Nullable<Text>,
card_subtype -> Nullable<Text>,
card_issuing_country -> Nullable<Text>,
#[max_length = 32]
bank_code_id -> Nullable<Varchar>,
#[max_length = 32]
bank_code -> Nullable<Varchar>,
#[max_length = 32]
country_code -> Nullable<Varchar>,
date_created -> Timestamp,
last_updated -> Nullable<Timestamp>,
last_updated_provider -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
configs (key) {
#[max_length = 255]
key -> Varchar,
config -> Text,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
customers (customer_id, merchant_id) {
#[max_length = 64]
customer_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
name -> Nullable<Bytea>,
email -> Nullable<Bytea>,
phone -> Nullable<Bytea>,
#[max_length = 8]
phone_country_code -> Nullable<Varchar>,
#[max_length = 255]
description -> Nullable<Varchar>,
created_at -> Timestamp,
metadata -> Nullable<Json>,
connector_customer -> Nullable<Jsonb>,
modified_at -> Timestamp,
#[max_length = 64]
address_id -> Nullable<Varchar>,
#[max_length = 64]
default_payment_method_id -> Nullable<Varchar>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
version -> ApiVersion,
tax_registration_id -> Nullable<Bytea>,
#[max_length = 255]
created_by -> Nullable<Varchar>,
#[max_length = 255]
last_modified_by -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dashboard_metadata (id) {
id -> Int4,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
org_id -> Varchar,
data_key -> DashboardMetadata,
data_value -> Json,
#[max_length = 64]
created_by -> Varchar,
created_at -> Timestamp,
#[max_length = 64]
last_modified_by -> Varchar,
last_modified_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dispute (dispute_id) {
#[max_length = 64]
dispute_id -> Varchar,
#[max_length = 255]
amount -> Varchar,
#[max_length = 255]
currency -> Varchar,
dispute_stage -> DisputeStage,
dispute_status -> DisputeStatus,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
connector_status -> Varchar,
#[max_length = 255]
connector_dispute_id -> Varchar,
#[max_length = 255]
connector_reason -> Nullable<Varchar>,
#[max_length = 255]
connector_reason_code -> Nullable<Varchar>,
challenge_required_by -> Nullable<Timestamp>,
connector_created_at -> Nullable<Timestamp>,
connector_updated_at -> Nullable<Timestamp>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 255]
connector -> Varchar,
evidence -> Jsonb,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
dispute_amount -> Int8,
#[max_length = 32]
organization_id -> Varchar,
dispute_currency -> Nullable<Currency>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dynamic_routing_stats (attempt_id, merchant_id) {
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
amount -> Int8,
#[max_length = 64]
success_based_routing_connector -> Varchar,
#[max_length = 64]
payment_connector -> Varchar,
currency -> Nullable<Currency>,
#[max_length = 64]
payment_method -> Nullable<Varchar>,
capture_method -> Nullable<CaptureMethod>,
authentication_type -> Nullable<AuthenticationType>,
payment_status -> AttemptStatus,
conclusive_classification -> SuccessBasedRoutingConclusiveState,
created_at -> Timestamp,
#[max_length = 64]
payment_method_type -> Nullable<Varchar>,
#[max_length = 64]
global_success_based_connector -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
events (event_id) {
#[max_length = 64]
event_id -> Varchar,
event_type -> EventType,
event_class -> EventClass,
is_webhook_notified -> Bool,
#[max_length = 64]
primary_object_id -> Varchar,
primary_object_type -> EventObjectType,
created_at -> Timestamp,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
business_profile_id -> Nullable<Varchar>,
primary_object_created_at -> Nullable<Timestamp>,
#[max_length = 64]
idempotent_event_id -> Nullable<Varchar>,
#[max_length = 64]
initial_attempt_id -> Nullable<Varchar>,
request -> Nullable<Bytea>,
response -> Nullable<Bytea>,
delivery_attempt -> Nullable<WebhookDeliveryAttempt>,
metadata -> Nullable<Jsonb>,
is_overall_delivery_successful -> Nullable<Bool>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
file_metadata (file_id, merchant_id) {
#[max_length = 64]
file_id -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
file_name -> Nullable<Varchar>,
file_size -> Int4,
#[max_length = 255]
file_type -> Varchar,
#[max_length = 255]
provider_file_id -> Nullable<Varchar>,
#[max_length = 255]
file_upload_provider -> Nullable<Varchar>,
available -> Bool,
created_at -> Timestamp,
#[max_length = 255]
connector_label -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
fraud_check (frm_id, attempt_id, payment_id, merchant_id) {
#[max_length = 64]
frm_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
created_at -> Timestamp,
#[max_length = 255]
frm_name -> Varchar,
#[max_length = 255]
frm_transaction_id -> Nullable<Varchar>,
frm_transaction_type -> FraudCheckType,
frm_status -> FraudCheckStatus,
frm_score -> Nullable<Int4>,
frm_reason -> Nullable<Jsonb>,
#[max_length = 255]
frm_error -> Nullable<Varchar>,
payment_details -> Nullable<Jsonb>,
metadata -> Nullable<Jsonb>,
modified_at -> Timestamp,
#[max_length = 64]
last_step -> Varchar,
payment_capture_method -> Nullable<CaptureMethod>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
gateway_status_map (connector, flow, sub_flow, code, message) {
#[max_length = 64]
connector -> Varchar,
#[max_length = 64]
flow -> Varchar,
#[max_length = 64]
sub_flow -> Varchar,
#[max_length = 255]
code -> Varchar,
#[max_length = 1024]
message -> Varchar,
#[max_length = 64]
status -> Varchar,
#[max_length = 64]
router_error -> Nullable<Varchar>,
#[max_length = 64]
decision -> Varchar,
created_at -> Timestamp,
last_modified -> Timestamp,
step_up_possible -> Bool,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
#[max_length = 64]
error_category -> Nullable<Varchar>,
clear_pan_possible -> Bool,
feature_data -> Nullable<Jsonb>,
#[max_length = 64]
feature -> Nullable<Varchar>,
#[max_length = 64]
standardised_code -> Nullable<Varchar>,
#[max_length = 1024]
description -> Nullable<Varchar>,
#[max_length = 1024]
user_guidance_message -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
generic_link (link_id) {
#[max_length = 64]
link_id -> Varchar,
#[max_length = 64]
primary_reference -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
created_at -> Timestamp,
last_modified_at -> Timestamp,
expiry -> Timestamp,
link_data -> Jsonb,
link_status -> Jsonb,
link_type -> GenericLinkType,
url -> Text,
return_url -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
hyperswitch_ai_interaction (id, created_at) {
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
session_id -> Nullable<Varchar>,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
org_id -> Nullable<Varchar>,
#[max_length = 64]
role_id -> Nullable<Varchar>,
user_query -> Nullable<Bytea>,
response -> Nullable<Bytea>,
database_query -> Nullable<Text>,
#[max_length = 64]
interaction_status -> Nullable<Varchar>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
hyperswitch_ai_interaction_default (id, created_at) {
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
session_id -> Nullable<Varchar>,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
org_id -> Nullable<Varchar>,
#[max_length = 64]
role_id -> Nullable<Varchar>,
user_query -> Nullable<Bytea>,
response -> Nullable<Bytea>,
database_query -> Nullable<Text>,
#[max_length = 64]
interaction_status -> Nullable<Varchar>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
incremental_authorization (authorization_id, merchant_id) {
#[max_length = 64]
authorization_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
amount -> Int8,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
status -> Varchar,
#[max_length = 255]
error_code -> Nullable<Varchar>,
error_message -> Nullable<Text>,
#[max_length = 64]
connector_authorization_id -> Nullable<Varchar>,
previously_authorized_amount -> Int8,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
invoice (id) {
#[max_length = 64]
id -> Varchar,
#[max_length = 128]
subscription_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 128]
merchant_connector_id -> Varchar,
#[max_length = 64]
payment_intent_id -> Nullable<Varchar>,
#[max_length = 64]
payment_method_id -> Nullable<Varchar>,
#[max_length = 64]
customer_id -> Varchar,
amount -> Int8,
#[max_length = 3]
currency -> Varchar,
#[max_length = 64]
status -> Varchar,
#[max_length = 128]
provider_name -> Varchar,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
connector_invoice_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
locker_mock_up (card_id) {
#[max_length = 255]
card_id -> Varchar,
#[max_length = 255]
external_id -> Varchar,
#[max_length = 255]
card_fingerprint -> Varchar,
#[max_length = 255]
card_global_fingerprint -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
card_number -> Varchar,
#[max_length = 255]
card_exp_year -> Varchar,
#[max_length = 255]
card_exp_month -> Varchar,
#[max_length = 255]
name_on_card -> Nullable<Varchar>,
#[max_length = 255]
nickname -> Nullable<Varchar>,
#[max_length = 255]
customer_id -> Nullable<Varchar>,
duplicate -> Nullable<Bool>,
#[max_length = 8]
card_cvc -> Nullable<Varchar>,
#[max_length = 64]
payment_method_id -> Nullable<Varchar>,
enc_card_data -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
mandate (mandate_id) {
#[max_length = 64]
mandate_id -> Varchar,
#[max_length = 64]
customer_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_method_id -> Varchar,
mandate_status -> MandateStatus,
mandate_type -> MandateType,
customer_accepted_at -> Nullable<Timestamp>,
#[max_length = 64]
customer_ip_address -> Nullable<Varchar>,
#[max_length = 255]
customer_user_agent -> Nullable<Varchar>,
#[max_length = 128]
network_transaction_id -> Nullable<Varchar>,
#[max_length = 64]
previous_attempt_id -> Nullable<Varchar>,
created_at -> Timestamp,
mandate_amount -> Nullable<Int8>,
mandate_currency -> Nullable<Currency>,
amount_captured -> Nullable<Int8>,
#[max_length = 64]
connector -> Varchar,
#[max_length = 128]
connector_mandate_id -> Nullable<Varchar>,
start_date -> Nullable<Timestamp>,
end_date -> Nullable<Timestamp>,
metadata -> Nullable<Jsonb>,
connector_mandate_ids -> Nullable<Jsonb>,
#[max_length = 64]
original_payment_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
#[max_length = 2048]
customer_user_agent_extended -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_account (merchant_id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 255]
return_url -> Nullable<Varchar>,
enable_payment_response_hash -> Bool,
#[max_length = 255]
payment_response_hash_key -> Nullable<Varchar>,
redirect_to_merchant_with_http_post -> Bool,
merchant_name -> Nullable<Bytea>,
merchant_details -> Nullable<Bytea>,
webhook_details -> Nullable<Json>,
sub_merchants_enabled -> Nullable<Bool>,
#[max_length = 64]
parent_merchant_id -> Nullable<Varchar>,
#[max_length = 128]
publishable_key -> Nullable<Varchar>,
storage_scheme -> MerchantStorageScheme,
#[max_length = 64]
locker_id -> Nullable<Varchar>,
metadata -> Nullable<Jsonb>,
routing_algorithm -> Nullable<Json>,
primary_business_details -> Json,
intent_fulfillment_time -> Nullable<Int8>,
created_at -> Timestamp,
modified_at -> Timestamp,
frm_routing_algorithm -> Nullable<Jsonb>,
payout_routing_algorithm -> Nullable<Jsonb>,
#[max_length = 32]
organization_id -> Varchar,
is_recon_enabled -> Bool,
#[max_length = 64]
default_profile -> Nullable<Varchar>,
recon_status -> ReconStatus,
payment_link_config -> Nullable<Jsonb>,
pm_collect_link_config -> Nullable<Jsonb>,
version -> ApiVersion,
is_platform_account -> Bool,
#[max_length = 64]
id -> Nullable<Varchar>,
#[max_length = 64]
product_type -> Nullable<Varchar>,
#[max_length = 64]
merchant_account_type -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_connector_account (merchant_connector_id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
connector_name -> Varchar,
connector_account_details -> Bytea,
test_mode -> Nullable<Bool>,
disabled -> Nullable<Bool>,
#[max_length = 128]
merchant_connector_id -> Varchar,
payment_methods_enabled -> Nullable<Array<Nullable<Json>>>,
connector_type -> ConnectorType,
metadata -> Nullable<Jsonb>,
#[max_length = 255]
connector_label -> Nullable<Varchar>,
business_country -> Nullable<CountryAlpha2>,
#[max_length = 255]
business_label -> Nullable<Varchar>,
#[max_length = 64]
business_sub_label -> Nullable<Varchar>,
frm_configs -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
connector_webhook_details -> Nullable<Jsonb>,
frm_config -> Nullable<Array<Nullable<Jsonb>>>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
pm_auth_config -> Nullable<Jsonb>,
status -> ConnectorStatus,
additional_merchant_data -> Nullable<Bytea>,
connector_wallets_details -> Nullable<Bytea>,
version -> ApiVersion,
#[max_length = 64]
id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_key_store (merchant_id) {
#[max_length = 64]
merchant_id -> Varchar,
key -> Bytea,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
organization (org_id) {
#[max_length = 32]
org_id -> Varchar,
org_name -> Nullable<Text>,
organization_details -> Nullable<Jsonb>,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 32]
id -> Nullable<Varchar>,
organization_name -> Nullable<Text>,
version -> ApiVersion,
#[max_length = 64]
organization_type -> Nullable<Varchar>,
#[max_length = 64]
platform_merchant_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_attempt (attempt_id, merchant_id) {
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
status -> AttemptStatus,
amount -> Int8,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/payouts.rs | crates/diesel_models/src/payouts.rs | use common_utils::{pii, types::MinorUnit};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{self, Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{enums as storage_enums, schema::payouts};
// Payouts
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize,
)]
#[diesel(table_name = payouts, primary_key(payout_id), check_for_backend(diesel::pg::Pg))]
pub struct Payouts {
pub payout_id: common_utils::id_type::PayoutId,
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub address_id: Option<String>,
pub payout_type: Option<storage_enums::PayoutType>,
pub payout_method_id: Option<String>,
pub amount: MinorUnit,
pub destination_currency: storage_enums::Currency,
pub source_currency: storage_enums::Currency,
pub description: Option<String>,
pub recurring: bool,
pub auto_fulfill: bool,
pub return_url: Option<String>,
pub entity_type: storage_enums::PayoutEntityType,
pub metadata: Option<pii::SecretSerdeValue>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub last_modified_at: PrimitiveDateTime,
pub attempt_count: i16,
pub profile_id: common_utils::id_type::ProfileId,
pub status: storage_enums::PayoutStatus,
pub confirm: Option<bool>,
pub payout_link_id: Option<String>,
pub client_secret: Option<String>,
pub priority: Option<storage_enums::PayoutSendPriority>,
pub organization_id: Option<common_utils::id_type::OrganizationId>,
}
#[derive(
Clone,
Debug,
Eq,
PartialEq,
Insertable,
serde::Serialize,
serde::Deserialize,
router_derive::DebugAsDisplay,
router_derive::Setter,
)]
#[diesel(table_name = payouts)]
pub struct PayoutsNew {
pub payout_id: common_utils::id_type::PayoutId,
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub address_id: Option<String>,
pub payout_type: Option<storage_enums::PayoutType>,
pub payout_method_id: Option<String>,
pub amount: MinorUnit,
pub destination_currency: storage_enums::Currency,
pub source_currency: storage_enums::Currency,
pub description: Option<String>,
pub recurring: bool,
pub auto_fulfill: bool,
pub return_url: Option<String>,
pub entity_type: storage_enums::PayoutEntityType,
pub metadata: Option<pii::SecretSerdeValue>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub last_modified_at: PrimitiveDateTime,
pub attempt_count: i16,
pub profile_id: common_utils::id_type::ProfileId,
pub status: storage_enums::PayoutStatus,
pub confirm: Option<bool>,
pub payout_link_id: Option<String>,
pub client_secret: Option<String>,
pub priority: Option<storage_enums::PayoutSendPriority>,
pub organization_id: Option<common_utils::id_type::OrganizationId>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PayoutsUpdate {
Update {
amount: MinorUnit,
destination_currency: storage_enums::Currency,
source_currency: storage_enums::Currency,
description: Option<String>,
recurring: bool,
auto_fulfill: bool,
return_url: Option<String>,
entity_type: storage_enums::PayoutEntityType,
metadata: Option<pii::SecretSerdeValue>,
profile_id: Option<common_utils::id_type::ProfileId>,
status: Option<storage_enums::PayoutStatus>,
confirm: Option<bool>,
payout_type: Option<storage_enums::PayoutType>,
address_id: Option<String>,
customer_id: Option<common_utils::id_type::CustomerId>,
},
PayoutMethodIdUpdate {
payout_method_id: String,
},
RecurringUpdate {
recurring: bool,
},
AttemptCountUpdate {
attempt_count: i16,
},
StatusUpdate {
status: storage_enums::PayoutStatus,
},
ManualUpdate {
status: Option<storage_enums::PayoutStatus>,
},
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = payouts)]
pub struct PayoutsUpdateInternal {
pub amount: Option<MinorUnit>,
pub destination_currency: Option<storage_enums::Currency>,
pub source_currency: Option<storage_enums::Currency>,
pub description: Option<String>,
pub recurring: Option<bool>,
pub auto_fulfill: Option<bool>,
pub return_url: Option<String>,
pub entity_type: Option<storage_enums::PayoutEntityType>,
pub metadata: Option<pii::SecretSerdeValue>,
pub payout_method_id: Option<String>,
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub status: Option<storage_enums::PayoutStatus>,
pub last_modified_at: PrimitiveDateTime,
pub attempt_count: Option<i16>,
pub confirm: Option<bool>,
pub payout_type: Option<common_enums::PayoutType>,
pub address_id: Option<String>,
pub customer_id: Option<common_utils::id_type::CustomerId>,
}
impl Default for PayoutsUpdateInternal {
fn default() -> Self {
Self {
amount: None,
destination_currency: None,
source_currency: None,
description: None,
recurring: None,
auto_fulfill: None,
return_url: None,
entity_type: None,
metadata: None,
payout_method_id: None,
profile_id: None,
status: None,
last_modified_at: common_utils::date_time::now(),
attempt_count: None,
confirm: None,
payout_type: None,
address_id: None,
customer_id: None,
}
}
}
impl From<PayoutsUpdate> for PayoutsUpdateInternal {
fn from(payout_update: PayoutsUpdate) -> Self {
match payout_update {
PayoutsUpdate::Update {
amount,
destination_currency,
source_currency,
description,
recurring,
auto_fulfill,
return_url,
entity_type,
metadata,
profile_id,
status,
confirm,
payout_type,
address_id,
customer_id,
} => Self {
amount: Some(amount),
destination_currency: Some(destination_currency),
source_currency: Some(source_currency),
description,
recurring: Some(recurring),
auto_fulfill: Some(auto_fulfill),
return_url,
entity_type: Some(entity_type),
metadata,
profile_id,
status,
confirm,
payout_type,
address_id,
customer_id,
..Default::default()
},
PayoutsUpdate::PayoutMethodIdUpdate { payout_method_id } => Self {
payout_method_id: Some(payout_method_id),
..Default::default()
},
PayoutsUpdate::RecurringUpdate { recurring } => Self {
recurring: Some(recurring),
..Default::default()
},
PayoutsUpdate::AttemptCountUpdate { attempt_count } => Self {
attempt_count: Some(attempt_count),
..Default::default()
},
PayoutsUpdate::StatusUpdate { status } => Self {
status: Some(status),
..Default::default()
},
PayoutsUpdate::ManualUpdate { status } => Self {
status,
..Default::default()
},
}
}
}
impl PayoutsUpdate {
pub fn apply_changeset(self, source: Payouts) -> Payouts {
let PayoutsUpdateInternal {
amount,
destination_currency,
source_currency,
description,
recurring,
auto_fulfill,
return_url,
entity_type,
metadata,
payout_method_id,
profile_id,
status,
last_modified_at,
attempt_count,
confirm,
payout_type,
address_id,
customer_id,
} = self.into();
Payouts {
amount: amount.unwrap_or(source.amount),
destination_currency: destination_currency.unwrap_or(source.destination_currency),
source_currency: source_currency.unwrap_or(source.source_currency),
description: description.or(source.description),
recurring: recurring.unwrap_or(source.recurring),
auto_fulfill: auto_fulfill.unwrap_or(source.auto_fulfill),
return_url: return_url.or(source.return_url),
entity_type: entity_type.unwrap_or(source.entity_type),
metadata: metadata.or(source.metadata),
payout_method_id: payout_method_id.or(source.payout_method_id),
profile_id: profile_id.unwrap_or(source.profile_id),
status: status.unwrap_or(source.status),
last_modified_at,
attempt_count: attempt_count.unwrap_or(source.attempt_count),
confirm: confirm.or(source.confirm),
payout_type: payout_type.or(source.payout_type),
address_id: address_id.or(source.address_id),
customer_id: customer_id.or(source.customer_id),
..source
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/unified_translations.rs | crates/diesel_models/src/unified_translations.rs | //! Translations
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;
use crate::schema::unified_translations;
#[derive(Clone, Debug, Queryable, Selectable, Identifiable)]
#[diesel(table_name = unified_translations, primary_key(unified_code, unified_message, locale), check_for_backend(diesel::pg::Pg))]
pub struct UnifiedTranslations {
pub unified_code: String,
pub unified_message: String,
pub locale: String,
pub translation: String,
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
}
#[derive(Clone, Debug, Insertable)]
#[diesel(table_name = unified_translations)]
pub struct UnifiedTranslationsNew {
pub unified_code: String,
pub unified_message: String,
pub locale: String,
pub translation: String,
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
}
#[derive(Clone, Debug, AsChangeset)]
#[diesel(table_name = unified_translations)]
pub struct UnifiedTranslationsUpdateInternal {
pub translation: Option<String>,
pub last_modified_at: PrimitiveDateTime,
}
#[derive(Debug)]
pub struct UnifiedTranslationsUpdate {
pub translation: Option<String>,
}
impl From<UnifiedTranslationsUpdate> for UnifiedTranslationsUpdateInternal {
fn from(value: UnifiedTranslationsUpdate) -> Self {
let now = common_utils::date_time::now();
let UnifiedTranslationsUpdate { translation } = value;
Self {
translation,
last_modified_at: now,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/mod.rs | crates/diesel_models/src/mod.rs | #[cfg(all(feature = "v2", feature = "tokenization_v2"))]
pub mod tokenization; | rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/gsm.rs | crates/diesel_models/src/gsm.rs | //! Gateway status mapping
use common_enums::ErrorCategory;
use common_utils::{
custom_serde,
events::{ApiEventMetric, ApiEventsType},
};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;
use crate::schema::gateway_status_map;
#[derive(
Clone,
Debug,
Eq,
PartialEq,
router_derive::DebugAsDisplay,
Identifiable,
Queryable,
Selectable,
serde::Serialize,
)]
#[diesel(table_name = gateway_status_map, primary_key(connector, flow, sub_flow, code, message), check_for_backend(diesel::pg::Pg))]
pub struct GatewayStatusMap {
pub connector: String,
pub flow: String,
pub sub_flow: String,
pub code: String,
pub message: String,
pub status: String,
pub router_error: Option<String>,
pub decision: String,
#[serde(with = "custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "custom_serde::iso8601")]
pub last_modified: PrimitiveDateTime,
pub step_up_possible: bool,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub error_category: Option<ErrorCategory>,
pub clear_pan_possible: bool,
pub feature_data: Option<common_types::domain::GsmFeatureData>,
pub feature: Option<common_enums::GsmFeature>,
pub standardised_code: Option<common_enums::StandardisedCode>,
pub description: Option<String>,
pub user_guidance_message: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Insertable)]
#[diesel(table_name = gateway_status_map)]
pub struct GatewayStatusMappingNew {
pub connector: String,
pub flow: String,
pub sub_flow: String,
pub code: String,
pub message: String,
pub status: String,
pub router_error: Option<String>,
pub decision: String,
pub step_up_possible: bool,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub error_category: Option<ErrorCategory>,
pub clear_pan_possible: bool,
pub feature_data: Option<common_types::domain::GsmFeatureData>,
pub feature: Option<common_enums::GsmFeature>,
pub standardised_code: Option<common_enums::StandardisedCode>,
pub description: Option<String>,
pub user_guidance_message: Option<String>,
}
#[derive(
Clone, Debug, PartialEq, Eq, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize,
)]
#[diesel(table_name = gateway_status_map)]
pub struct GatewayStatusMapperUpdateInternal {
pub connector: Option<String>,
pub flow: Option<String>,
pub sub_flow: Option<String>,
pub code: Option<String>,
pub message: Option<String>,
pub status: Option<String>,
pub router_error: Option<Option<String>>,
pub decision: Option<String>,
pub step_up_possible: Option<bool>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub error_category: Option<ErrorCategory>,
pub last_modified: PrimitiveDateTime,
pub clear_pan_possible: Option<bool>,
pub feature_data: Option<common_types::domain::GsmFeatureData>,
pub feature: Option<common_enums::GsmFeature>,
pub standardised_code: Option<common_enums::StandardisedCode>,
pub description: Option<String>,
pub user_guidance_message: Option<String>,
}
#[derive(Debug)]
pub struct GatewayStatusMappingUpdate {
pub status: Option<String>,
pub router_error: Option<Option<String>>,
pub decision: Option<String>,
pub step_up_possible: Option<bool>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub error_category: Option<ErrorCategory>,
pub clear_pan_possible: Option<bool>,
pub feature_data: Option<common_types::domain::GsmFeatureData>,
pub feature: Option<common_enums::GsmFeature>,
pub standardised_code: Option<common_enums::StandardisedCode>,
pub description: Option<String>,
pub user_guidance_message: Option<String>,
}
impl From<GatewayStatusMappingUpdate> for GatewayStatusMapperUpdateInternal {
fn from(value: GatewayStatusMappingUpdate) -> Self {
let GatewayStatusMappingUpdate {
decision,
status,
router_error,
step_up_possible,
unified_code,
unified_message,
error_category,
clear_pan_possible,
feature_data,
feature,
standardised_code,
description,
user_guidance_message,
} = value;
Self {
status,
router_error,
decision,
step_up_possible,
unified_code,
unified_message,
error_category,
last_modified: common_utils::date_time::now(),
connector: None,
flow: None,
sub_flow: None,
code: None,
message: None,
clear_pan_possible,
feature_data,
feature,
standardised_code,
description,
user_guidance_message,
}
}
}
impl ApiEventMetric for GatewayStatusMap {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Gsm)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/payment_methods_session.rs | crates/diesel_models/src/payment_methods_session.rs | use common_utils::pii;
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct PaymentMethodSession {
pub id: common_utils::id_type::GlobalPaymentMethodSessionId,
pub customer_id: Option<common_utils::id_type::GlobalCustomerId>,
pub billing: Option<common_utils::encryption::Encryption>,
pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>,
pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,
pub tokenization_data: Option<pii::SecretSerdeValue>,
pub return_url: Option<common_utils::types::Url>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub expires_at: time::PrimitiveDateTime,
pub associated_payment_methods: Option<Vec<String>>,
pub associated_payment: Option<common_utils::id_type::GlobalPaymentId>,
pub associated_token_id: Option<common_utils::id_type::GlobalTokenId>,
}
#[cfg(feature = "v2")]
impl PaymentMethodSession {
pub fn apply_changeset(self, update_session: PaymentMethodsSessionUpdateInternal) -> Self {
let Self {
id,
customer_id,
billing,
psp_tokenization,
network_tokenization,
tokenization_data,
expires_at,
return_url,
associated_payment_methods,
associated_payment,
associated_token_id,
} = self;
Self {
id,
customer_id,
billing: update_session.billing.or(billing),
psp_tokenization: update_session.psp_tokenization.or(psp_tokenization),
network_tokenization: update_session.network_tokenization.or(network_tokenization),
tokenization_data: update_session.tokenzation_data.or(tokenization_data),
expires_at,
return_url,
associated_payment_methods,
associated_payment,
associated_token_id,
}
}
}
#[cfg(feature = "v2")]
pub struct PaymentMethodsSessionUpdateInternal {
pub billing: Option<common_utils::encryption::Encryption>,
pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>,
pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,
pub tokenzation_data: Option<masking::Secret<serde_json::Value>>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/authentication.rs | crates/diesel_models/src/authentication.rs | use common_utils::{encryption::Encryption, pii};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{self, Deserialize, Serialize};
use crate::schema::authentication;
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize,
)]
#[diesel(table_name = authentication, primary_key(authentication_id), check_for_backend(diesel::pg::Pg))]
pub struct Authentication {
pub authentication_id: common_utils::id_type::AuthenticationId,
pub merchant_id: common_utils::id_type::MerchantId,
pub authentication_connector: Option<String>,
pub connector_authentication_id: Option<String>,
pub authentication_data: Option<serde_json::Value>,
pub payment_method_id: String,
pub authentication_type: Option<common_enums::DecoupledAuthenticationType>,
pub authentication_status: common_enums::AuthenticationStatus,
pub authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: time::PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: time::PrimitiveDateTime,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub connector_metadata: Option<serde_json::Value>,
pub maximum_supported_version: Option<common_utils::types::SemanticVersion>,
pub threeds_server_transaction_id: Option<String>,
pub cavv: Option<String>,
pub authentication_flow_type: Option<String>,
pub message_version: Option<common_utils::types::SemanticVersion>,
pub eci: Option<String>,
pub trans_status: Option<common_enums::TransactionStatus>,
pub acquirer_bin: Option<String>,
pub acquirer_merchant_id: Option<String>,
pub three_ds_method_data: Option<String>,
pub three_ds_method_url: Option<String>,
pub acs_url: Option<String>,
pub challenge_request: Option<String>,
pub acs_reference_number: Option<String>,
pub acs_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
pub profile_id: common_utils::id_type::ProfileId,
pub payment_id: Option<common_utils::id_type::PaymentId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub ds_trans_id: Option<String>,
pub directory_server_id: Option<String>,
pub acquirer_country_code: Option<String>,
pub service_details: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub authentication_client_secret: Option<String>,
pub force_3ds_challenge: Option<bool>,
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
pub return_url: Option<String>,
pub amount: Option<common_utils::types::MinorUnit>,
pub currency: Option<common_enums::Currency>,
pub billing_address: Option<Encryption>,
pub shipping_address: Option<Encryption>,
pub browser_info: Option<serde_json::Value>,
pub email: Option<Encryption>,
pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,
pub challenge_code: Option<String>,
pub challenge_cancel: Option<String>,
pub challenge_code_reason: Option<String>,
pub message_extension: Option<pii::SecretSerdeValue>,
pub challenge_request_key: Option<String>,
pub customer_details: Option<Encryption>,
pub earliest_supported_version: Option<common_utils::types::SemanticVersion>,
pub latest_supported_version: Option<common_utils::types::SemanticVersion>,
pub mcc: Option<common_enums::MerchantCategoryCode>,
pub platform: Option<String>,
pub device_type: Option<String>,
pub device_brand: Option<String>,
pub device_os: Option<String>,
pub device_display: Option<String>,
pub browser_name: Option<String>,
pub browser_version: Option<String>,
pub scheme_name: Option<String>,
pub exemption_requested: Option<bool>,
pub exemption_accepted: Option<bool>,
pub issuer_id: Option<String>,
pub issuer_country: Option<String>,
pub merchant_country_code: Option<String>,
pub billing_country: Option<String>,
pub shipping_country: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Insertable)]
#[diesel(table_name = authentication)]
pub struct AuthenticationNew {
pub authentication_id: common_utils::id_type::AuthenticationId,
pub merchant_id: common_utils::id_type::MerchantId,
pub authentication_connector: Option<String>,
pub connector_authentication_id: Option<String>,
pub authentication_data: Option<serde_json::Value>,
pub payment_method_id: String,
pub authentication_type: Option<common_enums::DecoupledAuthenticationType>,
pub authentication_status: common_enums::AuthenticationStatus,
pub authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub connector_metadata: Option<serde_json::Value>,
pub maximum_supported_version: Option<common_utils::types::SemanticVersion>,
pub threeds_server_transaction_id: Option<String>,
pub cavv: Option<String>,
pub authentication_flow_type: Option<String>,
pub message_version: Option<common_utils::types::SemanticVersion>,
pub eci: Option<String>,
pub trans_status: Option<common_enums::TransactionStatus>,
pub acquirer_bin: Option<String>,
pub acquirer_merchant_id: Option<String>,
pub three_ds_method_data: Option<String>,
pub three_ds_method_url: Option<String>,
pub acs_url: Option<String>,
pub challenge_request: Option<String>,
pub acs_reference_number: Option<String>,
pub acs_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
pub profile_id: common_utils::id_type::ProfileId,
pub payment_id: Option<common_utils::id_type::PaymentId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub ds_trans_id: Option<String>,
pub directory_server_id: Option<String>,
pub acquirer_country_code: Option<String>,
pub service_details: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub authentication_client_secret: Option<String>,
pub force_3ds_challenge: Option<bool>,
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
pub return_url: Option<String>,
pub amount: Option<common_utils::types::MinorUnit>,
pub currency: Option<common_enums::Currency>,
pub billing_address: Option<Encryption>,
pub shipping_address: Option<Encryption>,
pub browser_info: Option<serde_json::Value>,
pub email: Option<Encryption>,
pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,
pub challenge_code: Option<String>,
pub challenge_cancel: Option<String>,
pub challenge_code_reason: Option<String>,
pub message_extension: Option<pii::SecretSerdeValue>,
pub challenge_request_key: Option<String>,
pub customer_details: Option<Encryption>,
pub earliest_supported_version: Option<common_utils::types::SemanticVersion>,
pub latest_supported_version: Option<common_utils::types::SemanticVersion>,
pub mcc: Option<common_enums::MerchantCategoryCode>,
pub platform: Option<String>,
pub device_type: Option<String>,
pub device_brand: Option<String>,
pub device_os: Option<String>,
pub device_display: Option<String>,
pub browser_name: Option<String>,
pub browser_version: Option<String>,
pub scheme_name: Option<String>,
pub exemption_requested: Option<bool>,
pub exemption_accepted: Option<bool>,
pub issuer_id: Option<String>,
pub issuer_country: Option<String>,
pub merchant_country_code: Option<String>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub billing_country: Option<String>,
pub shipping_country: Option<String>,
}
#[derive(Debug)]
pub enum AuthenticationUpdate {
PreAuthenticationVersionCallUpdate {
maximum_supported_3ds_version: common_utils::types::SemanticVersion,
message_version: common_utils::types::SemanticVersion,
},
PreAuthenticationThreeDsMethodCall {
threeds_server_transaction_id: String,
three_ds_method_data: Option<String>,
three_ds_method_url: Option<String>,
acquirer_bin: Option<String>,
acquirer_merchant_id: Option<String>,
connector_metadata: Option<serde_json::Value>,
},
PreAuthenticationUpdate {
threeds_server_transaction_id: String,
maximum_supported_3ds_version: common_utils::types::SemanticVersion,
connector_authentication_id: String,
three_ds_method_data: Option<String>,
three_ds_method_url: Option<String>,
message_version: common_utils::types::SemanticVersion,
connector_metadata: Option<serde_json::Value>,
authentication_status: common_enums::AuthenticationStatus,
acquirer_bin: Option<String>,
acquirer_merchant_id: Option<String>,
directory_server_id: Option<String>,
acquirer_country_code: Option<String>,
billing_address: Option<Encryption>,
shipping_address: Option<Encryption>,
browser_info: Box<Option<serde_json::Value>>,
email: Option<Encryption>,
scheme_id: Option<String>,
merchant_category_code: Option<common_enums::MerchantCategoryCode>,
merchant_country_code: Option<String>,
billing_country: Option<String>,
shipping_country: Option<String>,
earliest_supported_version: Option<common_utils::types::SemanticVersion>,
latest_supported_version: Option<common_utils::types::SemanticVersion>,
},
AuthenticationUpdate {
trans_status: common_enums::TransactionStatus,
authentication_type: common_enums::DecoupledAuthenticationType,
acs_url: Option<String>,
challenge_request: Option<String>,
acs_reference_number: Option<String>,
acs_trans_id: Option<String>,
acs_signed_content: Option<String>,
connector_metadata: Option<serde_json::Value>,
authentication_status: common_enums::AuthenticationStatus,
ds_trans_id: Option<String>,
eci: Option<String>,
challenge_code: Option<String>,
challenge_cancel: Option<String>,
challenge_code_reason: Option<String>,
message_extension: Option<pii::SecretSerdeValue>,
challenge_request_key: Option<String>,
device_type: Option<String>,
device_brand: Option<String>,
device_os: Option<String>,
device_display: Option<String>,
},
PostAuthenticationUpdate {
trans_status: common_enums::TransactionStatus,
eci: Option<String>,
authentication_status: common_enums::AuthenticationStatus,
challenge_cancel: Option<String>,
challenge_code_reason: Option<String>,
},
ErrorUpdate {
error_message: Option<String>,
error_code: Option<String>,
authentication_status: common_enums::AuthenticationStatus,
connector_authentication_id: Option<String>,
},
PostAuthorizationUpdate {
authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus,
},
AuthenticationStatusUpdate {
trans_status: common_enums::TransactionStatus,
authentication_status: common_enums::AuthenticationStatus,
},
}
impl Default for AuthenticationUpdateInternal {
fn default() -> Self {
Self {
connector_authentication_id: Default::default(),
payment_method_id: Default::default(),
authentication_type: Default::default(),
authentication_status: Default::default(),
authentication_lifecycle_status: Default::default(),
modified_at: common_utils::date_time::now(),
error_message: Default::default(),
error_code: Default::default(),
connector_metadata: Default::default(),
maximum_supported_version: Default::default(),
threeds_server_transaction_id: Default::default(),
authentication_flow_type: Default::default(),
message_version: Default::default(),
eci: Default::default(),
trans_status: Default::default(),
acquirer_bin: Default::default(),
acquirer_merchant_id: Default::default(),
three_ds_method_data: Default::default(),
three_ds_method_url: Default::default(),
acs_url: Default::default(),
challenge_request: Default::default(),
acs_reference_number: Default::default(),
acs_trans_id: Default::default(),
acs_signed_content: Default::default(),
ds_trans_id: Default::default(),
directory_server_id: Default::default(),
acquirer_country_code: Default::default(),
service_details: Default::default(),
force_3ds_challenge: Default::default(),
psd2_sca_exemption_type: Default::default(),
billing_address: Default::default(),
shipping_address: Default::default(),
browser_info: Default::default(),
email: Default::default(),
profile_acquirer_id: Default::default(),
challenge_code: Default::default(),
challenge_cancel: Default::default(),
challenge_code_reason: Default::default(),
message_extension: Default::default(),
challenge_request_key: Default::default(),
customer_details: Default::default(),
earliest_supported_version: Default::default(),
latest_supported_version: Default::default(),
mcc: Default::default(),
platform: Default::default(),
device_type: Default::default(),
device_brand: Default::default(),
device_os: Default::default(),
device_display: Default::default(),
browser_name: Default::default(),
browser_version: Default::default(),
scheme_name: Default::default(),
exemption_requested: Default::default(),
exemption_accepted: Default::default(),
issuer_id: Default::default(),
issuer_country: Default::default(),
merchant_country_code: Default::default(),
billing_country: Default::default(),
shipping_country: Default::default(),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, AsChangeset, Serialize, Deserialize)]
#[diesel(table_name = authentication)]
pub struct AuthenticationUpdateInternal {
pub connector_authentication_id: Option<String>,
// pub authentication_data: Option<serde_json::Value>,
pub payment_method_id: Option<String>,
pub authentication_type: Option<common_enums::DecoupledAuthenticationType>,
pub authentication_status: Option<common_enums::AuthenticationStatus>,
pub authentication_lifecycle_status: Option<common_enums::AuthenticationLifecycleStatus>,
pub modified_at: time::PrimitiveDateTime,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub connector_metadata: Option<serde_json::Value>,
pub maximum_supported_version: Option<common_utils::types::SemanticVersion>,
pub threeds_server_transaction_id: Option<String>,
pub authentication_flow_type: Option<String>,
pub message_version: Option<common_utils::types::SemanticVersion>,
pub eci: Option<String>,
pub trans_status: Option<common_enums::TransactionStatus>,
pub acquirer_bin: Option<String>,
pub acquirer_merchant_id: Option<String>,
pub three_ds_method_data: Option<String>,
pub three_ds_method_url: Option<String>,
pub acs_url: Option<String>,
pub challenge_request: Option<String>,
pub acs_reference_number: Option<String>,
pub acs_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
pub ds_trans_id: Option<String>,
pub directory_server_id: Option<String>,
pub acquirer_country_code: Option<String>,
pub service_details: Option<serde_json::Value>,
pub force_3ds_challenge: Option<bool>,
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
pub billing_address: Option<Encryption>,
pub shipping_address: Option<Encryption>,
pub browser_info: Option<serde_json::Value>,
pub email: Option<Encryption>,
pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,
pub challenge_code: Option<String>,
pub challenge_cancel: Option<String>,
pub challenge_code_reason: Option<String>,
pub message_extension: Option<pii::SecretSerdeValue>,
pub challenge_request_key: Option<String>,
pub customer_details: Option<Encryption>,
pub earliest_supported_version: Option<common_utils::types::SemanticVersion>,
pub latest_supported_version: Option<common_utils::types::SemanticVersion>,
pub mcc: Option<common_enums::MerchantCategoryCode>,
pub platform: Option<String>,
pub device_type: Option<String>,
pub device_brand: Option<String>,
pub device_os: Option<String>,
pub device_display: Option<String>,
pub browser_name: Option<String>,
pub browser_version: Option<String>,
pub scheme_name: Option<String>,
pub exemption_requested: Option<bool>,
pub exemption_accepted: Option<bool>,
pub issuer_id: Option<String>,
pub issuer_country: Option<String>,
pub merchant_country_code: Option<String>,
pub billing_country: Option<String>,
pub shipping_country: Option<String>,
}
impl AuthenticationUpdateInternal {
pub fn apply_changeset(self, source: AuthenticationNew) -> Authentication {
let Self {
connector_authentication_id,
payment_method_id,
authentication_type,
authentication_status,
authentication_lifecycle_status,
modified_at: _,
error_code,
error_message,
connector_metadata,
maximum_supported_version,
threeds_server_transaction_id,
authentication_flow_type,
message_version,
eci,
trans_status,
acquirer_bin,
acquirer_merchant_id,
three_ds_method_data,
three_ds_method_url,
acs_url,
challenge_request,
acs_reference_number,
acs_trans_id,
acs_signed_content,
ds_trans_id,
directory_server_id,
acquirer_country_code,
service_details,
force_3ds_challenge,
psd2_sca_exemption_type,
billing_address,
shipping_address,
browser_info,
email,
profile_acquirer_id,
challenge_code,
challenge_cancel,
challenge_code_reason,
message_extension,
challenge_request_key,
customer_details,
earliest_supported_version,
latest_supported_version,
mcc,
platform,
device_type,
device_brand,
device_os,
device_display,
browser_name,
browser_version,
scheme_name,
exemption_requested,
exemption_accepted,
issuer_id,
issuer_country,
merchant_country_code,
billing_country,
shipping_country,
} = self;
Authentication {
connector_authentication_id: connector_authentication_id
.or(source.connector_authentication_id),
payment_method_id: payment_method_id.unwrap_or(source.payment_method_id),
authentication_type: authentication_type.or(source.authentication_type),
authentication_status: authentication_status.unwrap_or(source.authentication_status),
authentication_lifecycle_status: authentication_lifecycle_status
.unwrap_or(source.authentication_lifecycle_status),
modified_at: common_utils::date_time::now(),
error_code: error_code.or(source.error_code),
error_message: error_message.or(source.error_message),
connector_metadata: connector_metadata.or(source.connector_metadata),
maximum_supported_version: maximum_supported_version
.or(source.maximum_supported_version),
threeds_server_transaction_id: threeds_server_transaction_id
.or(source.threeds_server_transaction_id),
authentication_flow_type: authentication_flow_type.or(source.authentication_flow_type),
message_version: message_version.or(source.message_version),
eci: eci.or(source.eci),
trans_status: trans_status.or(source.trans_status),
acquirer_bin: acquirer_bin.or(source.acquirer_bin),
acquirer_merchant_id: acquirer_merchant_id.or(source.acquirer_merchant_id),
three_ds_method_data: three_ds_method_data.or(source.three_ds_method_data),
three_ds_method_url: three_ds_method_url.or(source.three_ds_method_url),
acs_url: acs_url.or(source.acs_url),
challenge_request: challenge_request.or(source.challenge_request),
acs_reference_number: acs_reference_number.or(source.acs_reference_number),
acs_trans_id: acs_trans_id.or(source.acs_trans_id),
acs_signed_content: acs_signed_content.or(source.acs_signed_content),
ds_trans_id: ds_trans_id.or(source.ds_trans_id),
directory_server_id: directory_server_id.or(source.directory_server_id),
acquirer_country_code: acquirer_country_code.or(source.acquirer_country_code),
service_details: service_details.or(source.service_details),
force_3ds_challenge: force_3ds_challenge.or(source.force_3ds_challenge),
psd2_sca_exemption_type: psd2_sca_exemption_type.or(source.psd2_sca_exemption_type),
billing_address: billing_address.or(source.billing_address),
shipping_address: shipping_address.or(source.shipping_address),
browser_info: browser_info.or(source.browser_info),
email: email.or(source.email),
profile_acquirer_id: profile_acquirer_id.or(source.profile_acquirer_id),
challenge_code: challenge_code.or(source.challenge_code),
challenge_cancel: challenge_cancel.or(source.challenge_cancel),
challenge_code_reason: challenge_code_reason.or(source.challenge_code_reason),
message_extension: message_extension.or(source.message_extension),
challenge_request_key: challenge_request_key.or(source.challenge_request_key),
customer_details: customer_details.or(source.customer_details),
earliest_supported_version: earliest_supported_version
.or(source.earliest_supported_version),
latest_supported_version: latest_supported_version.or(source.latest_supported_version),
mcc: mcc.or(source.mcc),
platform: platform.or(source.platform),
device_type: device_type.or(source.device_type),
device_brand: device_brand.or(source.device_brand),
device_os: device_os.or(source.device_os),
device_display: device_display.or(source.device_display),
browser_name: browser_name.or(source.browser_name),
browser_version: browser_version.or(source.browser_version),
scheme_name: scheme_name.or(source.scheme_name),
exemption_requested: exemption_requested.or(source.exemption_requested),
exemption_accepted: exemption_accepted.or(source.exemption_accepted),
issuer_id: issuer_id.or(source.issuer_id),
issuer_country: issuer_country.or(source.issuer_country),
merchant_country_code: merchant_country_code.or(source.merchant_country_code),
authentication_id: source.authentication_id,
merchant_id: source.merchant_id,
authentication_connector: source.authentication_connector,
authentication_data: source.authentication_data,
created_at: source.created_at,
cavv: source.cavv,
profile_id: source.profile_id,
payment_id: source.payment_id,
merchant_connector_id: source.merchant_connector_id,
organization_id: source.organization_id,
authentication_client_secret: source.authentication_client_secret,
return_url: source.return_url,
amount: source.amount,
currency: source.currency,
billing_country: billing_country.or(source.billing_country),
shipping_country: shipping_country.or(source.shipping_country),
}
}
}
impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {
fn from(auth_update: AuthenticationUpdate) -> Self {
match auth_update {
AuthenticationUpdate::ErrorUpdate {
error_message,
error_code,
authentication_status,
connector_authentication_id,
} => Self {
error_code,
error_message,
authentication_status: Some(authentication_status),
connector_authentication_id,
authentication_type: None,
authentication_lifecycle_status: None,
modified_at: common_utils::date_time::now(),
payment_method_id: None,
connector_metadata: None,
..Default::default()
},
AuthenticationUpdate::PostAuthorizationUpdate {
authentication_lifecycle_status,
} => Self {
connector_authentication_id: None,
payment_method_id: None,
authentication_type: None,
authentication_status: None,
authentication_lifecycle_status: Some(authentication_lifecycle_status),
modified_at: common_utils::date_time::now(),
error_message: None,
error_code: None,
connector_metadata: None,
..Default::default()
},
AuthenticationUpdate::PreAuthenticationUpdate {
threeds_server_transaction_id,
maximum_supported_3ds_version,
connector_authentication_id,
three_ds_method_data,
three_ds_method_url,
message_version,
connector_metadata,
authentication_status,
acquirer_bin,
acquirer_merchant_id,
directory_server_id,
acquirer_country_code,
billing_address,
shipping_address,
browser_info,
email,
scheme_id,
merchant_category_code,
merchant_country_code,
billing_country,
shipping_country,
earliest_supported_version,
latest_supported_version,
} => Self {
threeds_server_transaction_id: Some(threeds_server_transaction_id),
maximum_supported_version: Some(maximum_supported_3ds_version),
connector_authentication_id: Some(connector_authentication_id),
three_ds_method_data,
three_ds_method_url,
message_version: Some(message_version),
connector_metadata,
authentication_status: Some(authentication_status),
acquirer_bin,
acquirer_merchant_id,
directory_server_id,
acquirer_country_code,
billing_address,
shipping_address,
browser_info: *browser_info,
email,
scheme_name: scheme_id,
mcc: merchant_category_code,
merchant_country_code,
billing_country,
shipping_country,
earliest_supported_version,
latest_supported_version,
..Default::default()
},
AuthenticationUpdate::AuthenticationUpdate {
trans_status,
authentication_type,
acs_url,
challenge_request,
acs_reference_number,
acs_trans_id,
acs_signed_content,
connector_metadata,
authentication_status,
ds_trans_id,
eci,
challenge_code,
challenge_cancel,
challenge_code_reason,
message_extension,
challenge_request_key,
device_type,
device_brand,
device_os,
device_display,
} => Self {
trans_status: Some(trans_status),
authentication_type: Some(authentication_type),
acs_url,
challenge_request,
acs_reference_number,
acs_trans_id,
acs_signed_content,
connector_metadata,
authentication_status: Some(authentication_status),
ds_trans_id,
eci,
challenge_code,
challenge_cancel,
challenge_code_reason,
message_extension,
challenge_request_key,
device_type,
device_brand,
device_os,
device_display,
..Default::default()
},
AuthenticationUpdate::PostAuthenticationUpdate {
trans_status,
eci,
authentication_status,
challenge_cancel,
challenge_code_reason,
} => Self {
trans_status: Some(trans_status),
eci,
authentication_status: Some(authentication_status),
challenge_cancel,
challenge_code_reason,
..Default::default()
},
AuthenticationUpdate::PreAuthenticationVersionCallUpdate {
maximum_supported_3ds_version,
message_version,
} => Self {
maximum_supported_version: Some(maximum_supported_3ds_version),
message_version: Some(message_version),
..Default::default()
},
AuthenticationUpdate::PreAuthenticationThreeDsMethodCall {
threeds_server_transaction_id,
three_ds_method_data,
three_ds_method_url,
acquirer_bin,
acquirer_merchant_id,
connector_metadata,
} => Self {
threeds_server_transaction_id: Some(threeds_server_transaction_id),
three_ds_method_data,
three_ds_method_url,
acquirer_bin,
acquirer_merchant_id,
connector_metadata,
..Default::default()
},
AuthenticationUpdate::AuthenticationStatusUpdate {
trans_status,
authentication_status,
} => Self {
trans_status: Some(trans_status),
authentication_status: Some(authentication_status),
..Default::default()
},
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/business_profile.rs | crates/diesel_models/src/business_profile.rs | use std::collections::{HashMap, HashSet};
use common_enums::{AuthenticationConnectors, UIWidgetFormLayout, VaultSdk};
use common_types::primitive_wrappers;
use common_utils::{encryption::Encryption, pii};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use masking::Secret;
use time::Duration;
#[cfg(feature = "v1")]
use crate::schema::business_profile;
#[cfg(feature = "v2")]
use crate::schema_v2::business_profile;
/// Note: The order of fields in the struct is important.
/// This should be in the same order as the fields in the schema.rs file, otherwise the code will
/// not compile
/// If two adjacent columns have the same type, then the compiler will not throw any error, but the
/// fields read / written will be interchanged
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay)]
#[diesel(table_name = business_profile, primary_key(profile_id), check_for_backend(diesel::pg::Pg))]
pub struct Profile {
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub intent_fulfillment_time: Option<i64>,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub is_recon_enabled: bool,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
pub version: common_enums::ApiVersion,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
pub always_request_extended_authorization:
Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>,
pub is_click_to_pay_enabled: bool,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: Option<Encryption>,
pub is_clear_pan_retries_enabled: bool,
pub force_3ds_challenge: Option<bool>,
pub is_debit_routing_enabled: bool,
pub merchant_business_country: Option<common_enums::CountryAlpha2>,
pub id: Option<common_utils::id_type::ProfileId>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_pre_network_tokenization_enabled: Option<bool>,
pub three_ds_decision_rule_algorithm: Option<serde_json::Value>,
pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>,
pub merchant_category_code: Option<common_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
pub is_manual_retry_enabled: Option<bool>,
pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_external_vault_enabled: Option<bool>,
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
pub is_l2_l3_enabled: Option<bool>,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = business_profile, primary_key(profile_id))]
pub struct ProfileNew {
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub intent_fulfillment_time: Option<i64>,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub is_recon_enabled: bool,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
pub version: common_enums::ApiVersion,
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
pub is_click_to_pay_enabled: bool,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: Option<Encryption>,
pub is_clear_pan_retries_enabled: bool,
pub force_3ds_challenge: Option<bool>,
pub is_debit_routing_enabled: bool,
pub merchant_business_country: Option<common_enums::CountryAlpha2>,
pub id: Option<common_utils::id_type::ProfileId>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_pre_network_tokenization_enabled: Option<bool>,
pub merchant_category_code: Option<common_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
pub is_manual_retry_enabled: Option<bool>,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_external_vault_enabled: Option<bool>,
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
pub is_l2_l3_enabled: Option<bool>,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = business_profile)]
pub struct ProfileUpdateInternal {
pub profile_name: Option<String>,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<String>,
pub enable_payment_response_hash: Option<bool>,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: Option<bool>,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub intent_fulfillment_time: Option<i64>,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub is_recon_enabled: Option<bool>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
pub is_l2_l3_enabled: Option<bool>,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: Option<bool>,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
pub always_request_extended_authorization:
Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>,
pub is_click_to_pay_enabled: Option<bool>,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: Option<Encryption>,
pub is_clear_pan_retries_enabled: Option<bool>,
pub force_3ds_challenge: Option<bool>,
pub is_debit_routing_enabled: Option<bool>,
pub merchant_business_country: Option<common_enums::CountryAlpha2>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_pre_network_tokenization_enabled: Option<bool>,
pub three_ds_decision_rule_algorithm: Option<serde_json::Value>,
pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>,
pub merchant_category_code: Option<common_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
pub is_manual_retry_enabled: Option<bool>,
pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_external_vault_enabled: Option<bool>,
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
}
#[cfg(feature = "v1")]
impl ProfileUpdateInternal {
pub fn apply_changeset(self, source: Profile) -> Profile {
let Self {
profile_name,
modified_at,
return_url,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
webhook_details,
metadata,
routing_algorithm,
intent_fulfillment_time,
frm_routing_algorithm,
payout_routing_algorithm,
is_recon_enabled,
applepay_verified_domains,
payment_link_config,
session_expiry,
authentication_connector_details,
payout_link_config,
is_extended_card_info_enabled,
extended_card_info_config,
is_connector_agnostic_mit_enabled,
use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers,
always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector,
tax_connector_id,
is_tax_connector_enabled,
is_l2_l3_enabled,
dynamic_routing_algorithm,
is_network_tokenization_enabled,
is_auto_retries_enabled,
max_auto_retries_enabled,
always_request_extended_authorization,
is_click_to_pay_enabled,
authentication_product_ids,
card_testing_guard_config,
card_testing_secret_key,
is_clear_pan_retries_enabled,
force_3ds_challenge,
is_debit_routing_enabled,
merchant_business_country,
is_iframe_redirection_enabled,
is_pre_network_tokenization_enabled,
three_ds_decision_rule_algorithm,
acquirer_config_map,
merchant_category_code,
merchant_country_code,
dispute_polling_interval,
is_manual_retry_enabled,
always_enable_overcapture,
is_external_vault_enabled,
external_vault_connector_details,
billing_processor_id,
} = self;
Profile {
profile_id: source.profile_id,
merchant_id: source.merchant_id,
profile_name: profile_name.unwrap_or(source.profile_name),
created_at: source.created_at,
modified_at,
return_url: return_url.or(source.return_url),
enable_payment_response_hash: enable_payment_response_hash
.unwrap_or(source.enable_payment_response_hash),
payment_response_hash_key: payment_response_hash_key
.or(source.payment_response_hash_key),
redirect_to_merchant_with_http_post: redirect_to_merchant_with_http_post
.unwrap_or(source.redirect_to_merchant_with_http_post),
webhook_details: webhook_details.or(source.webhook_details),
metadata: metadata.or(source.metadata),
routing_algorithm: routing_algorithm.or(source.routing_algorithm),
intent_fulfillment_time: intent_fulfillment_time.or(source.intent_fulfillment_time),
frm_routing_algorithm: frm_routing_algorithm.or(source.frm_routing_algorithm),
payout_routing_algorithm: payout_routing_algorithm.or(source.payout_routing_algorithm),
is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled),
applepay_verified_domains: applepay_verified_domains
.or(source.applepay_verified_domains),
payment_link_config: payment_link_config.or(source.payment_link_config),
session_expiry: session_expiry.or(source.session_expiry),
authentication_connector_details: authentication_connector_details
.or(source.authentication_connector_details),
payout_link_config: payout_link_config.or(source.payout_link_config),
is_extended_card_info_enabled: is_extended_card_info_enabled
.or(source.is_extended_card_info_enabled),
is_connector_agnostic_mit_enabled: is_connector_agnostic_mit_enabled
.or(source.is_connector_agnostic_mit_enabled),
extended_card_info_config: extended_card_info_config
.or(source.extended_card_info_config),
use_billing_as_payment_method_billing: use_billing_as_payment_method_billing
.or(source.use_billing_as_payment_method_billing),
collect_shipping_details_from_wallet_connector:
collect_shipping_details_from_wallet_connector
.or(source.collect_shipping_details_from_wallet_connector),
collect_billing_details_from_wallet_connector:
collect_billing_details_from_wallet_connector
.or(source.collect_billing_details_from_wallet_connector),
outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers
.or(source.outgoing_webhook_custom_http_headers),
always_collect_billing_details_from_wallet_connector:
always_collect_billing_details_from_wallet_connector
.or(source.always_collect_billing_details_from_wallet_connector),
always_collect_shipping_details_from_wallet_connector:
always_collect_shipping_details_from_wallet_connector
.or(source.always_collect_shipping_details_from_wallet_connector),
tax_connector_id: tax_connector_id.or(source.tax_connector_id),
is_tax_connector_enabled: is_tax_connector_enabled.or(source.is_tax_connector_enabled),
is_l2_l3_enabled: is_l2_l3_enabled.or(source.is_l2_l3_enabled),
version: source.version,
dynamic_routing_algorithm: dynamic_routing_algorithm
.or(source.dynamic_routing_algorithm),
is_network_tokenization_enabled: is_network_tokenization_enabled
.unwrap_or(source.is_network_tokenization_enabled),
is_auto_retries_enabled: is_auto_retries_enabled.or(source.is_auto_retries_enabled),
max_auto_retries_enabled: max_auto_retries_enabled.or(source.max_auto_retries_enabled),
always_request_extended_authorization: always_request_extended_authorization
.or(source.always_request_extended_authorization),
is_click_to_pay_enabled: is_click_to_pay_enabled
.unwrap_or(source.is_click_to_pay_enabled),
authentication_product_ids: authentication_product_ids
.or(source.authentication_product_ids),
card_testing_guard_config: card_testing_guard_config
.or(source.card_testing_guard_config),
card_testing_secret_key,
is_clear_pan_retries_enabled: is_clear_pan_retries_enabled
.unwrap_or(source.is_clear_pan_retries_enabled),
force_3ds_challenge,
id: source.id,
is_debit_routing_enabled: is_debit_routing_enabled
.unwrap_or(source.is_debit_routing_enabled),
merchant_business_country: merchant_business_country
.or(source.merchant_business_country),
is_iframe_redirection_enabled: is_iframe_redirection_enabled
.or(source.is_iframe_redirection_enabled),
is_pre_network_tokenization_enabled: is_pre_network_tokenization_enabled
.or(source.is_pre_network_tokenization_enabled),
three_ds_decision_rule_algorithm: three_ds_decision_rule_algorithm
.or(source.three_ds_decision_rule_algorithm),
acquirer_config_map: acquirer_config_map.or(source.acquirer_config_map),
merchant_category_code: merchant_category_code.or(source.merchant_category_code),
merchant_country_code: merchant_country_code.or(source.merchant_country_code),
dispute_polling_interval: dispute_polling_interval.or(source.dispute_polling_interval),
is_manual_retry_enabled: is_manual_retry_enabled.or(source.is_manual_retry_enabled),
always_enable_overcapture: always_enable_overcapture
.or(source.always_enable_overcapture),
is_external_vault_enabled: is_external_vault_enabled
.or(source.is_external_vault_enabled),
external_vault_connector_details: external_vault_connector_details
.or(source.external_vault_connector_details),
billing_processor_id: billing_processor_id.or(source.billing_processor_id),
}
}
}
/// Note: The order of fields in the struct is important.
/// This should be in the same order as the fields in the schema.rs file, otherwise the code will
/// not compile
/// If two adjacent columns have the same type, then the compiler will not throw any error, but the
/// fields read / written will be interchanged
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay)]
#[diesel(table_name = business_profile, primary_key(id), check_for_backend(diesel::pg::Pg))]
pub struct Profile {
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<common_utils::types::Url>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub is_recon_enabled: bool,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
pub version: common_enums::ApiVersion,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
pub always_request_extended_authorization:
Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>,
pub is_click_to_pay_enabled: bool,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: Option<Encryption>,
pub is_clear_pan_retries_enabled: bool,
pub force_3ds_challenge: Option<bool>,
pub is_debit_routing_enabled: bool,
pub merchant_business_country: Option<common_enums::CountryAlpha2>,
pub id: common_utils::id_type::ProfileId,
pub is_iframe_redirection_enabled: Option<bool>,
pub three_ds_decision_rule_algorithm: Option<serde_json::Value>,
pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>,
pub merchant_category_code: Option<common_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
pub is_manual_retry_enabled: Option<bool>,
pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_external_vault_enabled: Option<bool>,
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
pub is_l2_l3_enabled: Option<bool>,
pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub default_fallback_routing: Option<pii::SecretSerdeValue>,
pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>,
pub should_collect_cvv_during_payment:
Option<primitive_wrappers::ShouldCollectCvvDuringPayment>,
pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>,
pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>,
pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>,
}
impl Profile {
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &common_utils::id_type::ProfileId {
&self.profile_id
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &common_utils::id_type::ProfileId {
&self.id
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = business_profile, primary_key(profile_id))]
pub struct ProfileNew {
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<common_utils::types::Url>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub is_recon_enabled: bool,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
pub version: common_enums::ApiVersion,
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
pub is_click_to_pay_enabled: bool,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: Option<Encryption>,
pub is_clear_pan_retries_enabled: Option<bool>,
pub is_debit_routing_enabled: bool,
pub merchant_business_country: Option<common_enums::CountryAlpha2>,
pub merchant_category_code: Option<common_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub default_fallback_routing: Option<pii::SecretSerdeValue>,
pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>,
pub should_collect_cvv_during_payment:
Option<primitive_wrappers::ShouldCollectCvvDuringPayment>,
pub id: common_utils::id_type::ProfileId,
pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>,
pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_external_vault_enabled: Option<bool>,
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
pub is_l2_l3_enabled: Option<bool>,
pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = business_profile)]
pub struct ProfileUpdateInternal {
pub profile_name: Option<String>,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<common_utils::types::Url>,
pub enable_payment_response_hash: Option<bool>,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: Option<bool>,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub is_recon_enabled: Option<bool>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
pub is_network_tokenization_enabled: Option<bool>,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
pub is_click_to_pay_enabled: Option<bool>,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: Option<Encryption>,
pub is_clear_pan_retries_enabled: Option<bool>,
pub is_debit_routing_enabled: Option<bool>,
pub merchant_business_country: Option<common_enums::CountryAlpha2>,
pub merchant_category_code: Option<common_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub default_fallback_routing: Option<pii::SecretSerdeValue>,
pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>,
pub should_collect_cvv_during_payment:
Option<primitive_wrappers::ShouldCollectCvvDuringPayment>,
pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>,
pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_external_vault_enabled: Option<bool>,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query.rs | crates/diesel_models/src/query.rs | pub mod address;
pub mod api_keys;
pub mod blocklist_lookup;
pub mod business_profile;
mod capture;
pub mod cards_info;
pub mod configs;
pub mod authentication;
pub mod authorization;
pub mod blocklist;
pub mod blocklist_fingerprint;
pub mod callback_mapper;
pub mod customers;
pub mod dashboard_metadata;
pub mod dispute;
pub mod dynamic_routing_stats;
pub mod events;
pub mod file;
pub mod fraud_check;
pub mod generic_link;
pub mod generics;
pub mod gsm;
pub mod hyperswitch_ai_interaction;
pub mod invoice;
pub mod locker_mock_up;
pub mod mandate;
pub mod merchant_account;
pub mod merchant_connector_account;
pub mod merchant_key_store;
pub mod organization;
pub mod payment_attempt;
pub mod payment_intent;
pub mod payment_link;
pub mod payment_method;
pub mod payout_attempt;
pub mod payouts;
pub mod process_tracker;
pub mod refund;
pub mod relay;
pub mod reverse_lookup;
pub mod role;
pub mod routing_algorithm;
pub mod subscription;
#[cfg(feature = "tokenization_v2")]
pub mod tokenization;
pub mod unified_translations;
pub mod user;
pub mod user_authentication_method;
pub mod user_key_store;
pub mod user_role;
mod utils;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/mandate.rs | crates/diesel_models/src/mandate.rs | use common_enums::MerchantStorageScheme;
use common_utils::pii;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use masking::Secret;
use time::PrimitiveDateTime;
use crate::{enums as storage_enums, schema::mandate};
#[derive(
Clone, Debug, Identifiable, Queryable, Selectable, serde::Serialize, serde::Deserialize,
)]
#[diesel(table_name = mandate, primary_key(mandate_id), check_for_backend(diesel::pg::Pg))]
pub struct Mandate {
pub mandate_id: String,
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_method_id: String,
pub mandate_status: storage_enums::MandateStatus,
pub mandate_type: storage_enums::MandateType,
pub customer_accepted_at: Option<PrimitiveDateTime>,
pub customer_ip_address: Option<Secret<String, pii::IpAddress>>,
pub customer_user_agent: Option<String>,
pub network_transaction_id: Option<String>,
pub previous_attempt_id: Option<String>,
pub created_at: PrimitiveDateTime,
pub mandate_amount: Option<i64>,
pub mandate_currency: Option<storage_enums::Currency>,
pub amount_captured: Option<i64>,
pub connector: String,
pub connector_mandate_id: Option<String>,
pub start_date: Option<PrimitiveDateTime>,
pub end_date: Option<PrimitiveDateTime>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_mandate_ids: Option<pii::SecretSerdeValue>,
pub original_payment_id: Option<common_utils::id_type::PaymentId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub updated_by: Option<String>,
// This is the extended version of customer user agent that can store string upto 2048 characters unlike customer user agent that can store 255 characters at max
pub customer_user_agent_extended: Option<String>,
}
#[derive(
router_derive::Setter,
Clone,
Debug,
Default,
Insertable,
router_derive::DebugAsDisplay,
serde::Serialize,
serde::Deserialize,
)]
#[diesel(table_name = mandate)]
pub struct MandateNew {
pub mandate_id: String,
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_method_id: String,
pub mandate_status: storage_enums::MandateStatus,
pub mandate_type: storage_enums::MandateType,
pub customer_accepted_at: Option<PrimitiveDateTime>,
pub customer_ip_address: Option<Secret<String, pii::IpAddress>>,
pub customer_user_agent: Option<String>,
pub network_transaction_id: Option<String>,
pub previous_attempt_id: Option<String>,
pub created_at: Option<PrimitiveDateTime>,
pub mandate_amount: Option<i64>,
pub mandate_currency: Option<storage_enums::Currency>,
pub amount_captured: Option<i64>,
pub connector: String,
pub connector_mandate_id: Option<String>,
pub start_date: Option<PrimitiveDateTime>,
pub end_date: Option<PrimitiveDateTime>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_mandate_ids: Option<pii::SecretSerdeValue>,
pub original_payment_id: Option<common_utils::id_type::PaymentId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub updated_by: Option<String>,
pub customer_user_agent_extended: Option<String>,
}
impl Mandate {
/// Returns customer_user_agent_extended with customer_user_agent as fallback
pub fn get_user_agent_extended(&self) -> Option<String> {
self.customer_user_agent_extended
.clone()
.or_else(|| self.customer_user_agent.clone())
}
}
impl MandateNew {
pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) {
self.updated_by = Some(storage_scheme.to_string());
}
/// Returns customer_user_agent_extended with customer_user_agent as fallback
pub fn get_customer_user_agent_extended(&self) -> Option<String> {
self.customer_user_agent_extended
.clone()
.or_else(|| self.customer_user_agent.clone())
}
}
#[derive(Debug)]
pub enum MandateUpdate {
StatusUpdate {
mandate_status: storage_enums::MandateStatus,
},
CaptureAmountUpdate {
amount_captured: Option<i64>,
},
ConnectorReferenceUpdate {
connector_mandate_ids: Option<pii::SecretSerdeValue>,
},
ConnectorMandateIdUpdate {
connector_mandate_id: Option<String>,
connector_mandate_ids: Option<pii::SecretSerdeValue>,
payment_method_id: String,
original_payment_id: Option<common_utils::id_type::PaymentId>,
},
}
impl MandateUpdate {
pub fn convert_to_mandate_update(
self,
storage_scheme: MerchantStorageScheme,
) -> MandateUpdateInternal {
let mut updated_object = MandateUpdateInternal::from(self);
updated_object.updated_by = Some(storage_scheme.to_string());
updated_object
}
}
#[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct SingleUseMandate {
pub amount: i64,
pub currency: storage_enums::Currency,
}
#[derive(
Clone,
Debug,
Default,
AsChangeset,
router_derive::DebugAsDisplay,
serde::Serialize,
serde::Deserialize,
)]
#[diesel(table_name = mandate)]
pub struct MandateUpdateInternal {
mandate_status: Option<storage_enums::MandateStatus>,
amount_captured: Option<i64>,
connector_mandate_ids: Option<pii::SecretSerdeValue>,
connector_mandate_id: Option<String>,
payment_method_id: Option<String>,
original_payment_id: Option<common_utils::id_type::PaymentId>,
updated_by: Option<String>,
}
impl From<MandateUpdate> for MandateUpdateInternal {
fn from(mandate_update: MandateUpdate) -> Self {
match mandate_update {
MandateUpdate::StatusUpdate { mandate_status } => Self {
mandate_status: Some(mandate_status),
connector_mandate_ids: None,
amount_captured: None,
connector_mandate_id: None,
payment_method_id: None,
original_payment_id: None,
updated_by: None,
},
MandateUpdate::CaptureAmountUpdate { amount_captured } => Self {
mandate_status: None,
amount_captured,
connector_mandate_ids: None,
connector_mandate_id: None,
payment_method_id: None,
original_payment_id: None,
updated_by: None,
},
MandateUpdate::ConnectorReferenceUpdate {
connector_mandate_ids,
} => Self {
connector_mandate_ids,
..Default::default()
},
MandateUpdate::ConnectorMandateIdUpdate {
connector_mandate_id,
connector_mandate_ids,
payment_method_id,
original_payment_id,
} => Self {
connector_mandate_id,
connector_mandate_ids,
payment_method_id: Some(payment_method_id),
original_payment_id,
..Default::default()
},
}
}
}
impl MandateUpdateInternal {
pub fn apply_changeset(self, source: Mandate) -> Mandate {
let Self {
mandate_status,
amount_captured,
connector_mandate_ids,
connector_mandate_id,
payment_method_id,
original_payment_id,
updated_by,
} = self;
Mandate {
mandate_status: mandate_status.unwrap_or(source.mandate_status),
amount_captured: amount_captured.map_or(source.amount_captured, Some),
connector_mandate_ids: connector_mandate_ids.map_or(source.connector_mandate_ids, Some),
connector_mandate_id: connector_mandate_id.map_or(source.connector_mandate_id, Some),
payment_method_id: payment_method_id.unwrap_or(source.payment_method_id),
original_payment_id: original_payment_id.map_or(source.original_payment_id, Some),
updated_by: updated_by.map_or(source.updated_by, Some),
..source
}
}
}
impl From<&MandateNew> for Mandate {
fn from(mandate_new: &MandateNew) -> Self {
Self {
mandate_id: mandate_new.mandate_id.clone(),
customer_id: mandate_new.customer_id.clone(),
merchant_id: mandate_new.merchant_id.clone(),
payment_method_id: mandate_new.payment_method_id.clone(),
mandate_status: mandate_new.mandate_status,
mandate_type: mandate_new.mandate_type,
customer_accepted_at: mandate_new.customer_accepted_at,
customer_ip_address: mandate_new.customer_ip_address.clone(),
customer_user_agent: None,
network_transaction_id: mandate_new.network_transaction_id.clone(),
previous_attempt_id: mandate_new.previous_attempt_id.clone(),
created_at: mandate_new
.created_at
.unwrap_or_else(common_utils::date_time::now),
mandate_amount: mandate_new.mandate_amount,
mandate_currency: mandate_new.mandate_currency,
amount_captured: mandate_new.amount_captured,
connector: mandate_new.connector.clone(),
connector_mandate_id: mandate_new.connector_mandate_id.clone(),
start_date: mandate_new.start_date,
end_date: mandate_new.end_date,
metadata: mandate_new.metadata.clone(),
connector_mandate_ids: mandate_new.connector_mandate_ids.clone(),
original_payment_id: mandate_new.original_payment_id.clone(),
merchant_connector_id: mandate_new.merchant_connector_id.clone(),
updated_by: mandate_new.updated_by.clone(),
// Using customer_user_agent as a fallback
customer_user_agent_extended: mandate_new.get_customer_user_agent_extended(),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/role.rs | crates/diesel_models/src/role.rs | use common_utils::id_type;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;
use crate::{enums, schema::roles};
#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]
#[diesel(table_name = roles, primary_key(role_id), check_for_backend(diesel::pg::Pg))]
pub struct Role {
pub role_name: String,
pub role_id: String,
pub merchant_id: Option<id_type::MerchantId>,
pub org_id: id_type::OrganizationId,
#[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)]
pub groups: Vec<enums::PermissionGroup>,
pub scope: enums::RoleScope,
pub created_at: PrimitiveDateTime,
pub created_by: String,
pub last_modified_at: PrimitiveDateTime,
pub last_modified_by: String,
pub entity_type: enums::EntityType,
pub profile_id: Option<id_type::ProfileId>,
pub tenant_id: id_type::TenantId,
}
#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = roles)]
pub struct RoleNew {
pub role_name: String,
pub role_id: String,
pub merchant_id: Option<id_type::MerchantId>,
pub org_id: id_type::OrganizationId,
#[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)]
pub groups: Vec<enums::PermissionGroup>,
pub scope: enums::RoleScope,
pub created_at: PrimitiveDateTime,
pub created_by: String,
pub last_modified_at: PrimitiveDateTime,
pub last_modified_by: String,
pub entity_type: enums::EntityType,
pub profile_id: Option<id_type::ProfileId>,
pub tenant_id: id_type::TenantId,
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = roles)]
pub struct RoleUpdateInternal {
groups: Option<Vec<enums::PermissionGroup>>,
role_name: Option<String>,
last_modified_by: String,
last_modified_at: PrimitiveDateTime,
}
pub enum RoleUpdate {
UpdateDetails {
groups: Option<Vec<enums::PermissionGroup>>,
role_name: Option<String>,
last_modified_at: PrimitiveDateTime,
last_modified_by: String,
},
}
impl From<RoleUpdate> for RoleUpdateInternal {
fn from(value: RoleUpdate) -> Self {
match value {
RoleUpdate::UpdateDetails {
groups,
role_name,
last_modified_by,
last_modified_at,
} => Self {
groups,
role_name,
last_modified_at,
last_modified_by,
},
}
}
}
#[derive(Clone, Debug)]
pub enum ListRolesByEntityPayload {
Profile(id_type::MerchantId, id_type::ProfileId),
Merchant(id_type::MerchantId),
Organization,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/events.rs | crates/diesel_models/src/events.rs | use common_utils::{custom_serde, encryption::Encryption};
use diesel::{
expression::AsExpression, AsChangeset, Identifiable, Insertable, Queryable, Selectable,
};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{enums as storage_enums, schema::events};
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = events)]
pub struct EventNew {
pub event_id: String,
pub event_type: storage_enums::EventType,
pub event_class: storage_enums::EventClass,
pub is_webhook_notified: bool,
pub primary_object_id: String,
pub primary_object_type: storage_enums::EventObjectType,
pub created_at: PrimitiveDateTime,
pub merchant_id: Option<common_utils::id_type::MerchantId>,
pub business_profile_id: Option<common_utils::id_type::ProfileId>,
pub primary_object_created_at: Option<PrimitiveDateTime>,
pub idempotent_event_id: Option<String>,
pub initial_attempt_id: Option<String>,
pub request: Option<Encryption>,
pub response: Option<Encryption>,
pub delivery_attempt: Option<storage_enums::WebhookDeliveryAttempt>,
pub metadata: Option<EventMetadata>,
pub is_overall_delivery_successful: Option<bool>,
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = events)]
pub struct EventUpdateInternal {
pub is_webhook_notified: Option<bool>,
pub response: Option<Encryption>,
pub is_overall_delivery_successful: Option<bool>,
}
#[derive(Clone, Debug, Deserialize, Serialize, Identifiable, Queryable, Selectable)]
#[diesel(table_name = events, primary_key(event_id), check_for_backend(diesel::pg::Pg))]
pub struct Event {
pub event_id: String,
pub event_type: storage_enums::EventType,
pub event_class: storage_enums::EventClass,
pub is_webhook_notified: bool,
pub primary_object_id: String,
pub primary_object_type: storage_enums::EventObjectType,
#[serde(with = "custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
pub merchant_id: Option<common_utils::id_type::MerchantId>,
pub business_profile_id: Option<common_utils::id_type::ProfileId>,
// This column can be used to partition the database table, so that all events related to a
// single object would reside in the same partition
pub primary_object_created_at: Option<PrimitiveDateTime>,
pub idempotent_event_id: Option<String>,
pub initial_attempt_id: Option<String>,
pub request: Option<Encryption>,
pub response: Option<Encryption>,
pub delivery_attempt: Option<storage_enums::WebhookDeliveryAttempt>,
pub metadata: Option<EventMetadata>,
pub is_overall_delivery_successful: Option<bool>,
}
#[derive(Clone, Debug, Deserialize, Serialize, AsExpression, diesel::FromSqlRow)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub enum EventMetadata {
#[cfg(feature = "v1")]
Payment {
payment_id: common_utils::id_type::PaymentId,
},
#[cfg(feature = "v2")]
Payment {
payment_id: common_utils::id_type::GlobalPaymentId,
},
Payout {
payout_id: common_utils::id_type::PayoutId,
},
#[cfg(feature = "v1")]
Refund {
payment_id: common_utils::id_type::PaymentId,
refund_id: String,
},
#[cfg(feature = "v2")]
Refund {
payment_id: common_utils::id_type::GlobalPaymentId,
refund_id: common_utils::id_type::GlobalRefundId,
},
#[cfg(feature = "v1")]
Dispute {
payment_id: common_utils::id_type::PaymentId,
attempt_id: String,
dispute_id: String,
},
#[cfg(feature = "v2")]
Dispute {
payment_id: common_utils::id_type::GlobalPaymentId,
attempt_id: String,
dispute_id: String,
},
Mandate {
payment_method_id: String,
mandate_id: String,
},
Subscription {
subscription_id: common_utils::id_type::SubscriptionId,
invoice_id: Option<common_utils::id_type::InvoiceId>,
payment_id: Option<common_utils::id_type::PaymentId>,
},
}
common_utils::impl_to_sql_from_sql_json!(EventMetadata);
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/authorization.rs | crates/diesel_models/src/authorization.rs | use common_utils::types::MinorUnit;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{enums as storage_enums, schema::incremental_authorization};
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, Hash,
)]
#[diesel(table_name = incremental_authorization, primary_key(authorization_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct Authorization {
pub authorization_id: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: common_utils::id_type::PaymentId,
pub amount: MinorUnit,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub status: storage_enums::AuthorizationStatus,
pub error_code: Option<String>,
pub error_message: Option<String>,
pub connector_authorization_id: Option<String>,
pub previously_authorized_amount: MinorUnit,
}
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = incremental_authorization)]
pub struct AuthorizationNew {
pub authorization_id: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: common_utils::id_type::PaymentId,
pub amount: MinorUnit,
pub status: storage_enums::AuthorizationStatus,
pub error_code: Option<String>,
pub error_message: Option<String>,
pub connector_authorization_id: Option<String>,
pub previously_authorized_amount: MinorUnit,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AuthorizationUpdate {
StatusUpdate {
status: storage_enums::AuthorizationStatus,
error_code: Option<String>,
error_message: Option<String>,
connector_authorization_id: Option<String>,
},
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = incremental_authorization)]
pub struct AuthorizationUpdateInternal {
pub status: Option<storage_enums::AuthorizationStatus>,
pub error_code: Option<String>,
pub error_message: Option<String>,
pub modified_at: Option<PrimitiveDateTime>,
pub connector_authorization_id: Option<String>,
}
impl AuthorizationUpdateInternal {
pub fn create_authorization(self, source: Authorization) -> Authorization {
Authorization {
status: self.status.unwrap_or(source.status),
error_code: self.error_code.or(source.error_code),
error_message: self.error_message.or(source.error_message),
modified_at: self.modified_at.unwrap_or(common_utils::date_time::now()),
connector_authorization_id: self
.connector_authorization_id
.or(source.connector_authorization_id),
..source
}
}
}
impl From<AuthorizationUpdate> for AuthorizationUpdateInternal {
fn from(authorization_child_update: AuthorizationUpdate) -> Self {
let now = Some(common_utils::date_time::now());
match authorization_child_update {
AuthorizationUpdate::StatusUpdate {
status,
error_code,
error_message,
connector_authorization_id,
} => Self {
status: Some(status),
error_code,
error_message,
connector_authorization_id,
modified_at: now,
},
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/refund.rs | crates/diesel_models/src/refund.rs | use common_utils::{
id_type, pii,
types::{ChargeRefunds, ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit},
};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::enums as storage_enums;
#[cfg(feature = "v1")]
use crate::schema::refund;
#[cfg(feature = "v2")]
use crate::{schema_v2::refund, RequiredFromNullable};
#[cfg(feature = "v1")]
#[derive(
Clone,
Debug,
Eq,
Identifiable,
Queryable,
Selectable,
PartialEq,
serde::Serialize,
serde::Deserialize,
)]
#[diesel(table_name = refund, primary_key(refund_id), check_for_backend(diesel::pg::Pg))]
pub struct Refund {
pub internal_reference_id: String,
pub refund_id: String, //merchant_reference id
pub payment_id: id_type::PaymentId,
pub merchant_id: id_type::MerchantId,
pub connector_transaction_id: ConnectorTransactionId,
pub connector: String,
pub connector_refund_id: Option<ConnectorTransactionId>,
pub external_reference_id: Option<String>,
pub refund_type: storage_enums::RefundType,
pub total_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub refund_amount: MinorUnit,
pub refund_status: storage_enums::RefundStatus,
pub sent_to_gateway: bool,
pub refund_error_message: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub refund_arn: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub description: Option<String>,
pub attempt_id: String,
pub refund_reason: Option<String>,
pub refund_error_code: Option<String>,
pub profile_id: Option<id_type::ProfileId>,
pub updated_by: String,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub charges: Option<ChargeRefunds>,
pub organization_id: id_type::OrganizationId,
/// INFO: This field is deprecated and replaced by processor_refund_data
pub connector_refund_data: Option<String>,
/// INFO: This field is deprecated and replaced by processor_transaction_data
pub connector_transaction_data: Option<String>,
pub split_refunds: Option<common_types::refunds::SplitRefund>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub processor_refund_data: Option<String>,
pub processor_transaction_data: Option<String>,
pub issuer_error_code: Option<String>,
pub issuer_error_message: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(
Clone,
Debug,
Eq,
Identifiable,
Queryable,
Selectable,
PartialEq,
serde::Serialize,
serde::Deserialize,
)]
#[diesel(table_name = refund, primary_key(id), check_for_backend(diesel::pg::Pg))]
pub struct Refund {
pub payment_id: id_type::GlobalPaymentId,
pub merchant_id: id_type::MerchantId,
pub connector_transaction_id: ConnectorTransactionId,
pub connector: String,
pub connector_refund_id: Option<ConnectorTransactionId>,
pub external_reference_id: Option<String>,
pub refund_type: storage_enums::RefundType,
pub total_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub refund_amount: MinorUnit,
pub refund_status: storage_enums::RefundStatus,
pub sent_to_gateway: bool,
pub refund_error_message: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub refund_arn: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub description: Option<String>,
pub attempt_id: id_type::GlobalAttemptId,
pub refund_reason: Option<String>,
pub refund_error_code: Option<String>,
pub profile_id: Option<id_type::ProfileId>,
pub updated_by: String,
pub charges: Option<ChargeRefunds>,
pub organization_id: id_type::OrganizationId,
pub split_refunds: Option<common_types::refunds::SplitRefund>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub processor_refund_data: Option<String>,
pub processor_transaction_data: Option<String>,
pub id: id_type::GlobalRefundId,
#[diesel(deserialize_as = RequiredFromNullable<id_type::RefundReferenceId>)]
pub merchant_reference_id: id_type::RefundReferenceId,
pub connector_id: Option<id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v1")]
#[derive(
Clone,
Debug,
Eq,
PartialEq,
Insertable,
router_derive::DebugAsDisplay,
serde::Serialize,
serde::Deserialize,
router_derive::Setter,
)]
#[diesel(table_name = refund)]
pub struct RefundNew {
pub refund_id: String,
pub payment_id: id_type::PaymentId,
pub merchant_id: id_type::MerchantId,
pub internal_reference_id: String,
pub external_reference_id: Option<String>,
pub connector_transaction_id: ConnectorTransactionId,
pub connector: String,
pub connector_refund_id: Option<ConnectorTransactionId>,
pub refund_type: storage_enums::RefundType,
pub total_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub refund_amount: MinorUnit,
pub refund_status: storage_enums::RefundStatus,
pub sent_to_gateway: bool,
pub metadata: Option<pii::SecretSerdeValue>,
pub refund_arn: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub description: Option<String>,
pub attempt_id: String,
pub refund_reason: Option<String>,
pub profile_id: Option<id_type::ProfileId>,
pub updated_by: String,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub charges: Option<ChargeRefunds>,
pub organization_id: id_type::OrganizationId,
pub split_refunds: Option<common_types::refunds::SplitRefund>,
pub processor_refund_data: Option<String>,
pub processor_transaction_data: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(
Clone,
Debug,
Eq,
PartialEq,
Insertable,
router_derive::DebugAsDisplay,
serde::Serialize,
serde::Deserialize,
router_derive::Setter,
)]
#[diesel(table_name = refund)]
pub struct RefundNew {
pub merchant_reference_id: id_type::RefundReferenceId,
pub payment_id: id_type::GlobalPaymentId,
pub merchant_id: id_type::MerchantId,
pub id: id_type::GlobalRefundId,
pub external_reference_id: Option<String>,
pub connector_transaction_id: ConnectorTransactionId,
pub connector: String,
pub connector_refund_id: Option<ConnectorTransactionId>,
pub refund_type: storage_enums::RefundType,
pub total_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub refund_amount: MinorUnit,
pub refund_status: storage_enums::RefundStatus,
pub sent_to_gateway: bool,
pub metadata: Option<pii::SecretSerdeValue>,
pub refund_arn: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub description: Option<String>,
pub attempt_id: id_type::GlobalAttemptId,
pub refund_reason: Option<String>,
pub profile_id: Option<id_type::ProfileId>,
pub updated_by: String,
pub connector_id: Option<id_type::MerchantConnectorAccountId>,
pub charges: Option<ChargeRefunds>,
pub organization_id: id_type::OrganizationId,
pub split_refunds: Option<common_types::refunds::SplitRefund>,
pub processor_refund_data: Option<String>,
pub processor_transaction_data: Option<String>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum RefundUpdate {
Update {
connector_refund_id: ConnectorTransactionId,
refund_status: storage_enums::RefundStatus,
sent_to_gateway: bool,
refund_error_message: Option<String>,
refund_arn: String,
updated_by: String,
processor_refund_data: Option<String>,
},
MetadataAndReasonUpdate {
metadata: Option<pii::SecretSerdeValue>,
reason: Option<String>,
updated_by: String,
},
StatusUpdate {
connector_refund_id: Option<ConnectorTransactionId>,
sent_to_gateway: bool,
refund_status: storage_enums::RefundStatus,
updated_by: String,
processor_refund_data: Option<String>,
},
ErrorUpdate {
refund_status: Option<storage_enums::RefundStatus>,
refund_error_message: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
connector_refund_id: Option<ConnectorTransactionId>,
processor_refund_data: Option<String>,
unified_code: Option<String>,
unified_message: Option<String>,
issuer_error_code: Option<String>,
issuer_error_message: Option<String>,
},
ManualUpdate {
refund_status: Option<storage_enums::RefundStatus>,
refund_error_message: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
},
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum RefundUpdate {
Update {
connector_refund_id: ConnectorTransactionId,
refund_status: storage_enums::RefundStatus,
sent_to_gateway: bool,
refund_error_message: Option<String>,
refund_arn: String,
updated_by: String,
processor_refund_data: Option<String>,
},
MetadataAndReasonUpdate {
metadata: Option<pii::SecretSerdeValue>,
reason: Option<String>,
updated_by: String,
},
StatusUpdate {
connector_refund_id: Option<ConnectorTransactionId>,
sent_to_gateway: bool,
refund_status: storage_enums::RefundStatus,
updated_by: String,
processor_refund_data: Option<String>,
},
ErrorUpdate {
refund_status: Option<storage_enums::RefundStatus>,
refund_error_message: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
connector_refund_id: Option<ConnectorTransactionId>,
processor_refund_data: Option<String>,
unified_code: Option<String>,
unified_message: Option<String>,
},
ManualUpdate {
refund_status: Option<storage_enums::RefundStatus>,
refund_error_message: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
},
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = refund)]
pub struct RefundUpdateInternal {
connector_refund_id: Option<ConnectorTransactionId>,
refund_status: Option<storage_enums::RefundStatus>,
sent_to_gateway: Option<bool>,
refund_error_message: Option<String>,
refund_arn: Option<String>,
metadata: Option<pii::SecretSerdeValue>,
refund_reason: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
modified_at: PrimitiveDateTime,
processor_refund_data: Option<String>,
unified_code: Option<String>,
unified_message: Option<String>,
issuer_error_code: Option<String>,
issuer_error_message: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = refund)]
pub struct RefundUpdateInternal {
connector_refund_id: Option<ConnectorTransactionId>,
refund_status: Option<storage_enums::RefundStatus>,
sent_to_gateway: Option<bool>,
refund_error_message: Option<String>,
refund_arn: Option<String>,
metadata: Option<pii::SecretSerdeValue>,
refund_reason: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
modified_at: PrimitiveDateTime,
processor_refund_data: Option<String>,
unified_code: Option<String>,
unified_message: Option<String>,
}
#[cfg(feature = "v1")]
impl RefundUpdateInternal {
pub fn create_refund(self, source: Refund) -> Refund {
Refund {
connector_refund_id: self.connector_refund_id,
refund_status: self.refund_status.unwrap_or_default(),
sent_to_gateway: self.sent_to_gateway.unwrap_or_default(),
refund_error_message: self.refund_error_message,
refund_arn: self.refund_arn,
metadata: self.metadata,
refund_reason: self.refund_reason,
refund_error_code: self.refund_error_code,
updated_by: self.updated_by,
modified_at: self.modified_at,
processor_refund_data: self.processor_refund_data,
unified_code: self.unified_code,
unified_message: self.unified_message,
..source
}
}
}
#[cfg(feature = "v2")]
impl RefundUpdateInternal {
pub fn create_refund(self, source: Refund) -> Refund {
Refund {
connector_refund_id: self.connector_refund_id,
refund_status: self.refund_status.unwrap_or_default(),
sent_to_gateway: self.sent_to_gateway.unwrap_or_default(),
refund_error_message: self.refund_error_message,
refund_arn: self.refund_arn,
metadata: self.metadata,
refund_reason: self.refund_reason,
refund_error_code: self.refund_error_code,
updated_by: self.updated_by,
modified_at: self.modified_at,
processor_refund_data: self.processor_refund_data,
unified_code: self.unified_code,
unified_message: self.unified_message,
..source
}
}
}
#[cfg(feature = "v1")]
impl From<RefundUpdate> for RefundUpdateInternal {
fn from(refund_update: RefundUpdate) -> Self {
match refund_update {
RefundUpdate::Update {
connector_refund_id,
refund_status,
sent_to_gateway,
refund_error_message,
refund_arn,
updated_by,
processor_refund_data,
} => Self {
connector_refund_id: Some(connector_refund_id),
refund_status: Some(refund_status),
sent_to_gateway: Some(sent_to_gateway),
refund_error_message,
refund_arn: Some(refund_arn),
updated_by,
processor_refund_data,
metadata: None,
refund_reason: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
},
RefundUpdate::MetadataAndReasonUpdate {
metadata,
reason,
updated_by,
} => Self {
metadata,
refund_reason: reason,
updated_by,
connector_refund_id: None,
refund_status: None,
sent_to_gateway: None,
refund_error_message: None,
refund_arn: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
processor_refund_data: None,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
},
RefundUpdate::StatusUpdate {
connector_refund_id,
sent_to_gateway,
refund_status,
updated_by,
processor_refund_data,
} => Self {
connector_refund_id,
sent_to_gateway: Some(sent_to_gateway),
refund_status: Some(refund_status),
updated_by,
processor_refund_data,
refund_error_message: None,
refund_arn: None,
metadata: None,
refund_reason: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
},
RefundUpdate::ErrorUpdate {
refund_status,
refund_error_message,
refund_error_code,
unified_code,
unified_message,
updated_by,
connector_refund_id,
processor_refund_data,
issuer_error_code,
issuer_error_message,
} => Self {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
connector_refund_id,
processor_refund_data,
sent_to_gateway: None,
refund_arn: None,
metadata: None,
refund_reason: None,
modified_at: common_utils::date_time::now(),
unified_code,
unified_message,
issuer_error_code,
issuer_error_message,
},
RefundUpdate::ManualUpdate {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
} => Self {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
connector_refund_id: None,
sent_to_gateway: None,
refund_arn: None,
metadata: None,
refund_reason: None,
modified_at: common_utils::date_time::now(),
processor_refund_data: None,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
},
}
}
}
#[cfg(feature = "v2")]
impl From<RefundUpdate> for RefundUpdateInternal {
fn from(refund_update: RefundUpdate) -> Self {
match refund_update {
RefundUpdate::Update {
connector_refund_id,
refund_status,
sent_to_gateway,
refund_error_message,
refund_arn,
updated_by,
processor_refund_data,
} => Self {
connector_refund_id: Some(connector_refund_id),
refund_status: Some(refund_status),
sent_to_gateway: Some(sent_to_gateway),
refund_error_message,
refund_arn: Some(refund_arn),
updated_by,
processor_refund_data,
metadata: None,
refund_reason: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
unified_code: None,
unified_message: None,
},
RefundUpdate::MetadataAndReasonUpdate {
metadata,
reason,
updated_by,
} => Self {
metadata,
refund_reason: reason,
updated_by,
connector_refund_id: None,
refund_status: None,
sent_to_gateway: None,
refund_error_message: None,
refund_arn: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
processor_refund_data: None,
unified_code: None,
unified_message: None,
},
RefundUpdate::StatusUpdate {
connector_refund_id,
sent_to_gateway,
refund_status,
updated_by,
processor_refund_data,
} => Self {
connector_refund_id,
sent_to_gateway: Some(sent_to_gateway),
refund_status: Some(refund_status),
updated_by,
processor_refund_data,
refund_error_message: None,
refund_arn: None,
metadata: None,
refund_reason: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
unified_code: None,
unified_message: None,
},
RefundUpdate::ErrorUpdate {
refund_status,
refund_error_message,
refund_error_code,
unified_code,
unified_message,
updated_by,
connector_refund_id,
processor_refund_data,
} => Self {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
connector_refund_id,
processor_refund_data,
sent_to_gateway: None,
refund_arn: None,
metadata: None,
refund_reason: None,
modified_at: common_utils::date_time::now(),
unified_code,
unified_message,
},
RefundUpdate::ManualUpdate {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
} => Self {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
connector_refund_id: None,
sent_to_gateway: None,
refund_arn: None,
metadata: None,
refund_reason: None,
modified_at: common_utils::date_time::now(),
processor_refund_data: None,
unified_code: None,
unified_message: None,
},
}
}
}
#[cfg(feature = "v1")]
impl RefundUpdate {
pub fn apply_changeset(self, source: Refund) -> Refund {
let RefundUpdateInternal {
connector_refund_id,
refund_status,
sent_to_gateway,
refund_error_message,
refund_arn,
metadata,
refund_reason,
refund_error_code,
updated_by,
modified_at: _,
processor_refund_data,
unified_code,
unified_message,
issuer_error_code,
issuer_error_message,
} = self.into();
Refund {
connector_refund_id: connector_refund_id.or(source.connector_refund_id),
refund_status: refund_status.unwrap_or(source.refund_status),
sent_to_gateway: sent_to_gateway.unwrap_or(source.sent_to_gateway),
refund_error_message: refund_error_message.or(source.refund_error_message),
refund_error_code: refund_error_code.or(source.refund_error_code),
refund_arn: refund_arn.or(source.refund_arn),
metadata: metadata.or(source.metadata),
refund_reason: refund_reason.or(source.refund_reason),
updated_by,
modified_at: common_utils::date_time::now(),
processor_refund_data: processor_refund_data.or(source.processor_refund_data),
unified_code: unified_code.or(source.unified_code),
unified_message: unified_message.or(source.unified_message),
issuer_error_code: issuer_error_code.or(source.issuer_error_code),
issuer_error_message: issuer_error_message.or(source.issuer_error_message),
..source
}
}
}
#[cfg(feature = "v2")]
impl RefundUpdate {
pub fn apply_changeset(self, source: Refund) -> Refund {
let RefundUpdateInternal {
connector_refund_id,
refund_status,
sent_to_gateway,
refund_error_message,
refund_arn,
metadata,
refund_reason,
refund_error_code,
updated_by,
modified_at: _,
processor_refund_data,
unified_code,
unified_message,
} = self.into();
Refund {
connector_refund_id: connector_refund_id.or(source.connector_refund_id),
refund_status: refund_status.unwrap_or(source.refund_status),
sent_to_gateway: sent_to_gateway.unwrap_or(source.sent_to_gateway),
refund_error_message: refund_error_message.or(source.refund_error_message),
refund_error_code: refund_error_code.or(source.refund_error_code),
refund_arn: refund_arn.or(source.refund_arn),
metadata: metadata.or(source.metadata),
refund_reason: refund_reason.or(source.refund_reason),
updated_by,
modified_at: common_utils::date_time::now(),
processor_refund_data: processor_refund_data.or(source.processor_refund_data),
unified_code: unified_code.or(source.unified_code),
unified_message: unified_message.or(source.unified_message),
..source
}
}
pub fn build_error_update_for_unified_error_and_message(
unified_error_object: (String, String),
refund_error_message: Option<String>,
refund_error_code: Option<String>,
storage_scheme: &storage_enums::MerchantStorageScheme,
) -> Self {
let (unified_code, unified_message) = unified_error_object;
Self::ErrorUpdate {
refund_status: Some(storage_enums::RefundStatus::Failure),
refund_error_message,
refund_error_code,
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: Some(unified_code),
unified_message: Some(unified_message),
}
}
pub fn build_error_update_for_integrity_check_failure(
integrity_check_failed_fields: String,
connector_refund_id: Option<ConnectorTransactionId>,
storage_scheme: &storage_enums::MerchantStorageScheme,
) -> Self {
Self::ErrorUpdate {
refund_status: Some(storage_enums::RefundStatus::ManualReview),
refund_error_message: Some(format!(
"Integrity Check Failed! as data mismatched for fields {integrity_check_failed_fields}"
)),
refund_error_code: Some("IE".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: connector_refund_id.clone(),
processor_refund_data: connector_refund_id.and_then(|x| x.extract_hashed_data()),
unified_code: None,
unified_message: None,
}
}
pub fn build_refund_update(
connector_refund_id: ConnectorTransactionId,
refund_status: storage_enums::RefundStatus,
storage_scheme: &storage_enums::MerchantStorageScheme,
) -> Self {
Self::Update {
connector_refund_id: connector_refund_id.clone(),
refund_status,
sent_to_gateway: true,
refund_error_message: None,
refund_arn: "".to_string(),
updated_by: storage_scheme.to_string(),
processor_refund_data: connector_refund_id.extract_hashed_data(),
}
}
pub fn build_error_update_for_refund_failure(
refund_status: Option<storage_enums::RefundStatus>,
refund_error_message: Option<String>,
refund_error_code: Option<String>,
storage_scheme: &storage_enums::MerchantStorageScheme,
) -> Self {
Self::ErrorUpdate {
refund_status,
refund_error_message,
refund_error_code,
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
}
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct RefundCoreWorkflow {
pub refund_internal_reference_id: String,
pub connector_transaction_id: ConnectorTransactionId,
pub merchant_id: id_type::MerchantId,
pub payment_id: id_type::PaymentId,
pub processor_transaction_data: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct RefundCoreWorkflow {
pub refund_id: id_type::GlobalRefundId,
pub connector_transaction_id: ConnectorTransactionId,
pub merchant_id: id_type::MerchantId,
pub payment_id: id_type::GlobalPaymentId,
pub processor_transaction_data: Option<String>,
}
#[cfg(feature = "v1")]
impl common_utils::events::ApiEventMetric for Refund {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Refund {
payment_id: Some(self.payment_id.clone()),
refund_id: self.refund_id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl common_utils::events::ApiEventMetric for Refund {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Refund {
payment_id: Some(self.payment_id.clone()),
refund_id: self.id.clone(),
})
}
}
impl ConnectorTransactionIdTrait for Refund {
fn get_optional_connector_refund_id(&self) -> Option<&String> {
match self
.connector_refund_id
.as_ref()
.map(|refund_id| refund_id.get_txn_id(self.processor_refund_data.as_ref()))
.transpose()
{
Ok(refund_id) => refund_id,
// In case hashed data is missing from DB, use the hashed ID as connector transaction ID
Err(_) => self
.connector_refund_id
.as_ref()
.map(|txn_id| txn_id.get_id()),
}
}
fn get_connector_transaction_id(&self) -> &String {
match self
.connector_transaction_id
.get_txn_id(self.processor_transaction_data.as_ref())
{
Ok(txn_id) => txn_id,
// In case hashed data is missing from DB, use the hashed ID as connector transaction ID
Err(_) => self.connector_transaction_id.get_id(),
}
}
}
mod tests {
#[test]
fn test_backwards_compatibility() {
let serialized_refund = r#"{
"internal_reference_id": "internal_ref_123",
"refund_id": "refund_456",
"payment_id": "payment_789",
"merchant_id": "merchant_123",
"connector_transaction_id": "connector_txn_789",
"connector": "stripe",
"connector_refund_id": null,
"external_reference_id": null,
"refund_type": "instant_refund",
"total_amount": 10000,
"currency": "USD",
"refund_amount": 9500,
"refund_status": "Success",
"sent_to_gateway": true,
"refund_error_message": null,
"metadata": null,
"refund_arn": null,
"created_at": "2024-02-26T12:00:00Z",
"updated_at": "2024-02-26T12:00:00Z",
"description": null,
"attempt_id": "attempt_123",
"refund_reason": null,
"refund_error_code": null,
"profile_id": null,
"updated_by": "admin",
"merchant_connector_id": null,
"charges": null,
"connector_transaction_data": null
"unified_code": null,
"unified_message": null,
"processor_transaction_data": null,
}"#;
let deserialized = serde_json::from_str::<super::Refund>(serialized_refund);
assert!(deserialized.is_ok());
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/kv.rs | crates/diesel_models/src/kv.rs | use error_stack::ResultExt;
use serde::{Deserialize, Serialize};
#[cfg(feature = "v2")]
use crate::payment_attempt::PaymentAttemptUpdateInternal;
#[cfg(feature = "v1")]
use crate::payment_intent::PaymentIntentUpdate;
#[cfg(feature = "v2")]
use crate::payment_intent::PaymentIntentUpdateInternal;
use crate::{
address::{Address, AddressNew, AddressUpdateInternal},
customers::{Customer, CustomerNew, CustomerUpdateInternal},
errors,
payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate},
payment_intent::PaymentIntentNew,
payout_attempt::{PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate},
payouts::{Payouts, PayoutsNew, PayoutsUpdate},
refund::{Refund, RefundNew, RefundUpdate},
reverse_lookup::{ReverseLookup, ReverseLookupNew},
Mandate, MandateNew, MandateUpdateInternal, PaymentIntent, PaymentMethod, PaymentMethodNew,
PaymentMethodUpdateInternal, PgPooledConn,
};
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "db_op", content = "data")]
pub enum DBOperation {
Insert { insertable: Box<Insertable> },
Update { updatable: Box<Updateable> },
}
impl DBOperation {
pub fn operation<'a>(&self) -> &'a str {
match self {
Self::Insert { .. } => "insert",
Self::Update { .. } => "update",
}
}
pub fn table<'a>(&self) -> &'a str {
match self {
Self::Insert { insertable } => match **insertable {
Insertable::PaymentIntent(_) => "payment_intent",
Insertable::PaymentAttempt(_) => "payment_attempt",
Insertable::Refund(_) => "refund",
Insertable::Address(_) => "address",
Insertable::Payouts(_) => "payouts",
Insertable::PayoutAttempt(_) => "payout_attempt",
Insertable::Customer(_) => "customer",
Insertable::ReverseLookUp(_) => "reverse_lookup",
Insertable::PaymentMethod(_) => "payment_method",
Insertable::Mandate(_) => "mandate",
},
Self::Update { updatable } => match **updatable {
Updateable::PaymentIntentUpdate(_) => "payment_intent",
Updateable::PaymentAttemptUpdate(_) => "payment_attempt",
Updateable::RefundUpdate(_) => "refund",
Updateable::CustomerUpdate(_) => "customer",
Updateable::AddressUpdate(_) => "address",
Updateable::PayoutsUpdate(_) => "payouts",
Updateable::PayoutAttemptUpdate(_) => "payout_attempt",
Updateable::PaymentMethodUpdate(_) => "payment_method",
Updateable::MandateUpdate(_) => " mandate",
},
}
}
}
#[derive(Debug)]
pub enum DBResult {
PaymentIntent(Box<PaymentIntent>),
PaymentAttempt(Box<PaymentAttempt>),
Refund(Box<Refund>),
Address(Box<Address>),
Customer(Box<Customer>),
ReverseLookUp(Box<ReverseLookup>),
Payouts(Box<Payouts>),
PayoutAttempt(Box<PayoutAttempt>),
PaymentMethod(Box<PaymentMethod>),
Mandate(Box<Mandate>),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct TypedSql {
#[serde(flatten)]
pub op: DBOperation,
}
impl DBOperation {
pub async fn execute(self, conn: &PgPooledConn) -> crate::StorageResult<DBResult> {
Ok(match self {
Self::Insert { insertable } => match *insertable {
Insertable::PaymentIntent(a) => {
DBResult::PaymentIntent(Box::new(a.insert(conn).await?))
}
Insertable::PaymentAttempt(a) => {
DBResult::PaymentAttempt(Box::new(a.insert(conn).await?))
}
Insertable::Refund(a) => DBResult::Refund(Box::new(a.insert(conn).await?)),
Insertable::Address(addr) => DBResult::Address(Box::new(addr.insert(conn).await?)),
Insertable::Customer(cust) => {
DBResult::Customer(Box::new(cust.insert(conn).await?))
}
Insertable::ReverseLookUp(rev) => {
DBResult::ReverseLookUp(Box::new(rev.insert(conn).await?))
}
Insertable::Payouts(rev) => DBResult::Payouts(Box::new(rev.insert(conn).await?)),
Insertable::PayoutAttempt(rev) => {
DBResult::PayoutAttempt(Box::new(rev.insert(conn).await?))
}
Insertable::PaymentMethod(rev) => {
DBResult::PaymentMethod(Box::new(rev.insert(conn).await?))
}
Insertable::Mandate(m) => DBResult::Mandate(Box::new(m.insert(conn).await?)),
},
Self::Update { updatable } => match *updatable {
#[cfg(feature = "v1")]
Updateable::PaymentIntentUpdate(a) => {
DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?))
}
#[cfg(feature = "v2")]
Updateable::PaymentIntentUpdate(a) => {
DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?))
}
#[cfg(feature = "v1")]
Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new(
a.orig.update_with_attempt_id(conn, a.update_data).await?,
)),
#[cfg(feature = "v2")]
Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new(
a.orig.update_with_attempt_id(conn, a.update_data).await?,
)),
#[cfg(feature = "v1")]
Updateable::RefundUpdate(a) => {
DBResult::Refund(Box::new(a.orig.update(conn, a.update_data).await?))
}
#[cfg(feature = "v2")]
Updateable::RefundUpdate(a) => {
DBResult::Refund(Box::new(a.orig.update_with_id(conn, a.update_data).await?))
}
Updateable::AddressUpdate(a) => {
DBResult::Address(Box::new(a.orig.update(conn, a.update_data).await?))
}
Updateable::PayoutsUpdate(a) => {
DBResult::Payouts(Box::new(a.orig.update(conn, a.update_data).await?))
}
Updateable::PayoutAttemptUpdate(a) => DBResult::PayoutAttempt(Box::new(
a.orig.update_with_attempt_id(conn, a.update_data).await?,
)),
#[cfg(feature = "v1")]
Updateable::PaymentMethodUpdate(v) => DBResult::PaymentMethod(Box::new(
v.orig
.update_with_payment_method_id(conn, v.update_data)
.await?,
)),
#[cfg(feature = "v2")]
Updateable::PaymentMethodUpdate(v) => DBResult::PaymentMethod(Box::new(
v.orig.update_with_id(conn, v.update_data).await?,
)),
Updateable::MandateUpdate(m) => DBResult::Mandate(Box::new(
Mandate::update_by_merchant_id_mandate_id(
conn,
&m.orig.merchant_id,
&m.orig.mandate_id,
m.update_data,
)
.await?,
)),
#[cfg(feature = "v1")]
Updateable::CustomerUpdate(cust) => DBResult::Customer(Box::new(
Customer::update_by_customer_id_merchant_id(
conn,
cust.orig.customer_id.clone(),
cust.orig.merchant_id.clone(),
cust.update_data,
)
.await?,
)),
#[cfg(feature = "v2")]
Updateable::CustomerUpdate(cust) => DBResult::Customer(Box::new(
Customer::update_by_id(conn, cust.orig.id, cust.update_data).await?,
)),
},
})
}
}
impl TypedSql {
pub fn to_field_value_pairs(
&self,
request_id: String,
global_id: String,
) -> crate::StorageResult<Vec<(&str, String)>> {
let pushed_at = common_utils::date_time::now_unix_timestamp();
Ok(vec![
(
"typed_sql",
serde_json::to_string(self)
.change_context(errors::DatabaseError::QueryGenerationFailed)?,
),
("global_id", global_id),
("request_id", request_id),
("pushed_at", pushed_at.to_string()),
])
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "table", content = "data")]
pub enum Insertable {
PaymentIntent(Box<PaymentIntentNew>),
PaymentAttempt(Box<PaymentAttemptNew>),
Refund(RefundNew),
Address(Box<AddressNew>),
Customer(CustomerNew),
ReverseLookUp(ReverseLookupNew),
Payouts(PayoutsNew),
PayoutAttempt(PayoutAttemptNew),
PaymentMethod(Box<PaymentMethodNew>),
Mandate(MandateNew),
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "table", content = "data")]
pub enum Updateable {
PaymentIntentUpdate(Box<PaymentIntentUpdateMems>),
PaymentAttemptUpdate(Box<PaymentAttemptUpdateMems>),
RefundUpdate(Box<RefundUpdateMems>),
CustomerUpdate(CustomerUpdateMems),
AddressUpdate(Box<AddressUpdateMems>),
PayoutsUpdate(PayoutsUpdateMems),
PayoutAttemptUpdate(PayoutAttemptUpdateMems),
PaymentMethodUpdate(Box<PaymentMethodUpdateMems>),
MandateUpdate(MandateUpdateMems),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CustomerUpdateMems {
pub orig: Customer,
pub update_data: CustomerUpdateInternal,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AddressUpdateMems {
pub orig: Address,
pub update_data: AddressUpdateInternal,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentIntentUpdateMems {
pub orig: PaymentIntent,
pub update_data: PaymentIntentUpdate,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentIntentUpdateMems {
pub orig: PaymentIntent,
pub update_data: PaymentIntentUpdateInternal,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentAttemptUpdateMems {
pub orig: PaymentAttempt,
pub update_data: PaymentAttemptUpdate,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentAttemptUpdateMems {
pub orig: PaymentAttempt,
pub update_data: PaymentAttemptUpdateInternal,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RefundUpdateMems {
pub orig: Refund,
pub update_data: RefundUpdate,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PayoutsUpdateMems {
pub orig: Payouts,
pub update_data: PayoutsUpdate,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PayoutAttemptUpdateMems {
pub orig: PayoutAttempt,
pub update_data: PayoutAttemptUpdate,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentMethodUpdateMems {
pub orig: PaymentMethod,
pub update_data: PaymentMethodUpdateInternal,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MandateUpdateMems {
pub orig: Mandate,
pub update_data: MandateUpdateInternal,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/schema_v2.rs | crates/diesel_models/src/schema_v2.rs | // @generated automatically by Diesel CLI.
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
address (address_id) {
#[max_length = 64]
address_id -> Varchar,
#[max_length = 128]
city -> Nullable<Varchar>,
country -> Nullable<CountryAlpha2>,
line1 -> Nullable<Bytea>,
line2 -> Nullable<Bytea>,
line3 -> Nullable<Bytea>,
state -> Nullable<Bytea>,
zip -> Nullable<Bytea>,
first_name -> Nullable<Bytea>,
last_name -> Nullable<Bytea>,
phone_number -> Nullable<Bytea>,
#[max_length = 8]
country_code -> Nullable<Varchar>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_id -> Nullable<Varchar>,
#[max_length = 32]
updated_by -> Varchar,
email -> Nullable<Bytea>,
origin_zip -> Nullable<Bytea>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
api_keys (key_id) {
#[max_length = 64]
key_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
name -> Varchar,
#[max_length = 256]
description -> Nullable<Varchar>,
#[max_length = 128]
hashed_api_key -> Varchar,
#[max_length = 16]
prefix -> Varchar,
created_at -> Timestamp,
expires_at -> Nullable<Timestamp>,
last_used -> Nullable<Timestamp>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
authentication (authentication_id) {
#[max_length = 64]
authentication_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
authentication_connector -> Nullable<Varchar>,
#[max_length = 64]
connector_authentication_id -> Nullable<Varchar>,
authentication_data -> Nullable<Jsonb>,
#[max_length = 64]
payment_method_id -> Varchar,
#[max_length = 64]
authentication_type -> Nullable<Varchar>,
#[max_length = 64]
authentication_status -> Varchar,
#[max_length = 64]
authentication_lifecycle_status -> Varchar,
created_at -> Timestamp,
modified_at -> Timestamp,
error_message -> Nullable<Text>,
#[max_length = 64]
error_code -> Nullable<Varchar>,
connector_metadata -> Nullable<Jsonb>,
maximum_supported_version -> Nullable<Jsonb>,
#[max_length = 64]
threeds_server_transaction_id -> Nullable<Varchar>,
#[max_length = 64]
cavv -> Nullable<Varchar>,
#[max_length = 64]
authentication_flow_type -> Nullable<Varchar>,
message_version -> Nullable<Jsonb>,
#[max_length = 64]
eci -> Nullable<Varchar>,
#[max_length = 64]
trans_status -> Nullable<Varchar>,
#[max_length = 64]
acquirer_bin -> Nullable<Varchar>,
#[max_length = 64]
acquirer_merchant_id -> Nullable<Varchar>,
three_ds_method_data -> Nullable<Varchar>,
three_ds_method_url -> Nullable<Varchar>,
acs_url -> Nullable<Varchar>,
challenge_request -> Nullable<Varchar>,
acs_reference_number -> Nullable<Varchar>,
acs_trans_id -> Nullable<Varchar>,
acs_signed_content -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 255]
payment_id -> Nullable<Varchar>,
#[max_length = 128]
merchant_connector_id -> Nullable<Varchar>,
#[max_length = 64]
ds_trans_id -> Nullable<Varchar>,
#[max_length = 128]
directory_server_id -> Nullable<Varchar>,
#[max_length = 64]
acquirer_country_code -> Nullable<Varchar>,
service_details -> Nullable<Jsonb>,
#[max_length = 32]
organization_id -> Varchar,
#[max_length = 128]
authentication_client_secret -> Nullable<Varchar>,
force_3ds_challenge -> Nullable<Bool>,
psd2_sca_exemption_type -> Nullable<ScaExemptionType>,
#[max_length = 2048]
return_url -> Nullable<Varchar>,
amount -> Nullable<Int8>,
currency -> Nullable<Currency>,
billing_address -> Nullable<Bytea>,
shipping_address -> Nullable<Bytea>,
browser_info -> Nullable<Jsonb>,
email -> Nullable<Bytea>,
#[max_length = 128]
profile_acquirer_id -> Nullable<Varchar>,
challenge_code -> Nullable<Varchar>,
challenge_cancel -> Nullable<Varchar>,
challenge_code_reason -> Nullable<Varchar>,
message_extension -> Nullable<Jsonb>,
#[max_length = 255]
challenge_request_key -> Nullable<Varchar>,
customer_details -> Nullable<Bytea>,
earliest_supported_version -> Nullable<Jsonb>,
latest_supported_version -> Nullable<Jsonb>,
#[max_length = 8]
mcc -> Nullable<Varchar>,
#[max_length = 64]
platform -> Nullable<Varchar>,
#[max_length = 255]
device_type -> Nullable<Varchar>,
#[max_length = 255]
device_brand -> Nullable<Varchar>,
#[max_length = 255]
device_os -> Nullable<Varchar>,
#[max_length = 255]
device_display -> Nullable<Varchar>,
#[max_length = 255]
browser_name -> Nullable<Varchar>,
#[max_length = 255]
browser_version -> Nullable<Varchar>,
#[max_length = 255]
scheme_name -> Nullable<Varchar>,
exemption_requested -> Nullable<Bool>,
exemption_accepted -> Nullable<Bool>,
#[max_length = 255]
issuer_id -> Nullable<Varchar>,
#[max_length = 16]
issuer_country -> Nullable<Varchar>,
#[max_length = 8]
merchant_country_code -> Nullable<Varchar>,
#[max_length = 16]
billing_country -> Nullable<Varchar>,
#[max_length = 16]
shipping_country -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist (merchant_id, fingerprint_id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
fingerprint_id -> Varchar,
data_kind -> BlocklistDataKind,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist_fingerprint (id) {
id -> Int4,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
fingerprint_id -> Varchar,
data_kind -> BlocklistDataKind,
encrypted_fingerprint -> Text,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist_lookup (id) {
id -> Int4,
#[max_length = 64]
merchant_id -> Varchar,
fingerprint -> Text,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
business_profile (id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_name -> Varchar,
created_at -> Timestamp,
modified_at -> Timestamp,
return_url -> Nullable<Text>,
enable_payment_response_hash -> Bool,
#[max_length = 255]
payment_response_hash_key -> Nullable<Varchar>,
redirect_to_merchant_with_http_post -> Bool,
webhook_details -> Nullable<Json>,
metadata -> Nullable<Json>,
is_recon_enabled -> Bool,
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
payment_link_config -> Nullable<Jsonb>,
session_expiry -> Nullable<Int8>,
authentication_connector_details -> Nullable<Jsonb>,
payout_link_config -> Nullable<Jsonb>,
is_extended_card_info_enabled -> Nullable<Bool>,
extended_card_info_config -> Nullable<Jsonb>,
is_connector_agnostic_mit_enabled -> Nullable<Bool>,
use_billing_as_payment_method_billing -> Nullable<Bool>,
collect_shipping_details_from_wallet_connector -> Nullable<Bool>,
collect_billing_details_from_wallet_connector -> Nullable<Bool>,
outgoing_webhook_custom_http_headers -> Nullable<Bytea>,
always_collect_billing_details_from_wallet_connector -> Nullable<Bool>,
always_collect_shipping_details_from_wallet_connector -> Nullable<Bool>,
#[max_length = 64]
tax_connector_id -> Nullable<Varchar>,
is_tax_connector_enabled -> Nullable<Bool>,
version -> ApiVersion,
dynamic_routing_algorithm -> Nullable<Json>,
is_network_tokenization_enabled -> Bool,
is_auto_retries_enabled -> Nullable<Bool>,
max_auto_retries_enabled -> Nullable<Int2>,
always_request_extended_authorization -> Nullable<Bool>,
is_click_to_pay_enabled -> Bool,
authentication_product_ids -> Nullable<Jsonb>,
card_testing_guard_config -> Nullable<Jsonb>,
card_testing_secret_key -> Nullable<Bytea>,
is_clear_pan_retries_enabled -> Bool,
force_3ds_challenge -> Nullable<Bool>,
is_debit_routing_enabled -> Bool,
merchant_business_country -> Nullable<CountryAlpha2>,
#[max_length = 64]
id -> Varchar,
is_iframe_redirection_enabled -> Nullable<Bool>,
three_ds_decision_rule_algorithm -> Nullable<Jsonb>,
acquirer_config_map -> Nullable<Jsonb>,
#[max_length = 16]
merchant_category_code -> Nullable<Varchar>,
#[max_length = 32]
merchant_country_code -> Nullable<Varchar>,
dispute_polling_interval -> Nullable<Int4>,
is_manual_retry_enabled -> Nullable<Bool>,
always_enable_overcapture -> Nullable<Bool>,
#[max_length = 64]
billing_processor_id -> Nullable<Varchar>,
is_external_vault_enabled -> Nullable<Bool>,
external_vault_connector_details -> Nullable<Jsonb>,
is_l2_l3_enabled -> Nullable<Bool>,
#[max_length = 64]
routing_algorithm_id -> Nullable<Varchar>,
order_fulfillment_time -> Nullable<Int8>,
order_fulfillment_time_origin -> Nullable<OrderFulfillmentTimeOrigin>,
#[max_length = 64]
frm_routing_algorithm_id -> Nullable<Varchar>,
#[max_length = 64]
payout_routing_algorithm_id -> Nullable<Varchar>,
default_fallback_routing -> Nullable<Jsonb>,
three_ds_decision_manager_config -> Nullable<Jsonb>,
should_collect_cvv_during_payment -> Nullable<Bool>,
revenue_recovery_retry_algorithm_type -> Nullable<RevenueRecoveryAlgorithmType>,
revenue_recovery_retry_algorithm_data -> Nullable<Jsonb>,
#[max_length = 16]
split_txns_enabled -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
callback_mapper (id, type_) {
#[max_length = 128]
id -> Varchar,
#[sql_name = "type"]
#[max_length = 64]
type_ -> Varchar,
data -> Jsonb,
created_at -> Timestamp,
last_modified_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
captures (capture_id) {
#[max_length = 64]
capture_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
status -> CaptureStatus,
amount -> Int8,
currency -> Nullable<Currency>,
#[max_length = 255]
connector -> Varchar,
#[max_length = 255]
error_message -> Nullable<Varchar>,
#[max_length = 255]
error_code -> Nullable<Varchar>,
#[max_length = 255]
error_reason -> Nullable<Varchar>,
tax_amount -> Nullable<Int8>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
authorized_attempt_id -> Varchar,
#[max_length = 128]
connector_capture_id -> Nullable<Varchar>,
capture_sequence -> Int2,
#[max_length = 128]
connector_response_reference_id -> Nullable<Varchar>,
processor_capture_data -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
cards_info (card_iin) {
#[max_length = 16]
card_iin -> Varchar,
card_issuer -> Nullable<Text>,
card_network -> Nullable<Text>,
card_type -> Nullable<Text>,
card_subtype -> Nullable<Text>,
card_issuing_country -> Nullable<Text>,
#[max_length = 32]
bank_code_id -> Nullable<Varchar>,
#[max_length = 32]
bank_code -> Nullable<Varchar>,
#[max_length = 32]
country_code -> Nullable<Varchar>,
date_created -> Timestamp,
last_updated -> Nullable<Timestamp>,
last_updated_provider -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
configs (key) {
id -> Int4,
#[max_length = 255]
key -> Varchar,
config -> Text,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
customers (id) {
#[max_length = 64]
merchant_id -> Varchar,
name -> Nullable<Bytea>,
email -> Nullable<Bytea>,
phone -> Nullable<Bytea>,
#[max_length = 8]
phone_country_code -> Nullable<Varchar>,
#[max_length = 255]
description -> Nullable<Varchar>,
created_at -> Timestamp,
metadata -> Nullable<Json>,
connector_customer -> Nullable<Jsonb>,
modified_at -> Timestamp,
#[max_length = 64]
default_payment_method_id -> Nullable<Varchar>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
version -> ApiVersion,
tax_registration_id -> Nullable<Bytea>,
#[max_length = 255]
created_by -> Nullable<Varchar>,
#[max_length = 255]
last_modified_by -> Nullable<Varchar>,
#[max_length = 64]
merchant_reference_id -> Nullable<Varchar>,
default_billing_address -> Nullable<Bytea>,
default_shipping_address -> Nullable<Bytea>,
status -> Nullable<DeleteStatus>,
#[max_length = 64]
id -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dashboard_metadata (id) {
id -> Int4,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
org_id -> Varchar,
data_key -> DashboardMetadata,
data_value -> Json,
#[max_length = 64]
created_by -> Varchar,
created_at -> Timestamp,
#[max_length = 64]
last_modified_by -> Varchar,
last_modified_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dispute (dispute_id) {
#[max_length = 64]
dispute_id -> Varchar,
#[max_length = 255]
amount -> Varchar,
#[max_length = 255]
currency -> Varchar,
dispute_stage -> DisputeStage,
dispute_status -> DisputeStatus,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
connector_status -> Varchar,
#[max_length = 255]
connector_dispute_id -> Varchar,
#[max_length = 255]
connector_reason -> Nullable<Varchar>,
#[max_length = 255]
connector_reason_code -> Nullable<Varchar>,
challenge_required_by -> Nullable<Timestamp>,
connector_created_at -> Nullable<Timestamp>,
connector_updated_at -> Nullable<Timestamp>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 255]
connector -> Varchar,
evidence -> Jsonb,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
dispute_amount -> Int8,
#[max_length = 32]
organization_id -> Varchar,
dispute_currency -> Nullable<Currency>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dynamic_routing_stats (attempt_id, merchant_id) {
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
amount -> Int8,
#[max_length = 64]
success_based_routing_connector -> Varchar,
#[max_length = 64]
payment_connector -> Varchar,
currency -> Nullable<Currency>,
#[max_length = 64]
payment_method -> Nullable<Varchar>,
capture_method -> Nullable<CaptureMethod>,
authentication_type -> Nullable<AuthenticationType>,
payment_status -> AttemptStatus,
conclusive_classification -> SuccessBasedRoutingConclusiveState,
created_at -> Timestamp,
#[max_length = 64]
payment_method_type -> Nullable<Varchar>,
#[max_length = 64]
global_success_based_connector -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
events (event_id) {
#[max_length = 64]
event_id -> Varchar,
event_type -> EventType,
event_class -> EventClass,
is_webhook_notified -> Bool,
#[max_length = 64]
primary_object_id -> Varchar,
primary_object_type -> EventObjectType,
created_at -> Timestamp,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
business_profile_id -> Nullable<Varchar>,
primary_object_created_at -> Nullable<Timestamp>,
#[max_length = 64]
idempotent_event_id -> Nullable<Varchar>,
#[max_length = 64]
initial_attempt_id -> Nullable<Varchar>,
request -> Nullable<Bytea>,
response -> Nullable<Bytea>,
delivery_attempt -> Nullable<WebhookDeliveryAttempt>,
metadata -> Nullable<Jsonb>,
is_overall_delivery_successful -> Nullable<Bool>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
file_metadata (file_id, merchant_id) {
#[max_length = 64]
file_id -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
file_name -> Nullable<Varchar>,
file_size -> Int4,
#[max_length = 255]
file_type -> Varchar,
#[max_length = 255]
provider_file_id -> Nullable<Varchar>,
#[max_length = 255]
file_upload_provider -> Nullable<Varchar>,
available -> Bool,
created_at -> Timestamp,
#[max_length = 255]
connector_label -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
fraud_check (frm_id, attempt_id, payment_id, merchant_id) {
#[max_length = 64]
frm_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
created_at -> Timestamp,
#[max_length = 255]
frm_name -> Varchar,
#[max_length = 255]
frm_transaction_id -> Nullable<Varchar>,
frm_transaction_type -> FraudCheckType,
frm_status -> FraudCheckStatus,
frm_score -> Nullable<Int4>,
frm_reason -> Nullable<Jsonb>,
#[max_length = 255]
frm_error -> Nullable<Varchar>,
payment_details -> Nullable<Jsonb>,
metadata -> Nullable<Jsonb>,
modified_at -> Timestamp,
#[max_length = 64]
last_step -> Varchar,
payment_capture_method -> Nullable<CaptureMethod>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
gateway_status_map (connector, flow, sub_flow, code, message) {
#[max_length = 64]
connector -> Varchar,
#[max_length = 64]
flow -> Varchar,
#[max_length = 64]
sub_flow -> Varchar,
#[max_length = 255]
code -> Varchar,
#[max_length = 1024]
message -> Varchar,
#[max_length = 64]
status -> Varchar,
#[max_length = 64]
router_error -> Nullable<Varchar>,
#[max_length = 64]
decision -> Varchar,
created_at -> Timestamp,
last_modified -> Timestamp,
step_up_possible -> Bool,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
#[max_length = 64]
error_category -> Nullable<Varchar>,
clear_pan_possible -> Bool,
feature_data -> Nullable<Jsonb>,
#[max_length = 64]
feature -> Nullable<Varchar>,
#[max_length = 64]
standardised_code -> Nullable<Varchar>,
#[max_length = 1024]
description -> Nullable<Varchar>,
#[max_length = 1024]
user_guidance_message -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
generic_link (link_id) {
#[max_length = 64]
link_id -> Varchar,
#[max_length = 64]
primary_reference -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
created_at -> Timestamp,
last_modified_at -> Timestamp,
expiry -> Timestamp,
link_data -> Jsonb,
link_status -> Jsonb,
link_type -> GenericLinkType,
url -> Text,
return_url -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
hyperswitch_ai_interaction (id, created_at) {
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
session_id -> Nullable<Varchar>,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
org_id -> Nullable<Varchar>,
#[max_length = 64]
role_id -> Nullable<Varchar>,
user_query -> Nullable<Bytea>,
response -> Nullable<Bytea>,
database_query -> Nullable<Text>,
#[max_length = 64]
interaction_status -> Nullable<Varchar>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
hyperswitch_ai_interaction_default (id, created_at) {
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
session_id -> Nullable<Varchar>,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
org_id -> Nullable<Varchar>,
#[max_length = 64]
role_id -> Nullable<Varchar>,
user_query -> Nullable<Bytea>,
response -> Nullable<Bytea>,
database_query -> Nullable<Text>,
#[max_length = 64]
interaction_status -> Nullable<Varchar>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
incremental_authorization (authorization_id, merchant_id) {
#[max_length = 64]
authorization_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
amount -> Int8,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
status -> Varchar,
#[max_length = 255]
error_code -> Nullable<Varchar>,
error_message -> Nullable<Text>,
#[max_length = 64]
connector_authorization_id -> Nullable<Varchar>,
previously_authorized_amount -> Int8,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
invoice (id) {
#[max_length = 64]
id -> Varchar,
#[max_length = 128]
subscription_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 128]
merchant_connector_id -> Varchar,
#[max_length = 64]
payment_intent_id -> Nullable<Varchar>,
#[max_length = 64]
payment_method_id -> Nullable<Varchar>,
#[max_length = 64]
customer_id -> Varchar,
amount -> Int8,
#[max_length = 3]
currency -> Varchar,
#[max_length = 64]
status -> Varchar,
#[max_length = 128]
provider_name -> Varchar,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
connector_invoice_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
locker_mock_up (id) {
id -> Int4,
#[max_length = 255]
card_id -> Varchar,
#[max_length = 255]
external_id -> Varchar,
#[max_length = 255]
card_fingerprint -> Varchar,
#[max_length = 255]
card_global_fingerprint -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
card_number -> Varchar,
#[max_length = 255]
card_exp_year -> Varchar,
#[max_length = 255]
card_exp_month -> Varchar,
#[max_length = 255]
name_on_card -> Nullable<Varchar>,
#[max_length = 255]
nickname -> Nullable<Varchar>,
#[max_length = 255]
customer_id -> Nullable<Varchar>,
duplicate -> Nullable<Bool>,
#[max_length = 8]
card_cvc -> Nullable<Varchar>,
#[max_length = 64]
payment_method_id -> Nullable<Varchar>,
enc_card_data -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
mandate (mandate_id) {
#[max_length = 64]
mandate_id -> Varchar,
#[max_length = 64]
customer_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_method_id -> Varchar,
mandate_status -> MandateStatus,
mandate_type -> MandateType,
customer_accepted_at -> Nullable<Timestamp>,
#[max_length = 64]
customer_ip_address -> Nullable<Varchar>,
#[max_length = 255]
customer_user_agent -> Nullable<Varchar>,
#[max_length = 128]
network_transaction_id -> Nullable<Varchar>,
#[max_length = 64]
previous_attempt_id -> Nullable<Varchar>,
created_at -> Timestamp,
mandate_amount -> Nullable<Int8>,
mandate_currency -> Nullable<Currency>,
amount_captured -> Nullable<Int8>,
#[max_length = 64]
connector -> Varchar,
#[max_length = 128]
connector_mandate_id -> Nullable<Varchar>,
start_date -> Nullable<Timestamp>,
end_date -> Nullable<Timestamp>,
metadata -> Nullable<Jsonb>,
connector_mandate_ids -> Nullable<Jsonb>,
#[max_length = 64]
original_payment_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
#[max_length = 2048]
customer_user_agent_extended -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_account (id) {
merchant_name -> Nullable<Bytea>,
merchant_details -> Nullable<Bytea>,
#[max_length = 128]
publishable_key -> Nullable<Varchar>,
storage_scheme -> MerchantStorageScheme,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 32]
organization_id -> Varchar,
recon_status -> ReconStatus,
version -> ApiVersion,
is_platform_account -> Bool,
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
product_type -> Nullable<Varchar>,
#[max_length = 64]
merchant_account_type -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_connector_account (id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
connector_name -> Varchar,
connector_account_details -> Bytea,
disabled -> Nullable<Bool>,
payment_methods_enabled -> Nullable<Array<Nullable<Json>>>,
connector_type -> ConnectorType,
metadata -> Nullable<Jsonb>,
#[max_length = 255]
connector_label -> Nullable<Varchar>,
created_at -> Timestamp,
modified_at -> Timestamp,
connector_webhook_details -> Nullable<Jsonb>,
frm_config -> Nullable<Array<Nullable<Jsonb>>>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
pm_auth_config -> Nullable<Jsonb>,
status -> ConnectorStatus,
additional_merchant_data -> Nullable<Bytea>,
connector_wallets_details -> Nullable<Bytea>,
version -> ApiVersion,
#[max_length = 64]
id -> Varchar,
feature_metadata -> Nullable<Jsonb>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_key_store (merchant_id) {
#[max_length = 64]
merchant_id -> Varchar,
key -> Bytea,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
organization (id) {
organization_details -> Nullable<Jsonb>,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 32]
id -> Varchar,
organization_name -> Nullable<Text>,
version -> ApiVersion,
#[max_length = 64]
organization_type -> Nullable<Varchar>,
#[max_length = 64]
platform_merchant_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_attempt (id) {
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
status -> AttemptStatus,
#[max_length = 64]
connector -> Nullable<Varchar>,
error_message -> Nullable<Text>,
surcharge_amount -> Nullable<Int8>,
#[max_length = 64]
payment_method_id -> Nullable<Varchar>,
authentication_type -> Nullable<AuthenticationType>,
created_at -> Timestamp,
modified_at -> Timestamp,
last_synced -> Nullable<Timestamp>,
#[max_length = 255]
cancellation_reason -> Nullable<Varchar>,
amount_to_capture -> Nullable<Int8>,
browser_info -> Nullable<Jsonb>,
#[max_length = 255]
error_code -> Nullable<Varchar>,
#[max_length = 128]
payment_token -> Nullable<Varchar>,
connector_metadata -> Nullable<Jsonb>,
#[max_length = 50]
payment_experience -> Nullable<Varchar>,
payment_method_data -> Nullable<Jsonb>,
preprocessing_step_id -> Nullable<Varchar>,
error_reason -> Nullable<Text>,
multiple_capture_count -> Nullable<Int2>,
#[max_length = 128]
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/routing_algorithm.rs | crates/diesel_models/src/routing_algorithm.rs | use common_utils::id_type;
use diesel::{Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use crate::{enums, schema::routing_algorithm};
#[derive(Clone, Debug, Identifiable, Insertable, Queryable, Selectable, Serialize, Deserialize)]
#[diesel(table_name = routing_algorithm, primary_key(algorithm_id), check_for_backend(diesel::pg::Pg))]
pub struct RoutingAlgorithm {
pub algorithm_id: id_type::RoutingId,
pub profile_id: id_type::ProfileId,
pub merchant_id: id_type::MerchantId,
pub name: String,
pub description: Option<String>,
pub kind: enums::RoutingAlgorithmKind,
pub algorithm_data: serde_json::Value,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub algorithm_for: enums::TransactionType,
pub decision_engine_routing_id: Option<String>,
}
pub struct RoutingAlgorithmMetadata {
pub algorithm_id: id_type::RoutingId,
pub name: String,
pub description: Option<String>,
pub kind: enums::RoutingAlgorithmKind,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub algorithm_for: enums::TransactionType,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RoutingProfileMetadata {
pub profile_id: id_type::ProfileId,
pub algorithm_id: id_type::RoutingId,
pub name: String,
pub description: Option<String>,
pub kind: enums::RoutingAlgorithmKind,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub algorithm_for: enums::TransactionType,
}
impl RoutingProfileMetadata {
pub fn metadata_is_advanced_rule_for_payments(&self) -> bool {
matches!(self.kind, enums::RoutingAlgorithmKind::Advanced)
&& matches!(self.algorithm_for, enums::TransactionType::Payment)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/configs.rs | crates/diesel_models/src/configs.rs | use std::convert::From;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use crate::schema::configs;
#[derive(Default, Clone, Debug, Insertable, Serialize, Deserialize)]
#[diesel(table_name = configs)]
pub struct ConfigNew {
pub key: String,
pub config: String,
}
#[derive(Default, Clone, Debug, Identifiable, Queryable, Selectable, Deserialize, Serialize)]
#[diesel(table_name = configs, primary_key(key), check_for_backend(diesel::pg::Pg))]
pub struct Config {
pub key: String,
pub config: String,
}
#[derive(Debug)]
pub enum ConfigUpdate {
Update { config: Option<String> },
}
#[derive(Clone, Debug, AsChangeset, Default)]
#[diesel(table_name = configs)]
pub struct ConfigUpdateInternal {
config: Option<String>,
}
impl ConfigUpdateInternal {
pub fn create_config(self, source: Config) -> Config {
Config { ..source }
}
}
impl From<ConfigUpdate> for ConfigUpdateInternal {
fn from(config_update: ConfigUpdate) -> Self {
match config_update {
ConfigUpdate::Update { config } => Self { config },
}
}
}
impl From<ConfigNew> for Config {
fn from(config_new: ConfigNew) -> Self {
Self {
key: config_new.key,
config: config_new.config,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.